首页 > 代码库 > hdu 2853 Assignment 费用流

hdu 2853 Assignment 费用流

就是本来就给出了一个匹配,然后让你求一个权值最大的匹配,并且和初始匹配变动最小。

#include <stdio.h>#include <iostream>#include <string.h>using namespace std;const int N=400;const int MAXE=20000000;const int inf=1<<30;int head[N],s,t,cnt,ans;int d[N],pre[N];bool vis[N];int q[MAXE];int map[200][200],fee[200][200];struct Edge{    int u,v,c,w,next;}edge[MAXE];void addedge(int u,int v,int w,int c){    edge[cnt].u=u;    edge[cnt].v=v;    edge[cnt].w=w;    edge[cnt].c=c;    edge[cnt].next=head[u];    head[u]=cnt++;    edge[cnt].v=u;    edge[cnt].u=v;    edge[cnt].w=-w;    edge[cnt].c=0;    edge[cnt].next=head[v];    head[v]=cnt++;}int SPFA(){    int l,r;    memset(pre,-1,sizeof(pre));    memset(vis,0,sizeof(vis));    for(int i=0;i<=t;i++) d[i]=inf;    d[s]=0;    l=0;r=0;    q[r++]=s;    vis[s]=1;    while(l<r)    {        int u=q[l++];        vis[u]=0;        for(int j=head[u];j!=-1;j=edge[j].next)        {            int v=edge[j].v;            if(edge[j].c>0&&d[u]+edge[j].w<d[v])            {                d[v]=d[u]+edge[j].w;                pre[v]=j;                if(!vis[v])                {                    vis[v]=1;                    q[r++]=v;                }            }        }    }    if(d[t]==inf)        return 0;    return 1;}void MCMF(){    int flow=0;    while(SPFA())    {        int u=t;        int mini=inf;        while(u!=s)        {            if(edge[pre[u]].c<mini)                mini=edge[pre[u]].c;                u=edge[pre[u]].u;        }        flow+=mini;        u=t;        ans+=d[t]*mini;        while(u!=s)        {            edge[pre[u]].c-=mini;            edge[pre[u]^1].c+=mini;            u=edge[pre[u]].u;        }    }}int main(){    int nn,mm;    while(scanf("%d%d",&nn,&mm)!=EOF)    {        int i,j,u;        cnt=0;        s=0;t=nn+mm+1;        for(i=0;i<=t;i++)            head[i]=-1;        memset(map,0,sizeof(map));        for(i=1;i<=nn;i++)            for(j=1;j<=mm;j++)                scanf("%d",&fee[i][j]);        int init=0;        for(i=1;i<=nn;i++)        {            scanf("%d",&u);            map[i][u]=1;            init+=fee[i][u];            addedge(s,i,0,1);        }        for(i=1;i<=mm;i++) addedge(i+nn,t,0,1);        for(i=1;i<=nn;i++)            for(j=1;j<=mm;j++)            {                if(map[i][j])                    addedge(i,j+nn,-fee[i][j]*51-1,1);                else addedge(i,j+nn,-fee[i][j]*51,1);            }        ans=0;        MCMF();        printf("%d %d\n",nn+ans%51,(-ans/51)-init);    }    return 0;}
View Code