例题一:【模板】并查集 link
#include <bits/stdc++.h>
#define fre(x) freopen(#x".in","r",stdin),freopen(#x".out","w",stdout);
#define ll long long
using namespace std;
const int MAX = 2147483647;
const int N = 1e4 + 10;
int n, m, type, x, y, fa[N];
int find(int x) {
return x == fa[x]? x: fa[x] = find(fa[x]);}
void unionn(int u , int v)
{
int x = find(u), y = find(v);
if(x != y) fa[x] = y;
return ;
}
void check(int u , int v)
{
int x = find(u), y = find(v);
if(x != y) printf("N\n");
else printf("Y\n");
return ;
}
int main()
{
//fre();
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; i++) fa[i] = i;
for(int i = 1; i <= m; i++)
{
scanf("%d%d%d", &type, &x, &y);
if(type == 1) unionn(x , y);
else check(x , y);
}
return 0;
}
例题二:程序自动分析 link
思路:
这道题我们考虑用并查集来做。
关心 x=y,那只用将其合并到同一个集合中
x≠y反之亦然。
再来考虑一下判定是否满足怎么做?
想必大家都知道:
- 如果判断为x=y,但是两数不在同一集合,No
- 如果判断为x≠y,但是两数在同一集合,No
- 其他情况则为Yes
但是数据不是很友好,编号最大有 1 9 1^9 19,数组这样开一定会爆。
于是我们最后考虑用一下离散化缩小绝对大小变成相对大小。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define R register int
using namespace std;
inline int read()
{
int f=1,x=0; char ch=getchar();
while(ch<'0'||ch>'9'){
if(ch=='-') f=-1; ch=getchar();}
while(ch<='9'&&ch>='0') x=x*10+ch-'0',ch=getchar();
return f*x;
}
const int maxn=1000005;
struct data
{
int x,y,e