hdu 1533(最小费用最大流)

主要是如何建图

#include<stdio.h>
#include<queue>
#include<string.h>
#include<iostream>//ek算法
using namespace std;
const int maxn=300;
const int inf=0x3f3f3f3f;
int m,n;
int mp[maxn][maxn];
int maxflow;
int flow[maxn];
bool vis[maxn];
int father[maxn];
void init()
{
    memset(mp,0,sizeof(mp));
    maxflow=0;
}
void solve(int s,int e)
{
    queue<int>q;
    while(1)
    {
        memset(vis,false,sizeof(vis));
        while(!q.empty()) q.pop();
        memset(flow,0,sizeof(flow));
        flow[s]=inf;
        q.push(s);
        vis[s]=true;
        while(!q.empty())
        {
            int u=q.front();
            q.pop();
            for(int i=s;i<=e;i++)
            {
                if(!vis[i]&&mp[u][i]>0)
                {
                    vis[i]=true;
                    q.push(i);
                    flow[i]=min(flow[u],mp[u][i]);
                    father[i]=u;
                }
            }
            if(flow[e]>0)
            {
                for(int i=e;i!=1;i=father[i])
                {
                    mp[father[i]][i]-=flow[e];
                    mp[i][father[i]]+=flow[e];
                }
                break;
            }
        }
        if(flow[e]==0) break;
        maxflow+=flow[e];
    }
}
int main()
{
    while(scanf("%d%d",&m,&n)!=EOF)
    {
        init();
        int u,v,w;
        for(int i=1;i<=m;i++)
        {
            scanf("%d%d%d",&u,&v,&w);
            mp[u][v]+=w;
        }
        solve(1,n);
        printf("%d\n",maxflow);
    }
    return 0;
}

1.设一个超级源点s,把s和全部的m连接,费用为0,对应的流为1

2设一个超级汇点t,把全部的h和t连接,费用为0,对应的流为1

3连接全部的m和全部的h,费用为距离,流为1.

猜你喜欢

转载自blog.csdn.net/qq_40642465/article/details/81331074