2015 ACM/ICPC Asia Regional Changchun Online Pro 1005 Travel (Krsukal变形) Travel
Time Limit: 1500/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 46 Accepted Submission(s): 20
Problem Description
Jack likes to travel around the world, but he doesn’t like to wait. Now, he is traveling in the Undirected Kingdom. There are m
bidirectional roads connecting the cities. Jack hates waiting too long
on the bus, but he can rest at every city. Jack can only stand staying
on the bus for a limited time and will go berserk after that. Assuming
you know the time it takes to go from one city to another and that the
time Jack can stand staying on a bus is b without going berserk?
Input
The first line contains one integer x is the time limit before Jack goes berserk.
Output
You should print b must be different cities.
Sample Input
1
5 5 3
2 3 6334
1 5 15724
3 5 5705
4 3 12382
1 3 21726
6000
10000
13000
Sample Output
2
6
12
类似Krsukal。首先确认一个事实,等待时间长的点对一定包含等待时间短的。
把询问离线然后排序,把边按照权值排序,每次只考虑比上次等待时间长,比这次等待时间短的边,用并查集维护连通分量的总个数。
#include<bits/stdc++.h> using namespace std; const int maxq = 5e3+5; int Qry[maxq]; long long ans[maxq]; bool cmp(int a,int b) { return Qry[a] < Qry[b]; } int rk[maxq]; int n,m,q; const int maxm = 1e5+5,maxn = 2e4+5; struct Edge { int u,v,w; bool operator < (const Edge &rh) const { return w < rh.w; } void IN() { scanf("%d%d%d",&u,&v,&w); } }edges[maxm]; int pa[maxn],cnt[maxn]; int fdst(int x) { return x==pa[x]?x:pa[x]=fdst(pa[x]); } int main() { //freopen("in.txt","r",stdin); int T; scanf("%d",&T); while(T--){ scanf("%d%d%d",&n,&m,&q); for(int i = 0; i < m ;i++){ edges[i].IN(); } for(int i = 0; i < q; i++){ rk[i] = i; scanf("%I64d",Qry+i); } sort(rk,rk+q,cmp); sort(edges,edges+m); for(int i = 1; i <= n; i++) pa[i] = i,cnt[i] = 1; long long cur = 0; for(int i = 0,j = 0; i < q; i++){ int id = rk[i]; int cq = Qry[id]; while(j < m && edges[j].w <= cq){ int u = fdst(edges[j].u),v = fdst(edges[j].v); if(u != v){ pa[u] = v; cur += 2LL*cnt[u]*cnt[v]; cnt[v] += cnt[u]; } j++; } ans[id] = cur; } for(int i = 0; i < q; i++){ printf("%I64d ",ans[i]); } } return 0; }