|洛谷|并查集|P1525 关押罪犯

时间:2022-01-22 14:36:46

https://www.luogu.org/problem/show?pid=1525

方法一:拆点,即一个点拆为一个实结点和一个虚结点

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#define ms(i,j) memset(i,j, sizeof i);
using namespace std;
struct node
{
int x;
int y;
int v;
bool operator <(node const &a) const//重载符号以排序
{
return v>a.v;
}
}zf[100005];//罪犯
int n,m;
int father[40005];//并查集
int find(int x)//并查集找根+路径压缩
{
if (father[x]==x) return x;
return father[x] = find(father[x]);
}
int merge(int x, int y)//并查集合并
{
int x1 = find(x);
int y1 = find(y);
father[y1] = x1;
}
int main()
{
scanf("%d%d", &n, &m);
for (int i=1;i<=2*n;i++) father[i] = i;
for (int i=1;i<=m;i++) scanf("%d%d%d", &zf[i].x, &zf[i].y, &zf[i].v);//输入
sort(zf+1, zf+1+m);//排序
for (int i=1;i<=m;i++)
{
int x1 = find(zf[i].x);
int y1 = find(zf[i].y);
if (x1!=y1)//不在同一*
{
merge(zf[i].x, zf[i].y+n);
merge(zf[i].y, zf[i].x+n);//合并虚结点
} else {printf("%d\n", zf[i].v);return 0;}
}
printf("%d\n", 0);
return 0;
}


方法二:先按权值从大到小排序边然后依次使边的两个点分开

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<queue>
#define ms(i,j) memset(i,j, sizeof i);
using namespace std;
struct ed
{
int x,y,v;
}edge[100005];
int father[20005];
int find(int x)
{
if (father[x]!=x) return father[x] = find(father[x]);
else return father[x];
}
int merge(int x, int y)
{
father[x] = y;
}
bool cmp(ed const &a, ed const &b)
{
return a.v>b.v;
}
int n,m;
int last[20005];//上一个敌人
int main()
{
scanf("%d%d", &n ,&m);
for (int i=1;i<=n;i++) father[i] = i;
for (int i=1;i<=m;i++)
{
scanf("%d%d%d", &edge[i].x, &edge[i].y, &edge[i].v);
}
sort(edge+1, edge+1+m, cmp);
ms(last,-1);
for (int i=1;i<=m;i++)
{
int a = find(edge[i].x);
int b = find(edge[i].y);
if (a==b)
{
printf("%d\n", edge[i].v);
return 0;
}
if (last[b]>0) merge(a,find(last[b]));
if (last[a]>0) merge(b,find(last[a]));
last[edge[i].x] = b, last[edge[i].y] = a;
}
printf("0\n");
return 0;
}


方法三:带权并查集

#include<cstdio>    
#include<algorithm>
#include<cstring>
#include<queue>
#define ms(i,j) memset(i,j, sizeof i);
using namespace std;
struct node
{
int x;
int y;
int v;
bool operator <(node const &a) const//重载符号以排序
{
return v>a.v;
}
}zf[100005];//罪犯
int n,m;
int father[20005];//并查集
int r[20005];//指出的权值 1表示在同一* 0表示不在同一*
int find(int x)//并查集找根+路径压缩
{
if (father[x]==x) return x;
int tmp = father[x];
father[x] = find(father[x]);
r[x] = (r[x]+r[tmp])%2;
return father[x];
}
int main()
{
scanf("%d%d", &n, &m);
for (int i=1;i<=n;i++) father[i] = i;
for (int i=1;i<=m;i++) scanf("%d%d%d", &zf[i].x, &zf[i].y, &zf[i].v);//输入
sort(zf+1, zf+1+m);//排序
for (int i=1;i<=m;i++)
{
int a = zf[i].x, b = zf[i].y, x = find(a), y = find(b);
if (x!=y)
{
father[x] = y;
r[x] = (r[b]-r[a]+1+666)%2;
} else
{
if ((r[b]-r[a]+1)%2) {printf("%d\n", zf[i].v); return 0;}
}
}
printf("%d\n", 0);
return 0;
}