有上下界的网络流总结(未完成)

LOJ上有全套的模板

题号为115,116,117

先贴个板子,到时候在填坑

无源无汇可行流

# include<iostream>
# include<cstdio>
# include<cmath>
# include<algorithm>
# include<cstring>
# include<queue>
using namespace std;
const int mn = 205;
const int inf = 0x3f3f3f3f;
struct edge{int to,next,flow,cup;};
edge e[10200*10];
int head[mn],edge_max=1;
void add(int x,int y,int z)
{
    //printf("%d %d\n",x,y);
    e[++edge_max].to=y;
    e[edge_max].flow=e[edge_max].cup=z;
    e[edge_max].next=head[x];
    head[x]=edge_max;
}
int n,m;
int B[mn],low[10200*10];
int cur[mn],deep[mn];
queue<int> q;
bool bfs(int x,int y)
{
    memset(deep,0,sizeof(deep));
    q.push(x);
    deep[x]=1;
    while(!q.empty())
    {
        int u=q.front();
        q.pop();
        for(int i=head[u];i;i=e[i].next)
        {
            if(e[i].flow>0 && deep[e[i].to]==0)
            {
                deep[e[i].to]=deep[u]+1;
                q.push(e[i].to);
            }
        }
    }
    /*for(int i=1;i<=y;i++)
        printf("%d ",deep[i]);
    printf("\n");*/
    return deep[y]!=0;
}
int dfs(int x,int dist,int y)
{
    if(x==y)
        return dist;
    for(int &i=cur[x];i;i=e[i].next)
    {
        if(e[i].flow>0 && deep[e[i].to]==deep[x]+1)
        {
            int di=dfs(e[i].to,min(e[i].flow,dist),y);
            if(di>0)
            {
                e[i].flow-=di;
                e[i^1].flow+=di;
                return di;
            }
        }
    }
    return 0;
}
int dinic(int x,int y)
{
    int ret=0;
    while(bfs(x,y))
    {
        //memset(cur,0,sizeof(cur));
        for(int i=1;i<=y;i++)
            cur[i]=head[i];
        while(int k=dfs(x,inf,y))
        {
            //printf("%d\n",k);
            ret+=k;
        }
        //printf("%d\n",ret);
    }
    return ret;
}
int main()
{
    int x,y,a,b;
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;i++)
    {
        scanf("%d%d%d%d",&x,&y,&a,&b);
        add(x,y,b-a);add(y,x,0);
        B[x]+=a;
        B[y]-=a;
        low[i]=a;
    }
    int sum=0,st=n+1,en=n+2;
    for(int i=1;i<=n;i++)
    {
        if(B[i]>0){
            sum+=B[i];
            add(i,en,B[i]);
            add(en,i,0);
        }
        else if(B[i]<0){
            add(st,i,-B[i]);
            add(i,st,0);
        }
    }
    if(dinic(st,en)==sum)
    {
        printf("YES\n");
        for(int i=1;i<=m;i++)
            printf("%d\n",e[i*2].cup-e[i*2].flow+low[i]);
    }
    else printf("NO");
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/logeadd/p/9715918.html
今日推荐