uva 10779(最大流)

模板:

#include<bits/stdc++.h>

using namespace std;
const int N =45;
const int M =30;
const int inf =0x3f3f3f3f;
int cnt[N][M];

struct Edge
{
    int from,to,cap,flow;
    Edge(int u,int v,int c,int f):from(f),to(v),cap(c),flow(f){}
};
int n,m;

struct Dinic
{
    int n,m,s,t;
    vector< Edge >edges;
    vector< int >G[N];
    bool vis[N];
    int d[N];
    int cur[N];

    void init()
    {
        for (int i=0; i<N; i++)
            G[i].clear();
        edges.clear();
    }


    void addedge(int from,int to,int cap)
    {
        edges.push_back(Edge(from,to,cap,0));
        edges.push_back(Edge(to,from,0,0));
        m=edges.size();
        G[from].push_back(m-2);
        G[to].push_back(m-1);
    }

    bool bfs()
    {
        memset(vis,0,sizeof(vis));
        queue<int >q;
        for (int i=0; i<N; i++) d[i] = inf;
        q.push(s); d[s]=0;vis[s]=1;
        while(!q.empty()){
            int x=q.front(); q.pop();
            for(int i=0;i<G[x].size();i++){
                Edge e=edges[G[x][i]];
                if(!vis[e.to]&&e.cap>e.flow){
                    vis[e.to]=1;
                    d[e.to]=d[x]+1;
                    q.push(e.to);
                }
            }
        }
        return vis[t];
    }

    int dfs(int x,int a)
    {
        if(x==t||a==0) return a;
        int flow=0,f;
        for(int &i=cur[x];i<G[x].size();i++){
            Edge &e=edges[G[x][i]];
            if(d[x]+1==d[e.to]&&(f=dfs(e.to,min(a,e.cap-e.flow)))>0){
                e.flow+=f;
                edges[G[x][i]^1].flow-=f;
                flow+=f;
                a-=f;
                if(a==0) break;
            }
        }
        return flow;
    }

    int maxflow(int s,int t)
    {
        this->s=s; this->t=t;
        int flow=0;
        while(bfs()){
            memset(cur,0,sizeof(cur));
            flow+=dfs(s,inf);
        }
        return flow;
    }

}a;



int main()
{
    int T;
    scanf("%d",&T);
    int kk=0;
    int k;
    while(T--)
    {
        scanf("%d %d",&n,&m);
        int x;
        a.init();
        memset(cnt,0,sizeof(cnt));

        for(int i=1;i<=n;i++)
        {
            scanf("%d",&k);
            for(int j=1;j<=k;j++)
            {
                scanf("%d",&x);
                cnt[i][x]++;
            }
        }

        for(int i=1;i<=m;i++)
        {
            a.addedge(0,i,cnt[1][i]);
        }

        for(int i=2;i<=n;i++)
        {
            for(int j=1;j<=m;j++)
            {
                if(cnt[i][j]==0){
                    a.addedge(j,m+i,1);
                    //cout<<"u "<<j<<" v "<<m+i<<" cap "<<1<<endl;
                }
                else a.addedge(m+i,j,cnt[i][j]-1);
            }
        }

        for(int i=1;i<=m;i++) a.addedge(i,n+m+1,1);

        int ans=a.maxflow(0,n+m+1);
        printf("Case #%d: %d\n",++kk,ans);
    }

    return 0;
}

/*

1
3 5
4 1 2 1 1
3 2 2 2
5 1 3 4 4 3

*/

猜你喜欢

转载自blog.csdn.net/yjt9299/article/details/81105173