USACO 4.2 The Perfect Stall网络流解最大二分图匹配

如下图所示方式构图,每条边的容量为1,则从source到sink最大流量就等于cow与stall的最大匹配

USACO 4.2 The Perfect Stall网络流解最大二分图匹配_第1张图片

代码:

#include<cstdio>
#include<queue>
#define MAX 410
using namespace std;

FILE *in,*out;
int map[MAX][MAX],nodes,ans,layer[MAX];
bool table[MAX];

void flow(void);
bool BFS(void);
void DFS(int *path,int index);

int main()
{
    in=fopen("stall4.in","r");
    out=fopen("stall4.out","w");
    int n,m,e,id;
    fscanf(in,"%d%d",&n,&m);
    for(int i=1;i<=n;i++)
    {
        fscanf(in,"%d",&e);
        for(int j=0;j<e;j++)
        {
             fscanf(in,"%d",&id);
             map[i][id+n]=1;
        }
    }
    nodes=n+m+2;
    for(int i=1;i<=n;i++) map[0][i]=1;
    for(int i=1;i<=m;i++) map[n+i][nodes-1]=1;
    flow();
    fprintf(out,"%d\n",ans);
    fclose(in);
    fclose(out);
    return 0;
}

void flow(void)
{
    int path[MAX];
    while(BFS())
    {
        for(int i=0;i<nodes;i++) table[i]=false;
        path[0]=0;
        table[0]=true;
        DFS(path,0);
    }
}

bool BFS(void)
{
     queue <int> myqueue;
     for(int i=1;i<=nodes;i++) layer[i]=MAX;
     layer[0]=0;
     myqueue.push(0);
     while(!myqueue.empty())
     {
          int p=myqueue.front();
          myqueue.pop();
          for(int i=1;i<nodes;i++)
          {
               if(map[p][i]>0 && layer[i]>layer[p]+1)
               {
                    layer[i]=layer[p]+1;
                    myqueue.push(i);
               }
          }
     }
     if(layer[nodes-1]<MAX) return true;
     return false;
}

void DFS(int *path,int index)
{
     int pid=path[index];
     if(pid==nodes-1)
     {
          int _min=100000;
          for(int i=1;i<=index;i++)
          {
               if(map[path[i-1]][path[i]]<_min) _min=map[path[i-1]][path[i]];
          }
          ans+=_min;
          for(int i=1;i<=index;i++)
          {
               map[path[i-1]][path[i]]-=_min;
               map[path[i]][path[i-1]]+=_min;
          }
          return ;
     }
     for(int i=1;i<nodes;i++)
     {
          if(map[pid][i]>0 && table[i]==false && layer[i]>layer[pid])
          {
               path[index+1]=i;
               table[i]=true;
               DFS(path,index+1);
               table[i]=false;
          }
     }
}


你可能感兴趣的:(网络,table,Path,layer)