版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
1、1034 Head of a Gang (30 分)
题目大意:给出一张图,得出每个连通分量,其点中连接边的权和最大的点为head,点的数量大于k,则输出其head及点数;
将每个点的字符串与整型字符对应,在需要将字符串储存进结果map进行输出时再使用inttostr进行转化;DFS整张图,得到几个连通分量,在输入过程中顺便完成每个点权值的计算;在DFS过程中将遍历过的边重新赋值为0,以免在遍历到下一个点(或其他点)时重复计算;
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
int he[2001][2001], edge[2001][2001], weight[2001], k;
bool visit[2001];
map<string, int> strtoint;
map<int, string> inttostr;
map<string, int> final_;
int no=1;
int conser(string s) {
if (strtoint[s]==0) {
strtoint[s] = no;
inttostr[no] = s;
return no++;
}
else{
return strtoint[s];
}
}
void DFS(int u, int &head, int &number, int &totalweight) {
visit[u] = true;
number++;
for (int i = 1; i < no; i++) {
if (weight[head] < weight[u]) {
head = u;
}
}
for (int i = 1; i < no; i++) {
if (edge[u][i] > 0) {
totalweight += edge[u][i];
edge[u][i] = edge[i][u] = 0;
if (visit[i] == false) DFS(i, head, number, totalweight);
}
}
}
void trace() {
for (int i = 1; i < no; i++) {
if (visit[i] == false) {
int head = i, number = 0, totalweight = 0;
DFS(i, head, number, totalweight);
if (number > 2 && totalweight > k) {
final_[inttostr[head]] = number;
}
}
}
}
int main() {
int n, w;
scanf("%d %d", &n, &k);
string s1, s2;
for (int i = 0; i < n; i++) {
cin>>s1>>s2>>w;
int e = conser(s1);
int r = conser(s2);
weight[e] += w;
weight[r] += w;
edge[e][r] += w;
edge[r][e] += w;
}
trace();
printf("%d\n", final_.size());
for (auto it = final_.begin(); it != final_.end(); it++) {
cout<<it->first<<" "<<it->second<<endl;
}
return 0;
}