天天看点

P1525 [NOIP2010 提高组] 关押罪犯 (二分图判定,种类并查集)

P1525 [NOIP2010 提高组] 关押罪犯

分析:

  • 二分图判定(染色法) + + + 二分答案
  • 二分答案,判断答案是否满足全部的罪犯关到两个监狱里,即二分图判定
#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
const int N=1e6+5;
struct Node 
{
    int next,to,w;
}e[N];
int head[N], tot;
inline void add(int u,int v,int w)
{
    e[++tot].next=head[u];
    e[tot].to=v;
    e[tot].w=w;
    head[u]=tot;
}
int n,m;
bool check(int k)
{   
    int clr[n+5]={0}; // 数组清零,一点小优化
    queue <int> q;
    for(int i=1;i<=n;i++) // 二分图判定板子
    {
        if(!clr[i])
        {
            clr[i]=1;
            q.push(i);
            while(!q.empty())
            {
                int u=q.front(); q.pop();
                for(int j=head[u]; j ; j=e[j].next)
                {
                    int v=e[j].to, w=e[j].w;
                    if(w>k) // 条件
                    {
                        if(!clr[v])
                        {
                            if(clr[u]==1) clr[v]=2;
                            else clr[v]=1;
                            q.push(v);
                        }
                        else if(clr[v]==clr[u]) return false;
                    }
                }
            }
        }
    }
    return true;
}
signed main()
{
    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    int r=0;
    cin>>n>>m;
    for(int i=1;i<=m;i++) 
    {
        int u,v,w;
        cin>>u>>v>>w;
        r=max(r,w);
        add(u,v,w); add(v,u,w);
    }
    int l=0;
    while(l<=r) // 二分答案
    {
        int mid=l+r>>1;
        if(check(mid)) r=mid-1;
        else l=mid+1;
    }
    cout<<l<<endl;
    return 0;
}
           

方法二:种类并查集

分析:

  • 考虑最终状态,划分成了两个集合,可以用种类并查集来维护
  • 从怨值最大的开始划分,直到两个人不得不在同一监狱时,便是答案了
#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
const int N=1e6+5;
struct Node
{
    int u,v,w;
    bool operator<(const Node &b) const{ return w>b.w; }
}e[N];
int f[N], b[N];
int fd(int k)
{
    if(f[k]==k) return k;
    return f[k]=fd(f[k]);
}

signed main()
{
    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=n;i++) f[i]=i;
    for(int i=1;i<=m;i++)
    {
        cin>>e[i].u>>e[i].v>>e[i].w;
    }
    sort(e+1,e+1+m);
    for(int i=1;i<=m;i++)
    {
        int x=fd(e[i].u), y=fd(e[i].v);
        if(x==y)
        {
            cout<<e[i].w<<endl; return 0;
        }
        else 
        {
            // 种类并查集的关键所在,b[x]记录x的对立集合
            if(!b[x]) b[x]=y; // x还没有根,直接记录
            else f[y]=fd(b[x]); //  将y归为x的对立集合
            if(!b[y]) b[y]=x; // 同上
            else f[x]=fd(b[y]);
        }
    }
    cout<<"0"<<endl;
    return 0;
}
           

继续阅读