2018SD省队集训R2 D6

T1

这里写图片描述

题解

这是一道签到题
考虑入度出度平衡的状态,我们先把所有的边减成0,然后考虑对于一条有向边x->y,如果有c个,那么可以连权值为-w,流量为c的,还要连权值是w,流量为INF的,我们从1跑到n的时候,考虑什么时候dis[t]>=0的时候就结束了,再走下去不会更优

代码

#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#define LL long long 
#define INF 1e18
using namespace std;
struct hh{int x,y;LL c,w;}e[505];
const int N=10005;
int tot=-1,nxt[N*2],point[300],v[N*2],n,m,num[300],du[300];bool vis[300];
LL dis[300],c[N*2],remind[N*2];
void addline(int x,int y,LL l,LL z)
{
    ++tot;nxt[tot]=point[x]; point[x]=tot; v[tot]=y; remind[tot]=l; c[tot]=z;
    ++tot;nxt[tot]=point[y]; point[y]=tot; v[tot]=x; remind[tot]=0; c[tot]=-z;
}
void add(int x,int y){++tot; nxt[tot]=point[x]; point[x]=tot; v[tot]=y;}
bool spfa(int s,int t)
{
    queue<int>q;q.push(s);
    memset(vis,0,sizeof(vis));
    memset(dis,0x7f,sizeof(dis));
    dis[s]=0;
    while (!q.empty())
    {
        int now=q.front(); q.pop(); vis[now]=0;
        for (int i=point[now];i!=-1;i=nxt[i])
          if (remind[i] && dis[v[i]]>dis[now]+c[i])
          {
            dis[v[i]]=dis[now]+c[i];
            if (!vis[v[i]]) vis[v[i]]=1,q.push(v[i]);
          }
    }
    return dis[t]<0;
}
LL dfs(int now,int t,LL limit)
{
    vis[now]=1;
    if (now==t || !limit) return limit;
    LL flow=0;
    for (int i=point[now];i!=-1;i=nxt[i])
      if (remind[i] && !vis[v[i]] && dis[v[i]]==dis[now]+c[i])
      {
        LL f=dfs(v[i],t,min(limit,remind[i]));
        flow+=f; limit-=f;
        remind[i]-=f; remind[i^1]+=f;
        if (!limit) return flow;
      }
    return flow;
}
LL zkw(int s,int t)
{
    LL ans=0;
    while (spfa(s,t)) 
    {
        memset(vis,0,sizeof(vis));
        ans+=dis[t]*dfs(s,t,INF);
    }
    return ans;
}
int main()
{
    freopen("cheat.in","r",stdin);
    freopen("cheat.out","w",stdout);
    scanf("%d%d",&n,&m);  
    for (int i=1;i<=m;i++) scanf("%d%d%lld%lld",&e[i].x,&e[i].y,&e[i].c,&e[i].w);
    tot=-1;memset(point,-1,sizeof(point));LL ans=0;
    for (int i=1;i<=m;i++) 
    {
        ans+=e[i].c*e[i].w;
        addline(e[i].x,e[i].y,INF,e[i].w); addline(e[i].x,e[i].y,e[i].c,-e[i].w);
    }
    printf("%lld",ans+zkw(1,n));
}

猜你喜欢

转载自blog.csdn.net/blue_cuso4/article/details/80945630
d6
今日推荐