当前位置:网站首页>并查集学习
并查集学习
2022-08-10 08:46:00 【Aidan 347】
Example
input
1 5 5 3 1 2 2 2 3 3 3 4 1 4 5 1 5 1 3 3 2 1output
2 6 10
思路:离线并查集
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
#include <cmath>
#include <map>
#include <set>
using namespace std;
#define mst(x, y) memset(x, y, sizeof x);
#define X first
#define Y second
#define int long long
#define FAST ios::sync_with_stdio(false), cin.tie(0), cout.tie(0)
const int N = 200010, INF = 0x3f3f3f3f, EPS = 1e-8;
typedef pair<int, int> PII;
int n, m, Q, t;
int ans[N];
int p[N];
int cnt[N];
struct Node
{
int l, r, w;
} node[N];
struct QUE
{
int id, c;
} que[N];
bool cmp1(Node a, Node b)
{
return a.w > b.w;
}
bool cmp2(QUE a, QUE b)
{
return a.c > b.c;
}
int find(int x) // 并查集
{
if (p[x] != x)
p[x] = find(p[x]);
return p[x];
}
signed main()
{
FAST;
cin >> t;
while (t--)
{
cin >> n >> m >> Q;
for (int i = 1; i <= n; i++)
{
p[i] = i;
cnt[i] = 1;
}
for (int i = 1, a, b, c; i <= m; i++)
{
cin >> a >> b >> c;
node[i] = {a, b, c};
}
for (int i = 1, a; i <= Q; i++)
{
cin >> a;
que[i] = {i, a};
}
sort(node + 1, node + 1 + m, cmp1);
sort(que + 1, que + 1 + Q, cmp2);
int j = 1, sum = 0;
for (int i = 1; i <= Q; i++)
{
int q = que[i].c, id = que[i].id;
while (j <= m && node[j].w >= q)
{
int pa = find(node[j].l), pb = find(node[j].r);
if (pa != pb)
{
sum += cnt[pa] * cnt[pb];
p[pa] = pb;
cnt[pb] += cnt[pa];
}
j++;
}
ans[id] = sum;
}
for (int i = 1; i <= Q; i++)
{
cout << ans[i] << endl;
}
}
system("pause");
return 0;
}
边栏推荐
猜你喜欢
随机推荐
硬件工程师90天学习资料及笔记汇总20220730
CTFSHOW七夕杯web
解决win10win7win8系统找不到指定的模块,注册不了大漠插件的问题
第十六天&charles的基本操作
1499. The maximum pile.then/deque
js函数聚合的三种实现方式
00后女孩月薪3200,3年买两套房,这个程序员变现新风口千万要把握住
本地生活商家如何通过短视频赛道,提升销量曝光量?
【API架构】使用 JSON API 的好处
Delphi实现的一个文件在线查询显示下载功能
Spotify expresses its architectural design using the C4 model
Hugo NexT主题升级记录
不想再干会计了,蝶变向新,勇往直前,最后成功通过转行测试实现月薪翻倍~
DAY25: Logic Vulnerability
Different command line styles
Unity—UGUI控件
【API架构】REST API 行业辩论:OData vs GraphQL vs ORDS
J9数字论:关于DAO 特点的宏观分析
ARM Architecture 3: Addressing and Exception Handling of ARM Instructions
MySQL的用户临时表与内部临时表