hdu 6118度クマの取引計画(最小費用実行可能フロー)


タイトルアドレス:http://acm.hdu.edu.cn/showproblem.php?pid=6118
考え方:最大値を求め、逆に最小値を求める.ソースポイントS、ポイントT.
ソースポイントから各地域iに接続され、費用はa[i]、流量はb[i](代表地域iの物品生産当たりの費用)である.
各地域iは送金ポイントに接続され、費用は-c[i]、流量はd[i](代表地域iは物品を売るごとに得られる)である.
地域間は2つに連なり、料金は地域間距離、流量はINF(物品を運ぶごとにかかることを表す).
注意:直接求めれば最大流量条件下での費用(この場合利益は必ずしも最大とは限らない)となるため、増広時に費用が正であることが判明した場合には直接増広を終了する(この場合、流量を増加し続けることで費用が大きくなり、すなわち増加し続けることで最終利益が減少する).
#include
#include
#include
#include
#include
#define S 0
#define T (n+1)
#define debug
using namespace std;
const int maxn=500+50;
const int INF=0x3f3f3f3f;
int n,m,ans;
int gg[maxn][maxn];
struct Edge
{
    int from,to,cap,flow,cost;
};
struct MCMF
{
    int n,m,s,t,flag;
    vector edges;
    vector G[maxn];
    int inq[maxn],d[maxn];
    int p[maxn],a[maxn];
    void init(int n)
    {
        flag=0;
        this->n=n;
        for(int i=0; i Q;
        Q.push(s);
        while(!Q.empty())
        {
            int u=Q.front();
            Q.pop(),inq[u]=0;
            for(int i=0; ie.flow&&d[e.to]>d[u]+e.cost)
                {
                    d[e.to]=d[u]+e.cost;
                    p[e.to]=G[u][i];
                    a[e.to]=min(a[u],e.cap-e.flow);
                    if(!inq[e.to])
                    {
                        Q.push(e.to);
                        inq[e.to]=1;
                    }
                }
            }
        }
        if(d[t]==INF) return false;
        if(d[t]*a[t]>0) return false;
        flow+=a[t];
        cost+=d[t]*a[t];
        int u=t;
        while(u!=s)
        {
            edges[p[u]].flow+=a[t];
            edges[p[u]^1].flow-=a[t];
            u=edges[p[u]].from;
        }
        return true;
    }
    int Mincost(int s,int t)
    {
        int flow=0,cost=0;
        while(BellmanFord(s,t,flow,cost));
        return cost;
    }
};
MCMF g;
void init()
{
    for(int i=0; i<=n; i++)
    {
        for(int j=0; j<=n; j++)
        {
            gg[i][j]=INF;
        }
    }
    ans=INF;
    g.init(n+2);
}

int main()
{
#ifdef debu
    freopen("in.txt","r",stdin);
#endif // debug
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        init();
        for(int i=1; i<=n; i++)
        {
            int a,b,c,d;
            scanf("%d%d%d%d",&a,&b,&c,&d);
            g.AddEdge(S,i,b,a);
            g.AddEdge(i,T,d,-c);
        }
        for(int i=1; i<=m; i++)
        {
            int u,v,k;
            scanf("%d%d%d",&u,&v,&k);
            gg[u][v]=gg[v][u]=min(gg[u][v],k);
        }
        for(int i=1; i<=n; i++)
        {
            gg[i][i]=0;
        }
        for(int i=1; i<=n; i++)
        {
            for(int j=1; j<=n; j++)
            {
                if(gg[i][j]