网络流前向星模板

题目链接:https://cn.vjudge.net/problem/HYSBZ-1001

AC代码:

#include<iostream>
#include<stack>
#include<queue>
#include<iomanip>
#include<stdio.h>
#include<cstring>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<map>
#include<vector>
using namespace std;
# define ll long long
# define maxn 6000000+100
# define inf 0x3f3f3f3f
int n;
int prev[maxn];//边的编号
int head[maxn];
struct node
{
    int to;
    int flow;
    int nex;
} edge[maxn];
int num;
void init()
{
    memset(head,-1,sizeof(head));
    num=0;
}
void addedge(int fr,int to,int flow)
{
    edge[num].to=to;
    edge[num].flow=flow;
    edge[num].nex=head[fr];
    head[fr]=num++;
    edge[num].to=fr;
    edge[num].flow=flow;
    edge[num].nex=head[to];
    head[to]=num++;
}
bool bfs()
{
    memset(prev,-1,sizeof(prev));
    prev[1]=1;
    queue<int>q;
    q.push(1);
    while(!q.empty())
    {
        int top=q.front();
        q.pop();
        for(int i=head[top]; i!=-1; i=edge[i].nex)
        {
            int temp=edge[i].to;
            if(prev[temp]==-1&&edge[i].flow>0)
            {
                prev[temp]=prev[top]+1;
                q.push(temp);
            }
        }
    }
    return prev[n]!=-1;
}
int dfs(int u,int flow)
{
    if(u==n)return flow;
    int res=0;
    for(int i=head[u]; i!=-1; i=edge[i].nex)
    {
        int t=edge[i].to;
        if(prev[t]==(prev[u]+1)&&edge[i].flow>0)
        {
            int temp=dfs(t,min(flow,edge[i].flow));
            edge[i].flow-=temp;
            edge[i^1].flow+=temp;
            res+=temp;
            flow-=temp;
            if(flow==0)break;
        }
    }
    if(res==0)prev[u]=-1;
    return res;
}
int dinic()
{
    int ans=0;
    while(bfs())
    {
        ans+=dfs(1,inf);
    }
    return ans;
}
int main()
{
    init();
    int nn,m;
    scanf("%d %d",&nn,&m);
    int temp;
    int minn=inf;
    for(int i=1; i<=nn; i++)
    {
        for(int j=1; j<=m-1; j++)
        {
            scanf("%d",&temp);
            addedge((i-1)*m+j,(i-1)*m+j+1,temp);
            minn=min(minn,temp);
            //    cout<<(i-1)*m+j<<" "<<(i-1)*m+j+1<<endl;
        }
    }
    for(int i=1; i<=nn-1; i++)
    {
        for(int j=1; j<=m; j++)
        {
            scanf("%d",&temp);
            addedge((i-1)*m+j,i*m+j,temp);
            minn=min(minn,temp);
        }
    }
    for(int i=1; i<=nn-1; i++)
    {
        for(int j=1; j<=m-1; j++)
        {
            scanf("%d",&temp);
            addedge((i-1)*m+j,i*m+j+1,temp);
        }
    }
//    if(nn==1&&m==1)
//    {
//        printf("%d\n",0);
//        return 0;
//    }
//    if(nn==1||m==1)
//    {
//        printf("%d\n",minn);
//        return 0;
//    }
    n=nn*m;
    int ans=dinic();
    printf("%d\n",ans);
    return 0;
}


 

posted @ 2018-11-18 11:53  Let_Life_Stop  阅读(160)  评论(0编辑  收藏  举报