LOJ [#115. 无源汇有上下界可行流](https://loj.ac/problem/115)

#115. 无源汇有上下界可行流

先扔个板子,上下界的东西一点点搞,写在奇怪的合集里面


Code:

#include <cstdio>
#include <cstring>
#include <algorithm>
const int N=210;
const int M=3e4;
const int inf=0x3f3f3f3f;
int head[N],to[M],Next[M],edge[M],cnt=1;
void add(int u,int v,int w)
{
    to[++cnt]=v,edge[cnt]=w,Next[cnt]=head[u],head[u]=cnt;
    to[++cnt]=u,edge[cnt]=0,Next[cnt]=head[v],head[v]=cnt;
}
int n,m,ss,tt,ans[M],d[N],dep[N],q[N],l,r,sum;
int bfs()
{
    memset(dep,0,sizeof dep);
    dep[q[l=r=1]=ss]=1;
    while(l<=r)
    {
        int now=q[l++];
        for(int v,i=head[now];i;i=Next[i])
            if(edge[i]&&!dep[v=to[i]])
            {
                dep[v]=dep[now]+1;
                if((q[++r]=v)==tt) return true;
            }
    }
    return false;
}
int dfs(int now,int flow)
{
    if(now==tt) return flow;
    int res=flow,bee;
    for(int v,i=head[now];i&&res;i=Next[i])
        if(edge[i]&&dep[v=to[i]]==dep[now]+1)
        {
            bee=dfs(v,std::min(res,edge[i]));
            if(!bee) {dep[v]=0;continue;}
            res-=bee,edge[i]-=bee,edge[i^1]+=bee;
        }
    return flow-res;
}
int Dinic()
{
    int flow,maxflow=0;
    while(bfs())
        while(flow=dfs(ss,inf))
            maxflow+=flow;
    return maxflow;
}
int main()
{
    scanf("%d%d",&n,&m);
    for(int s,t,l,u,i=1;i<=m;i++)
    {
        scanf("%d%d%d%d",&s,&t,&l,&u);
        ans[i]=l;
        add(s,t,u-l);
        d[s]-=l,d[t]+=l;
    }
    ss=n+1,tt=ss+1;
    for(int i=1;i<=n;i++)
    {
        if(d[i]>0) add(ss,i,d[i]),sum+=d[i];
        else if(d[i]<0) add(i,tt,-d[i]);
    }
    int flow=Dinic();
    if(flow!=sum) return puts("NO"),0;
    puts("YES");
    for(int i=2;i<=m<<1;i+=2) printf("%d\n",ans[i>>1]+edge[i^1]);
    return 0;
}

2019.2.17

上一篇:leetcode 115. 不同的子序列(Distinct Subsequences)


下一篇:int *p[4]与int (*q)[4]的区别