湖南大學ACM程序設計新生杯大賽(同步賽)B - Build
阿新 • • 發佈:2017-12-24
res continue lld -h pair () edge ted lines
題目描述
In country A, some roads are to be built to connect the cities。However, due to limited funds, only some roads can be built.That is to say,if the limit is 100$, only roads whose cost are no more than 100$ can be built.
Now give you n cities, m roads and the cost of each road wi (i=1..m). There are q queries, for each query there is a number k, represent the limit, you need to output the maximum number of pairs of cities that can reach each other.
輸入描述:
The first line consist of two integers, n,m, n the number of cities and m the number of roads. The next m lines , each line has three integers a,b,w, represent that you can bulid a road between city a and city b with cost w.
The next line an integer q, the number of querries. The next q lines each an integer k ,the limit of the fund.n<10000, m < 10000, k < 10000, q<10000;
輸出描述:
For each querry ,you should output the anwser.示例1
輸入
3 2 1 2 1 2 3 2 1 2
輸出
3
題解
並查集。
按邊排序做並查集,處理好每一條邊加進去之後的答案。每次詢問,找到符合要求的最後一條邊權加入後的答案。
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn = 500000 + 10; int f[maxn]; int c[maxn]; long long A; int n, m; struct Edge { int a, b, c; }e[maxn]; long long ans[maxn]; bool cmp(Edge &a , Edge &b) { return a.c < b.c; } int Find(int x) { if(x != f[x]) f[x] = Find(f[x]); return f[x]; } int main() { while(~scanf("%d%d", &n, &m)) { for(int i = 1; i <= n; i ++) { f[i] = i; c[i] = 1; } A = 0; for(int i = 1; i <= m; i ++) { scanf("%d%d%d", &e[i].a, &e[i].b, &e[i].c); ans[i] = 0; } sort(e + 1, e + 1 + m, cmp); for(int i = 1; i <= m; i ++) { int fx = Find(e[i].a); int fy = Find(e[i].b); if(fx == fy) { ans[i] = A; continue; } A = A + c[fx] * c[fy]; f[fx] = fy; c[fy] += c[fx]; ans[i] = A; } int Q; scanf("%d", &Q); while(Q --) { int x; scanf("%d", &x); int L = 1, R = m, p = 0; while(L <= R) { int mid = (L + R) / 2; if(e[mid].c <= x) p = mid, L = mid + 1; else R = mid - 1; } printf("%lld\n", ans[p]); } } return 0; }
湖南大學ACM程序設計新生杯大賽(同步賽)B - Build