3876: [Ahoi2014]支线剧情 有上下界的费用流

说一下建图吧
对于每个点 i ,我们要连 (i,1,inf,0) ,表示随时可以回一号点。
然后对于每条边 ij ,我们要连 (i,T,1,0),(S,j,1,v),(i,j,inf,v)
然后跑费用流
好慢啊。

#include<iostream>
#include<cstdio>
#include<cstring>
#define inf 1000000007
#define N 605
#define M 605
#define E 30005
using namespace std;
int n,SS,TT,cnt=1,ans;
int head[N],dis[N],q[N],path[N];
int next[E],list[E],flow[E],cost[E],from[E];
int du[N];
bool vis[N];
inline int read()
{
    int a=0,f=1; char c=getchar();
    while (c<'0'||c>'9') {if (c=='-') f=-1; c=getchar();}
    while (c>='0'&&c<='9') {a=a*10+c-'0'; c=getchar();}
    return a*f;
}
inline void insert(int x,int y,int z,int w)
{
    next[++cnt]=head[x];
    head[x]=cnt;
    from[cnt]=x;
    list[cnt]=y;
    flow[cnt]=z;
    cost[cnt]=w;
}
inline bool spfa()
{
    for (int i=0;i<=TT;i++) dis[i]=inf;
    int t=0,w=1,x;
    q[1]=SS; dis[SS]=0; vis[SS]=1;
    while (t!=w)
    {
        t=(t+1)%M;
        x=q[t];
        for (int i=head[x];i;i=next[i])
            if (flow[i]&&dis[list[i]]>dis[x]+cost[i])
            {
                dis[list[i]]=dis[x]+cost[i];
                path[list[i]]=i;
                if (!vis[list[i]])
                {
                    vis[list[i]]=1;
                    w=(w+1)%M;
                    q[w]=list[i];
                }
            }
        vis[x]=0;
    }
    return dis[TT]!=inf;
}
inline void mcf()
{
    int x=inf;
    for (int i=path[TT];i;i=path[from[i]]) x=min(x,flow[i]);
    for (int i=path[TT];i;i=path[from[i]])
        flow[i]-=x,flow[i^1]+=x,ans+=x*cost[i];
}
int main()
{
    n=read(); SS=0; TT=n+1;
    for (int i=1;i<=n;i++)
    {
        int sum=read();
        insert(i,TT,sum,0),insert(TT,i,0,0);
        insert(i,1,inf,0),insert(1,i,0,0);
        while (sum--)
        {
            int x=read(),y=read();
            insert(i,x,inf,y),insert(x,i,0,-y);
            insert(SS,x,1,y),insert(x,SS,0,-y);
        }
    }
    while (spfa()) mcf();
    cout << ans << endl;
    return 0;
}

你可能感兴趣的:(3876: [Ahoi2014]支线剧情 有上下界的费用流)