题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5441
题意:
给定N个顶点,M条边的一个无向图,Q个询问。对于每个询问x,从a,b的路径上各边的最大权值小于x,可以记为有序对<a,b>, 求这个图里面有多少个这样的有序对。
解题思路:kruskal思想+离线。首先把边从小到大排序,对于某个限制limit,如果边小于等于limit,则表示这条边是符合要求的,用并查集加入到连通块去,并且假设还要记得更新点对的个数,比如加入的这条边的两个顶点(u,v),它们所属的连通块的个数为sum1和sum2,则两个连通块合并后点对增加了sum1*sum2个。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
struct Edge
{
int u,v,d;
}edge[100005];
struct Query
{
int d,idx;
}que[5005];
int n,m,q,fa[20005],sum[20005];
int ans[5005],tot;
bool cmp(Edge a,Edge b)
{
return a.d < b.d;
}
bool cmp1(Query a,Query b)
{
return a.d < b.d;
}
int find(int x)
{
if(fa[x] == x) return x;
return fa[x] = find(fa[x]);
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d%d",&n,&m,&q);
for(int i = 1; i <= n; i++)
{
fa[i] = i;
sum[i] = 1;
}
for(int i = 1; i <= m; i++)
scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].d);
for(int i = 1; i <= q; i++)
{
scanf("%d",&que[i].d);
que[i].idx = i;
}
sort(edge+1,edge+1+m,cmp);
sort(que+1,que+1+q,cmp1);
int cnt = 1;
tot = 0;
for(int i = 1; i <= m; i++)
{
int u = edge[i].u;
int v = edge[i].v;
int fu = find(u);
int fv = find(v);
while(que[cnt].d < edge[i].d && cnt <= q)
{
ans[que[cnt].idx] = tot;
cnt++;
}
ans[que[cnt].idx] = tot;
if(fu != fv)
{
fa[fv] = fu;
tot += sum[fu] * sum[fv];
sum[fu] += sum[fv];
ans[que[cnt].idx] = tot;
}
}
for(int i = cnt + 1; i <= q; i++)
ans[que[i].idx] = tot;
for(int i = 1; i <= q; i++)
printf("%d\n",2*ans[i]);
}
return 0;
}