题解 | #Head of a Gang#
Head of a Gang
https://www.nowcoder.com/practice/a31b1ea6c87647bc86e382acaf21c53b
另辟蹊径,不使用并查集实现,但效率低下,代码复杂,仅供参考
#include <iostream> #include <map> #include <vector> using namespace std; struct team { int totalScore; // 总分 int peopleNumber; // 群体人数 team(int totalScore, int peopleNumber) : totalScore(totalScore), peopleNumber(peopleNumber) {} }; struct people { string name; int score = 0; int teamNo; people(string name, int score, int teamNo) : name(name), score(score), teamNo(teamNo) {} }; vector<team> teams; vector<people> pp; int main() { int n, k; while (cin >> n >> k) { for (int i = 0; i < n; ++i) { string A, B; // 两名字 bool flagA = false, flagB = false; // 是否存在 int AteamNo, BteamNo; // A与B的团队编号 int time; // 通话时间 cin >> A >> B >> time; for (auto &it : pp) { // 对已存在的人加权重,并获取其团队编号 if (it.name == A) { flagA = true; it.score += time; AteamNo = it.teamNo; continue; } if (it.name == B) { flagB = true; it.score += time; BteamNo = it.teamNo; } } if (flagA && !flagB) { // A存在,B不存在,新建B将其加入A的团队,并更新团队信息 people peo = people(B, time, AteamNo); pp.push_back(peo); teams[AteamNo].totalScore += time; teams[AteamNo].peopleNumber++; } else if (!flagA && flagB) {// B存在,A不存在,新建将其加入B的团队,并更新团队信息 people peo = people(A, time, BteamNo); pp.push_back(peo); teams[BteamNo].totalScore += time; teams[BteamNo].peopleNumber++; } else if (!flagA && !flagB) { // A B都不存在,新建两个人,并新建一个团队,将其加入新团队 team tt(time, 2); teams.push_back(tt); people peoA = people(A, time, teams.size() - 1); people peoB = people(B, time, teams.size() - 1); pp.push_back(peoA); pp.push_back(peoB); } else { // AB都存在 // 需要检查其是否在两个不同的团队,若是,则将B合并至A,并更新团队信息(此处B的信息置位0,若使用删除,则团队整体位置会变动,出错) if (AteamNo != BteamNo) { teams[AteamNo].peopleNumber += teams[BteamNo].peopleNumber; teams[AteamNo].totalScore += teams[BteamNo].totalScore; for (auto &it : pp) { if (it.teamNo == BteamNo) { it.teamNo = AteamNo; } } teams[BteamNo].peopleNumber = 0; teams[BteamNo].totalScore = 0; } teams[AteamNo].totalScore += time; } } int quntiTotal = 0; // 符合条件的团伙个数 map<string, int> output; // 符合条件的人的信息 for (int i = 0; i < teams.size(); ++i) { if (teams[i].peopleNumber > 2 && teams[i].totalScore > k) { quntiTotal++; string name; int score = 0; for (auto &it : pp) { // 寻找该团队中,分数最高的人 if (it.teamNo == i) { if (it.score > score) { score = it.score; name = it.name; } } } output[name] = teams[i].peopleNumber; // 存入输出map } } if (output.size() == 0) { cout << 0 << endl; } else { cout << output.size() << endl; for (auto &it:output) { cout << it.first << " " << it.second << endl; } } teams.clear(); pp.clear(); } } // 64 位输出请用 printf("%lld")