BZOJ 3931 网络吞吐量

Posted on 2017-01-20 12:13  ziliuziliu  阅读(185)  评论(0编辑  收藏  举报

题面即题解。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#define maxn 505
#define maxv 1050
#define maxe 300500
#define inf 0x7f7f7f7f7f7f7f7fLL
using namespace std;
long long n,m,x[maxe],y[maxe],d[maxe],dis[maxv],nume=1,s,t,lim[maxv],g[maxv];
struct edge
{
    long long v,f,c,nxt;
}e[maxe];
struct sta
{
    long long v,len;
    sta (long long v,long long len):v(v),len(len) {}
    sta () {}
    friend bool operator < (const sta & x,const sta & y)
    {
        return x.len>y.len;
    }
};
priority_queue <sta> q;
queue <long long> qt;
void addedge(long long u,long long v,long long f,long long c)
{
    e[++nume].v=v;e[nume].f=f;e[nume].c=c;
    e[nume].nxt=g[u];g[u]=nume;
}
void dijkstra()
{
    q.push(sta(1,0));dis[1]=0;
    for (long long i=2;i<=n;i++) dis[i]=inf;
    while (!q.empty())
    {
        sta head=q.top();q.pop();
        for (long long i=g[head.v];i;i=e[i].nxt)
        {
            long long v=e[i].v;
            if (dis[v]>dis[head.v]+e[i].c)
            {
                dis[v]=dis[head.v]+e[i].c;
                q.push(sta(v,dis[v]));
            }
        }
    }
}
void build()
{
    nume=1;memset(g,0,sizeof(g));s=0;t=2*n+1;lim[1]=lim[n]=inf;
    for (long long i=1;i<=m;i++)
    {
        if (dis[x[i]]+d[i]==dis[y[i]]) {addedge(x[i]+n,y[i],inf,0);addedge(y[i],x[i]+n,0,0);}
        if (dis[y[i]]+d[i]==dis[x[i]]) {addedge(x[i],y[i]+n,0,0);addedge(y[i]+n,x[i],inf,0);}
    }
    for (long long i=1;i<=n;i++) {addedge(i,i+n,lim[i],0);addedge(i+n,i,0,0);}
    addedge(s,1,inf,0);addedge(1,s,0,0);
    addedge(2*n,t,inf,0);addedge(t,2*n,0,0);
}
bool bfs()
{
    for (long long i=s;i<=t;i++) dis[i]=inf;
    dis[s]=0;while (!qt.empty()) qt.pop();qt.push(s);
    while (!qt.empty())
    {
        long long head=qt.front();qt.pop();
        for (long long i=g[head];i;i=e[i].nxt)
        {
            long long v=e[i].v;
            if ((dis[v]>dis[head]+1) && (e[i].f>0))
            {
                dis[v]=dis[head]+1;
                qt.push(v);
            }
        }
    }
    return dis[t]!=inf;
}
long long dinic(long long x,long long low)
{
    if (x==t) return low;
    long long ret=0;
    for (long long i=g[x];i && low;i=e[i].nxt)
    {
        long long v=e[i].v;
        if ((dis[v]==dis[x]+1) && (e[i].f))
        {
            long long dd=dinic(v,min(low,e[i].f));
            ret+=dd;low-=dd;
            e[i].f-=dd;e[i^1].f+=dd;            
        }
    }
    if (!ret) dis[x]=inf;
    return ret;
}
int main()
{
    scanf("%lld%lld",&n,&m);
    for (long long i=1;i<=m;i++)
    {
        scanf("%lld%lld%lld",&x[i],&y[i],&d[i]);
        addedge(x[i],y[i],0,d[i]);
        addedge(y[i],x[i],0,d[i]);
    }
    dijkstra();
    for (long long i=1;i<=n;i++) scanf("%lld",&lim[i]);
    build();
    long long mx_flow=0;
    while (bfs())
        mx_flow+=dinic(s,inf);
    printf("%lld\n",mx_flow);
    return 0;
}