http://acm.hdu.edu.cn/showproblem.php?pid=3938
10 10 10 7 2 1 6 8 3 4 5 8 5 8 2 2 8 9 6 4 5 2 1 5 8 10 5 7 3 7 7 8 8 10 6 1 5 9 1 8 2 7 6
36 13 1 13 36 1 36 2 16 13
题意:给出一个连通图,以及每条路径的长度,定义从u走到v的所有边的最长边作为消耗的能量,q次询问,每次给出一个L能量,问存在多少这样的<u,v>路径对;
分析:很明显是并查集,但是每询问一次就做一次并查集肯定会超时,所以应采用离线算法,先把所有答案全求出来,然后一块输出;首先把边权从小到大排序,然后把询问也从小到大排序,对于每次询问,只加入小于询问的边到一个集合中,用h数组记录每个集合中的元素,sum记录当加完这条边后此时的u,v点对数目;
程序:
#pragma comment(linker, "/STACK:1024000000,1024000000") #include"stdio.h" #include"string.h" #include"iostream" #include"map" #include"string" #include"queue" #include"stdlib.h" #include"math.h" #include"algorithm" #include"vector" #define M 100009 #define eps 1e-10 #define inf 1000000000 #define mod 1000000000 #define INF 1000000000 using namespace std; struct node { int u,v,w; }e[M*5],q[M]; int f[M],h[M]; __int64 sum,ans[M]; int cmp(node a,node b) { return a.w<b.w; } int finde(int x) { if(x!=f[x]) f[x]=finde(f[x]); return f[x]; } void make(int a,int b) { int x=finde(a); int y=finde(b); if(x==y)return; else if(x>y) { f[x]=y; int tt=h[y]; h[y]+=h[x]; sum+=h[y]*(h[y]-1)/2-h[x]*(h[x]-1)/2-tt*(tt-1)/2; } else { f[y]=x; int tt=h[x]; h[x]+=h[y]; sum+=h[x]*(h[x]-1)/2-h[y]*(h[y]-1)/2-tt*(tt-1)/2; } } int main() { int n,m,k,i; while(scanf("%d%d%d",&n,&m,&k)!=-1) { for(i=0;i<m;i++) scanf("%d%d%d",&e[i].u,&e[i].v,&e[i].w); sort(e,e+m,cmp); for(i=0;i<k;i++) { scanf("%d",&q[i].w); q[i].u=i; } sort(q,q+k,cmp); for(i=1;i<=n;i++) { f[i]=i;h[i]=1; } sum=0; int j=0; for(i=0;i<k;i++) { while(j<m&&e[j].w<=q[i].w) { make(e[j].u,e[j].v); j++; } ans[q[i].u]=sum; } for(i=0;i<k;i++) printf("%I64d\n",ans[i]); } return 0; }