思路
这里因为涉及到边的权重,而且存在双向边,因此我们最好将图看成有向图,而且用邻接矩阵来存储比较好。那么数组开多大?这取决于可能有多少点,因为点的name是3位char(A-Z),因此总共可能有26x26x26种,真的要这么多吗?仔细看可以发现边总共只有N条,即使每条边的首末节点互不相同,那么也只有2N个,所以我们实际上只用开1000x2+10(10是为了防止溢出)。另一个难点是点的name对应到整形,自然地想法就是用map,但是我们最后输出的时候还要将index转成name所以,还要一个反向的map,这个map实际上可以用一个vector实现。然后就是dfs了,但是要注意的是就算下一个点已经访问过了,这条边的权重还是要算进去的,只是不继续dfs而已。
#include <cstdio>
#include <map>
#include <vector>
#include <string>
#include <iostream>
using namespace std;
int weight[2010], edges[2010][2010]={0}, visited[2010] = {0};
int calls, threthold, cnt = 0;
int Count, maxi, total, maxId;
map<string, int> m;
vector<string> ss, ans;//ss用来map index to string,ans存答案
bool cmp(string a, string b){
return a < b;
}
void dfs(int i){
Count++;
visited[i] = 1;
if(weight[i] > maxi){
maxi = weight[i];
maxId = i;
}
for(int j = 0; j < cnt; j++){
if(edges[i][j] > 0){
total += edges[i][j];
if(visited[j] == 0)
dfs(j);
}
}
}
void getAns(){
for(int i = 0; i < cnt; i++){
Count = 0; maxi = 0; total = 0;
if(visited[i] == 0)
dfs(i);
if(Count > 2 && total > threthold)
{
//将答案转成字符串存储
string s = ss[maxId] +" " + to_string(Count);
ans.push_back(s);
}
}
}
int main(){
scanf("%d%d", &calls, &threthold);
for(int i = 0; i < calls; i++){
getchar();
string from, to;
int w, f, t;//w为权重,f,t分别为边的首末节点
cin >> from >> to >> w;
//将string转化成int
if(m.find(from) != m.end())
f = m[from];
else{
m[from] = cnt;
f = cnt;
ss.push_back(from);
cnt++;
}
if(m.find(to) != m.end())
t = m[to];
else{
m[to] = cnt;
t = cnt;
ss.push_back(to);
cnt++;
}
edges[f][t] = w;
//更新点的权重
weight[f] += w;
weight[t] += w;
}
getAns();
//为了满足字典序,将答案进行排序
sort(ans.begin(), ans.end(), cmp);
printf("%lu\n", ans.size());
for(int i = 0; i < ans.size(); i++)
cout << ans[i] << endl;
return 0;
}