BruceJay's Blog

BZOJ1143 祭祀

| Comments

To start with

网络流。。。

Problem

Solution

最长反链=最小链覆盖(Dilworth定理)
Floyd传递闭包后建立二分图,n-二分图最大匹配数即为答案。

Code

#include <cstdio>
#include <cstring>
#include <queue>
#include <iostream>
#include <algorithm>
using namespace std;

const int N = 210;
const int M = 200100;
const int INF = 0x3f3f3f3f;
struct Edge{int u,v,cap,flow,nxt;}e[M];
int head[N]; int cur[N]; int h[N];
int f[N][N]; queue<int> q;
int n,m,t,cnt=1,ans=0;

inline int read()
{
    int t=1,x=0; char ch=getchar();
    while(ch<'0' || ch>'9'){
        if(ch=='-') t=-1;
        ch=getchar();
    }
    while(ch>='0' && ch<='9'){
        x=x*10+ch-'0';
        ch=getchar();
    }
    return t*x;
}

void Floyd()
{
    for(int k=1;k<=n;k++)
    for(int i=1;i<=n;i++)
    for(int j=1;j<=n;j++)
        f[i][j]|=(f[i][k]&f[k][j]);
}

void Addedge(int u,int v,int cap)
{
    e[++cnt]=(Edge){u,v,cap,0,head[u]}; head[u]=cnt;
    e[++cnt]=(Edge){v,u,0,0,head[v]}; head[v]=cnt;
}

void Build()
{
    for(int i=1;i<=n;i++){
        Addedge(0,i,1);
        Addedge(i+n,t,1);
    }
    for(int i=1;i<=n;i++)
    for(int j=1;j<=n;j++)
        if(f[i][j]) Addedge(i,j+n,1);
}

bool Bfs()
{
    memset(h,-1,sizeof(h));
    h[0]=0; q.push(0);
    while(!q.empty()){
        int u=q.front(); q.pop();
        for(int i=head[u];i;i=e[i].nxt)
            if(h[e[i].v]==-1 && e[i].cap>e[i].flow){
                h[e[i].v]=h[u]+1; q.push(e[i].v);
            }
    }
    return h[t]!=-1;
}

int Dfs(int u,int now)
{
    int flow=0;
    if(u==t || !now) return now;
    for(int& i=cur[u];i;i=e[i].nxt)
        if(h[e[i].v]==h[u]+1){
            int f=Dfs(e[i].v,min(now,e[i].cap-e[i].flow));
            e[i].flow+=f; e[i^1].flow-=f;
            flow+=f; now-=f; if(!now) break;
        }
    return flow;
}

void Dinic()
{
    while(Bfs()){
        memcpy(cur,head,sizeof(cur));
        ans+=Dfs(0,INF);
    }
}

int main()
{
    int u,v;
    freopen("1143.in","r",stdin);
    freopen("1143.out","w",stdout);
    n=read(); m=read(); t=(n<<1)+1;
    for(int i=1;i<=m;i++){
        u=read(); v=read();
        f[u][v]=true;
    }
    Floyd();
    Build();
    Dinic();
    printf("%d",n-ans);
    return 0;
}

Last but not least

这题考察重点并不在网络流啊

Comments

comments powered by Disqus