P1525 [NOIP2010 提高组] 关押罪犯
代码:
#include <cstdio>
#include <algorithm>
using namespace std;
struct data {int x,y,z;};//结构体便于排序的变换
data f[100005];
int n,m,a[20005],b[20005],i;
inline bool cmp(data a,data b)//重写cmp函数
{
return a.z>b.z;
}
inline int find(int x)
{
if(a[x]==x) return x;
a[x]=find(a[x]);
return a[x];
}
inline void ad(int x,int y)//合并
{
x=find(a[x]);
y=find(a[y]);
a[x]=y;
}
inline bool check(int x,int y)//查找
{
x=find(x);
y=find(y);
if(x==y) return true;
return false;
}
int main()
{
scanf("%d%d",&n,&m);
for(i=1;i<=n;i++) a[i]=i;
for(i=1;i<=m;i++)
scanf("%d%d%d",&f[i].x,&f[i].y,&f[i].z);
sort(f+1,f+m+1,cmp);//c党的优越感~
for(i=1;i<=m+1;i++)//为什么m+1呢?如果运行到m+1会输出0,想想为什么。
{
if(check(f[i].x,f[i].y)) {printf("%d",f[i].z);break;}//如果两个罪犯已经在同一监狱就输出 ,并退出
else
{
if(!b[f[i].x]) b[f[i].x]=f[i].y;//标记“敌人”
else {ad(b[f[i].x],f[i].y);}//将敌人的敌人合并
if(!b[f[i].y]) b[f[i].y]=f[i].x;
else {ad(b[f[i].y],f[i].x);}
}
}
return 0;
}
解析:
淳朴的并查集~但因为它们带有权值,因此排序是必须的,我们要尽可能让危害大的罪犯在两个监狱里。
那么,再结合敌人的敌人和自己在一个监狱的规律合并。
当查找时发现其中两个罪犯不可避免地碰撞到一起时,只能将其输出并结束。
还有一点很重要,就是没有冲突时一定输出0!!!
P3386 【模板】二分图最大匹配
代码:
#include <cstdio>
#include <vector>
const int maxn = 1005;
int n, m, t;
int mch[maxn], vistime[maxn];
std::vector<int> e[maxn];
bool dfs(const int u, const int tag);
int main() {
scanf("%d %d %d", &n, &m, &t);
for (int u, v; t; --t) {
scanf("%d %d", &u, &v);
e[u].push_back(v);
}
int ans = 0;
for (int i = 1; i <= n; ++i) if (dfs(i, i)) {
++ans;
}
printf("%d\n", ans);
}
bool dfs(const int u, const int tag) {
if (vistime[u] == tag) return false;
vistime[u] = tag;
for (auto v : e[u]) if ((mch[v] == 0) || dfs(mch[v], tag)) {
mch[v] = u;
return true;
}
return false;
}
解析:
匈牙利算法
P1129 [ZJOI2007] 矩阵游戏
代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
struct edge
{
int to,next;
}e[1000010];
int t,n,size,CommunismParty_cnt;
int head[1000010],match[1000010];
bool flag[1000010];
inline void EdgeAdd(int,int);
inline void Hungary();
inline bool find(int);
int main()
{
scanf("%d",&t);
for(int _=1;_<=t;_++)
{
scanf("%d",&n);
CommunismParty_cnt=0;
size=0;
memset(head,-1,sizeof(head));
memset(match,0,sizeof(match));
memset(e,0,sizeof(e));
for(int __=1;__<=n;__++)
{
for(int ___=1;___<=n;___++)
{
int CommunistYouthLeague_color;
scanf("%d",&CommunistYouthLeague_color);
if(CommunistYouthLeague_color==1)
{
EdgeAdd(__,___);
}
}
}
Hungary();
printf("%s\n",CommunismParty_cnt>=n?"Yes":"No");
}
return 0;
}
inline void EdgeAdd(int from,int to)
{
e[++size].to=to;
e[size].next=head[from];
head[from]=size;
}
inline void Hungary()
{
for(int _=1;_<=n;_++)
{
memset(flag,false,sizeof(flag));
if(find(_)==true)
{
CommunismParty_cnt++;
}
}
}
inline bool find(int from)
{
for(int _=head[from];_!=-1;_=e[_].next)
{
int to=e[_].to;
if(flag[to]==false)
{
flag[to]=true;
if(match[to]==0||find(match[to])==true)
{
match[to]=from;
return true;
}
}
}
return false;
}
解析:
把每一个点看做一条匹配边,把它的的行数和列数连一条边,会发现整幅图是一组匹配。在交换行和列的时候,相当于在匈牙利算法中进行协商的过程,所以对最大匹配不变。如果交换后可以有n个及以上的匹配,就说明一定可以实现题意。