1034. Head of a Gang (30)
2017-04-09 09:36
148 查看
并查集
#include<cstdio> #include<vector> #include<map> #include<queue> #include<string> #include<iostream> #include<cstring> #include<algorithm> using namespace std; typedef long long LL; const int INF = 0x7FFFFFFF; const int maxn = 2e3 + 10; int n, k, fa[maxn], cnt[maxn], tot, z; int x[maxn], y[maxn], sum[maxn], p[maxn]; string s, t, w[maxn]; vector<string> ans; map<string, int> M; int get(int x) { return x == fa[x] ? x : fa[x] = get(fa[x]); } int main() { scanf("%d%d", &n, &k); for (int i = 0; i < n + n; i++) fa[i] = i; for (int i = 0; i < n; i++) { cin >> s >> t >> z; if (!M[s]) w[++tot] = s, M[s] = tot; if (!M[t]) w[++tot] = t, M[t] = tot; x[i] = M[s]; y[i] = M[t]; cnt[x[i]] += z; cnt[y[i]] += z; } for (int i = 0; i < n; i++) { int fx = get(x[i]), fy = get(y[i]); if (fx == fy) continue; if (cnt[fx]>cnt[fy]) fa[fy] = fx; else fa[fx] = fy; } for (int i = 1; i <= tot; i++) fa[i] = get(i), sum[fa[i]] += cnt[i], p[fa[i]]++; for (int i = 1; i <= tot; i++) if (sum[i] > 2*k&&p[i]>2) ans.push_back(w[i]); sort(ans.begin(), ans.end()); printf("%d\n", ans.size()); if (ans.size()) { for (int i = 0; i < ans.size(); i++) { cout << ans[i] << " " << p[M[ans[i]]] << endl; } } return 0; }
相关文章推荐
- PAT A1034. Head of a Gang (30)
- 1034. Head of a Gang (30)
- 1034. Head of a Gang (30) (我自己写的程序前后可能出现不合并的情况,参考程序好,简单实用)
- 1034. Head of a Gang (30)
- 1034. Head of a Gang (30)
- 1034. Head of a Gang (30)
- 1034. Head of a Gang (30)-PAT甲级真题(图的遍历dfs)
- PAT甲级 1034. Head of a Gang (30)
- PAT 1034. Head of a Gang (30) 并查集
- PAT 1034. Head of a Gang(30)
- 1034. Head of a Gang (30) -string离散化 -map应用 -并查集
- 1034. Head of a Gang (30)
- PAT-A-1034. Head of a Gang (30)
- 【PAT】【Advanced Level】1034. Head of a Gang (30)
- PAT - 甲级 - 1034. Head of a Gang (30)(DFS求连通块)
- 1034. Head of a Gang (30)
- Python实现Pat 1034. Head of a Gang (30)
- PAT (Advanced) 1034. Head of a Gang (30)
- 1034. Head of a Gang (30) -string离散化 -map应用 -并查集
- PAT甲级1034. Head of a Gang (30)