标签:
题目链接:点击打开链接
思路:
题目要求有多少对点(a, b)使得a到b的最短路上最长边不超过x。 我们将边从小到大排序, 用并查集来维护关系, 这样, 对于当前加入集合的一条边(a, b),权值为c, 他就是当前集合的最长边, 那么不大于c的对数就是就是这两个集合的个数的组合。 预处理一下即可。
细节参见代码:
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> #include <string> #include <vector> #include <stack> #include <bitset> #include <cstdlib> #include <cmath> #include <set> #include <list> #include <deque> #include <map> #include <queue> #define Max(a,b) ((a)>(b)?(a):(b)) #define Min(a,b) ((a)<(b)?(a):(b)) using namespace std; typedef long long ll; typedef long double ld; const double eps = 1e-2; const double PI = acos(-1); const int mod = 1e9 + 7; const int INF = 0x3f3f3f3f; const int seed = 131; const ll INF64 = ll(1e18); const int maxn = 2e4 + 10; int n, m, p[maxn],cnt[maxn],a, b, c, q, ans[100009]; struct node { int a, b, c; node(int a=0, int b=0, int c=0):a(a), b(b), c(c) {} bool operator < (const node& rhs) const { return c < rhs.c; } }e[100009]; int _find(int x) { return p[x] == x ? x : p[x] = _find(p[x]); } int main() { int T; scanf("%d", &T); while(T--) { scanf("%d%d%d", &n, &m, &q); int maxv = -INF; for(int i = 1; i <= m; i++) { scanf("%d%d%d", &e[i].a, &e[i].b, &e[i].c); maxv = max(maxv, e[i].c); } sort(e+1, e+m+1); for(int i = 0; i <= maxv; i++) ans[i] = 0; for(int i = 1; i <= n; i++) p[i] = i, cnt[i] = 1; int last = 0, pos = 0; for(int i = 1; i <= m; i++) { int x = _find(e[i].a); int y = _find(e[i].b); if(x != y) { p[x] = y; ans[e[i].c] = last + cnt[x]*cnt[y]*2; for(int j = pos; j < e[i].c; j++) { ans[j] = last; } pos = e[i].c+1; cnt[y] += cnt[x]; last = ans[e[i].c]; } } for(int i = pos; i <= maxv; i++) ans[i] = last; while(q--) { scanf("%d", &a); if(a > maxv) printf("%d\n", ans[maxv]); else printf("%d\n", ans[a]); } } return 0; }
标签:
原文地址:http://blog.csdn.net/weizhuwyzc000/article/details/52078249