HDU 2426 Interesting Housing Problem 最小费用流/KM
http://acm.hdu.edu.cn/showproblem.php?pid=2426
分宿舍,有一句
|
Note that you can never assign a student to a room which he/she has not rated, as the absence of rating indicates that the student cannot live in the room for other reasons
负数的不能分配吗?就WA在这里,在研究研究
代码:
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#define nMAX 5005
#define mMAX 500005
#define inf 999999999
using namespace std;
struct Edge
{
int u,v,cap,cost,nxt;
}edge[mMAX];
int head[nMAX],dis[nMAX],pre[nMAX],qu[nMAX];
int s_edge,ans,maxf;
bool vs[nMAX];
void addedge(int u,int v,int ca,int co)
{
edge[++s_edge].v=v;
edge[s_edge].cap=ca;
edge[s_edge].cost=co;
edge[s_edge].nxt=head[u];
head[u]=s_edge;
edge[++s_edge].v=u;
edge[s_edge].cap=0;
edge[s_edge].cost=-co;
edge[s_edge].nxt=head[v];
head[v]=s_edge;
}
bool spfa(int s,int t,int n)//起点 终点 总数
{
int start=0,tail=1;
for(int i=0;i<=n;i++)
{
dis[i]=-inf;
vs[i]=0;
}
qu[0]=s;
dis[s]=0;//是吗???
vs[s]=1;
while(start!=tail)
{
int u=qu[start];
for(int e=head[u];e;e=edge[e].nxt)
{
int v=edge[e].v;
if(edge[e].cap&&dis[v]<dis[u]+edge[e].cost)
{
dis[v]=dis[u]+edge[e].cost;
pre[v]=e;
if(!vs[v])
{
vs[v]=1;
qu[tail++]=v;
if(tail==nMAX)tail=0;
}
}
}
vs[u]=0;
start++;
if(start==nMAX)start=0;
}
if(dis[t]==-inf)return 0;
return 1;
}
void end(int s,int t)
{
int u,p;
for(u=t;u!=s;u=edge[p^1].v)
{
p=pre[u];
edge[p].cap-=1;
edge[p^1].cap+=1;
ans+=edge[p].cost;
}
maxf+=1;
}
int main()
{
int i,j,k,s,t,N,M,E,CASE=0;
while(~scanf("%d%d%d",&N,&M,&E))
{
CASE++;
s=N+M,t=N+M+1;//!!!
memset(head,0,sizeof(head));
s_edge=1;
for(i=0;i<N;i++)
addedge(s,i,1,0);
for(i=0;i<M;i++)
addedge(i+N,t,1,0);
while(E--)
{
scanf("%d%d%d",&i,&j,&k);
if(k<0)continue;
addedge(i,j+N,1,k);
}
ans=0, maxf=0;
while(spfa(s,t,N+M+2))
{
end(s,t);
}
if(maxf==N)printf("Case %d: %d\n",CASE,ans);
else printf("Case %d: -1\n",CASE);
}
return 0;
}
|

浙公网安备 33010602011771号