您的位置:首页 > 其它

PAT-A 1034. Head of a Gang (dfs)

2016-11-24 17:12 316 查看
题目链接:https://www.patest.cn/contests/pat-a-practise/1034

刚开始用并查集发现不太好处理。。用搜索就好做多了。

注意虽然路径数最多1000,但节点数可能2000,所以数组要开大不然段错误。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
#include <vector>
using namespace std;
int g[2010][2010], wei[2010], vis[2010];
int id;
int cnt, tot;
void dfs(int s) {
for(int i = 1; i < id; i++) {
if(g[s][i] != -1) {
tot += g[s][i];
g[s][i] = -1;
if(!vis[i]) {
cnt++;
vis[i] = 1;
dfs(i);
}
}
}
}
map<string, int> m;
int main() {
memset(g, -1, sizeof g);
int n, k;
scanf("%d %d", &n, &k);
string a, b;
int w;
id = 1;
for(int i = 0; i < n; i++) {
cin >> a >> b >> w;
if(!m.count(a)) m[a] = id++;
if(!m.count(b)) m[b] = id++; //哈希
g[m[a]][m[b]] = w;
wei[m[a]] += w;
wei[m[b]] += w;
}
vector<pair<string, int> > ans;
for(int i = 1; i < id; i++) {
if(!vis[i]) {
vis[i] = 1;
cnt = 1;
tot = 0;
dfs(i);
int maxn = 0, maxnid = 0;
for(int j = 1; j < id; j++) {
if(vis[j] == 1) {
vis[j] = -1;
if(maxn < wei[j]) {
maxn = wei[j];
maxnid = j;
}
}
}
if(cnt > 2 && tot > k) {
for(auto it = m.begin(); it != m.end(); it++) {
if(it->second == maxnid) {
ans.push_back(make_pair(it->first, cnt));
break;
}
}
}
}
}
sort(ans.begin(), ans.end());
cout << ans.size() << endl;
for(int i = 0; i < ans.size(); i++) {
cout << ans[i].first << " " << ans[i].second << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: