首页 > 代码库 > HDU 3549 Flow Problem

HDU 3549 Flow Problem

最大流问题。


睡醒了,继续找个网络流的简单题来熟练。跟上一个一样。弧容量要加起来。

#include<cstdio>
#include<cstring>
#include<string>
#include<queue>
#include<algorithm>
#include<map>
#include<stack>
#include<iostream>
#include<list>
#include<set>
#include<cmath>
#define INF 0x7fffffff
#define eps 1e-6
#define LL long long
#define acfun std::ios::sync_with_stdio(false)
using namespace std;
int n,m;
struct lx
{
    int c,f;
};
lx g[21][21];
bool vis[21];
int path[21];
int flow[21];
void EK(int start,int thend)
{
    int maxflow=0;
    while(1)
    {
        for(int i=1;i<=n;i++)
            vis[i]=path[i]=flow[i]=0;
        queue<int>q;
        q.push(start);
        vis[start]=1,flow[start]=INF;

        while(!q.empty()&&!vis[thend])
        {
            int u=q.front();q.pop();
            for(int j=1;j<=n;j++)
            {
                if(vis[j])continue;

                if(g[u][j].f<g[u][j].c)
                {
                    vis[j]=1;
                    path[j]=u;
                    flow[j]=min(flow[u],g[u][j].c-g[u][j].f);
                    q.push(j);
                }
                else if(g[j][u].f>0)
                {
                    vis[j]=1;
                    path[j]=u;
                    flow[j]=min(flow[u],g[j][u].f);
                    q.push(j);
                }
            }
        }

        if(!vis[thend]||flow[thend]==0)break;
        int v=thend,u=path[v];
        int tmp=flow[v];
        maxflow+=tmp;
        while(v)
        {
            if(g[u][v].c>g[u][v].f)
                g[u][v].f+=tmp;
            else
                g[v][u].f-=tmp;
            v=u,u=path[v];
        }
    }
    cout<<maxflow<<endl;
}

int main()
{
    acfun;
    int t,nn=1;
    cin>>t;
    while(t--)
    {
        cin>>n>>m;
        for(int i=1;i<=n;i++)
            for(int j=1;j<=n;j++)
            g[i][j].c=g[i][j].f=0;
        int u,v,c;
        while(m--)
        {
            cin>>u>>v>>c;
            g[u][v].c+=c;
        }
        cout<<"Case "<<nn++<<":"<<" ";
        EK(1,n);
    }
}