关键要点:
- 将字符串作为的key转化为int型的key,此处用的是getnum()函数
- 用宽度优先(或深度优先)探索整个图有多少连通分量,其中,人员数目及权重符合的即为gang
- 用map存储gang,利用其自动排序的特性。
#include<cstdio>
#include<queue>
#include<vector>
#include<iostream>
#include<map>
#include<string>
using namespace std;
const int maxn = 1010;
const int maxc = 30000;
int getnum(string str) {
int temp = 0;
for (int i = 0; i < 3; i++) {
temp = temp * 26 + str[i] - 'A';
}
return temp;
}
int BFS(int a, vector<int> people[], int weight[], bool inq[], int &head, int &pnum) {
queue<int> q;
q.push(a);
inq[a] = true;
head = a;
pnum = 0;
int totalweight = 0;
while(!q.empty()) {
int temp = q.front();
totalweight += weight[temp];
pnum++;
q.pop();
if (weight[head] < weight[temp]) {
head = temp;
}
for (int i = 0; i < people[temp].size(); i++) {
int temp2 = people[temp][i];
if (inq[temp2] == false) {
q.push(temp2);
inq[temp2] = true;
}
}
}
return totalweight / 2;
}
void numToChar(string &a, int b) {
a[0] = b / 26 / 26 + 'A';
a[1] = (b - (a[0] - 'A') * 26 * 26) / 26 + 'A';
a[2] = (b - (a[0] - 'A') * 26 * 26 - (a[1] - 'A') * 26) + 'A';
a[3] = '\0';
}
int main() {
int N, K;
string a, b;
int anum, bnum;
int tempTime;
vector<int> people[maxc];
int weight[maxc] = {0};
scanf("%d %d", &N, &K);
vector<int> itv;
for (int i = 0; i < N; i++) {
cin >> a >> b >> tempTime;
// printf("%s %s %d\n", a.c_str(), b.c_str(), tempTime);
anum = getnum(a);
bnum = getnum(b);
weight[anum] += tempTime;
weight[bnum] += tempTime;
int j = 0;
for (j = 0; j < people[anum].size(); j++) {
if (people[anum][j] == bnum) break;
}
if (j == people[anum].size()) {
people[anum].push_back(bnum);
people[bnum].push_back(anum);
}
}
bool inq[maxc] = {false};
queue<int> q;
map<int, int> gang;
int totalweight, head, pnum;
for (int i = 0; i < maxc; i++) {
if (weight[i] != 0 && inq[i] == false) {
inq[i] = true;
totalweight = BFS(i, people, weight, inq, head, pnum);
if (totalweight > K && pnum > 2) {
gang[head] = pnum;
}
}
}
printf("%d\n", gang.size());
for (map<int, int>::iterator it = gang.begin(); it != gang.end(); it++) {
numToChar(a, it->first);
printf("%s %d\n", a.c_str(), it->second);
}
return 0;
}