HDU 5988 最小费用最大流 好题

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5988

题目思路:最小费用最大流模板题,只不过有很多细节要注意,首先,对于每条边的第一次费用是0,将一条边非为1和cap-1,分别添加进入,第二,费用要用-log(1.pi)就是最小费用了,第三,要设置首尾,第四,必须要用eps进行判断,否则会超时

AC代码

#include<iostream>
#include<cmath>
#include<queue>
#include<cstring>
using namespace std;

const double eps=1e-8;
#define maxn 10007
#define maxm 5007
int first[100000];
int edge_num;
struct edge{
    int flow;
    int cap;
    int u,v;
    int next;
    double cost;
}e[100000];
double dis[maxn];
bool vis[maxn];
int p[maxn];
int n,m;
double ans;


void add_edge(int u,int v,double w ,int c)
{
    e[edge_num].u=u;
    e[edge_num].v=v;
    e[edge_num].cost=w;
    e[edge_num].cap=c;
    e[edge_num].flow=0;
    e[edge_num].next=first[u];
    first[u]=edge_num++;
    e[edge_num].u=v;
    e[edge_num].v=u;
    e[edge_num].cost=-w;
    e[edge_num].cap=0;
    e[edge_num].flow=0;
    e[edge_num].next=first[v];
    first[v]=edge_num++;
}

void EK(int s,int t)
{
    while(1)
    {
        queue<int>q;
        q.push(s);
        for(int i=0;i<n+30;++i)
        {
            dis[i]=1000000000007;
            vis[i]=false;
            p[i]=-1;
        }
        dis[s]=0;
        while(!q.empty())
        {
            int u=q.front();
            q.pop();
            vis[u]=false;
            for(int k=first[u];k!=-1;k=e[k].next)
            {
                int v=e[k].v;
                if(e[k].cap>e[k].flow&&dis[v]-dis[u]-e[k].cost>eps)
                {
                    dis[v]=dis[u]+e[k].cost;
                    p[v]=k;
                    if(!vis[v])
                    {
                        vis[v]=true;
                        q.push(v);
                    }
                }
            }
        }
        if(p[t]==-1)
            break;
        int a=999999999;
        for(int k=p[t];k!=-1;k=p[e[k].u])
            a=min(a,e[k].cap-e[k].flow);
        for(int k=p[t];k!=-1;k=p[e[k].u])
        {
            e[k].flow+=a;
            e[k^1].flow-=a;
        }
        ans+=dis[t]*a;
    }
}

int main()
{
    int t;
    scanf("%d",&t);
    int temp[maxn];
    while(t--)
    {
        memset(first,-1,sizeof(first));
        ans=0;
        edge_num=0;
        scanf("%d%d",&n,&m);
        for(int i=1;i<=n;++i)
        {
            int x,y;
            scanf("%d%d",&x,&y);
            temp[i]=x-y;
        }
        for(int i=1;i<=m;++i)
        {
            int u,v,c;
            double pi;
            scanf("%d%d%d%lf",&u,&v,&c,&pi);
            if(c>0)
                add_edge(u,v,0,1);
            if(c-1>0)
                add_edge(u,v,-log(1.0-pi),c-1);
        }
        for(int i=1;i<=n;++i)
        {
            if(temp[i]>0)
                add_edge(0,i,0,temp[i]);
            if(temp[i]<0)
                add_edge(i,n+1,0,-temp[i]);
        }
        EK(0,n+1);
        printf("%.2f\n",1-1/exp(ans));
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36921652/article/details/83059046