Fork me on 
Catalogue

我自问酒不问仙,半世逍遥半世癫,我自问心不问佛,半世情愁半世痴。 ​​​​

dinicの模板

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#include <queue>
using namespace std;
const int maxn=200000+50;
int n,m,ans,cnt,h[maxn],T;
int s,e,d[maxn],cur[maxn];
struct node
{
    int a,b,next,w;
}table[maxn];
void add(int a,int b,int w)
{
    table[++cnt].a=a;
    table[cnt].b=b;
    table[cnt].next=h[a];
    table[cnt].w=w;
    h[a]=cnt;
}
bool bfs()
{
    memset(d,0,sizeof(d));
    queue<int> q; q.push(s);
    while (!q.empty())
    {
        for (int t=h[q.front()]; t; t=table[t].next)
        if (!d[table[t].b] && table[t].b!=s && table[t].w)
        {
            d[table[t].b]=d[q.front()]+1;
            q.push(table[t].b);
        }
        q.pop();
    }
    return d[e];
}
int dfs(int x,int tot)
{
    if (x==e || !tot) return tot;
    int flow=0,flo=0;
    for (int t=cur[x]; t; t=table[t].next)
    {
        if (table[t].w && d[table[t].b]==d[x]+1)
        {
            flo=dfs(table[t].b,min(tot,table[t].w));
            flow+=flo;
            tot-=flo;
            table[t].w-=flo;
            table[t^1].w+=flo;
            if (!tot) break;
        }
        cur[x]=t;
    }
    if (!flow) d[x]=0;
    return flow;
}
void dinic()
{
    while (bfs())
    {
        memcpy(cur,h,sizeof(cur));
        ans+=dfs(s,1000000000);
    }
    return;
}
int main()
{
    scanf("%d",&T);
    for (int oo=1; oo<=T; ++oo)
    {
        ans=0; cnt=0;
        memset(h,0,sizeof(h));
        scanf("%d%d",&n,&m);
        int q1,q2,mx=maxn*20,md=-maxn*20;
        for (int i=1; i<=n; ++i)
        {
            scanf("%d%d",&q1,&q2);
            if (q1<mx) s=i,mx=q1;
            if (q1>md) e=i,md=q1;
        }
        for (int i=1; i<=m; ++i)
        {
            int q1,q2,q3;
            scanf("%d%d%d",&q1,&q2,&q3);
            add(q1,q2,q3);
            add(q2,q1,q3);
        }
        dinic();
        printf("%d\n",ans);
    }
    return 0;
}

 

posted @ 2021-01-18 22:53  汉孤臣  阅读(43)  评论(0)    收藏  举报
Live2D