City (并查集 + 思维)

该博客介绍了如何使用图论中的并查集数据结构解决一类问题:给定一个图,每次根据询问摧毁边权值小于特定值的边,求剩余能够互相到达的点对数量。通过将边权值和k值排序,从大到小合并路径,计算贡献,最终得出答案。代码中展示了C++实现的AC代码,包括并查集的初始化、合并及查找操作,以及如何根据边权值动态更新答案。
摘要由CSDN通过智能技术生成

City

题目链接

题意 :
给出一个图,每次询问给出x ,每次将边权< x 的边摧毁,问还能互相到达的点的对数。

思路 :
将k值和边权排序,从大到小并查集不断加边,计算贡献即可。
AC代码 :


#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>

#define int long long
#define IOS ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
using namespace std;

typedef pair<int, int> PII;
const int N = 2e5 + 5;
pair<PII, int> a[N];
int pre[N], cnt[N];
int W[N], res[N]; //统计城市数
int n, m, q, ans = 0;
PII p;

bool cmp(pair<PII, int> x, pair<PII, int> y)
{
	return x.second < y.second;
}

int find(int x)
{
	if (pre[x] != x)
		pre[x] = find(pre[x]);
	return pre[x];
}

void merge(int a, int b)
{
	int x = find(a);
	int y = find(b);
	if (x != y)
	{
		pre[x] = y;
		ans = ans + cnt[x] * cnt[y];
		cnt[y] = cnt[x] + cnt[y];
		cnt[x] = 0;
	}
}
void init()
{
	ans = 0;
	for (int i = 1; i <= n; i++)
	{
		pre[i] = i;
		cnt[i] = 1;
	}
}

signed main()
{
	IOS;
	int t;
	cin >> t;
	while (t--)
	{
		cin >> n >> m >> q;
		init();
		for (int i = 1; i <= m; i++)
		{
			int x, y, w;
			cin >> x >> y >> w;
			p.first = x;
			p.second = y;
			a[i].first = p;
			a[i].second = w;
			W[i] = w;
		}
		sort(a + 1, a + 1 + m, cmp);
		for (int i = m; i >= 1; i--)
		{
			merge(a[i].first.first, a[i].first.second);
			res[i] = ans;
		}
		sort(W + 1, W + 1 + m);
		while (q--)
		{
			int x;
			cin >> x;
			if (x > a[m].second)
			{
				cout << 0 << endl;
			}
			else
			{
				int temp = lower_bound(W + 1, W + 1 + m, x) - W;
				cout << res[temp] << endl;
			}
		}
	}
	return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值