hdu 5441 Travel(Kruskal+离线)

题目链接: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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值