标签:hdu-2426
题意:N个学生安排到M个宿舍,每个学生对宿舍有个评价,正数,0,负数,现在评价是负数的,不能让这个学生去这个房间,问怎么安排让所有的学生都住进宿舍且评价最大。
思路:建立图的权重时,筛选掉负数边。
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<set>
#include<map>
#include<string>
#include<cstring>
#include<stack>
#include<queue>
#include<vector>
#include<cstdlib>
#define lson (rt<<1),L,M
#define rson (rt<<1|1),M+1,R
#define M ((L+R)>>1)
#define cl(a,b) memset(a,b,sizeof(a));
#define LL long long
#define P pair<int,int>
#define X first
#define Y second
#define pb push_back
#define fread(zcc) freopen(zcc,"r",stdin)
#define fwrite(zcc) freopen(zcc,"w",stdout)
using namespace std;
const int maxn=505;
const LL inf=9999999999;
LL w[maxn][maxn];
int linker[maxn],lx[maxn],ly[maxn],slack[maxn];
bool visx[maxn],visy[maxn];
int nx,ny;
bool dfs(int x){
visx[x]=true;
for(int y=0;y<ny;y++)if(w[x][y]>=0){///边的限制
if(visy[y])continue;
int tmp=lx[x]+ly[y]-w[x][y];
if(tmp==0){
visy[y]=true;
if(linker[y]==-1||dfs(linker[y])){
linker[y]=x;
return true;
}
}
else if(slack[y]>tmp){
slack[y]=tmp;
}
}
return false;
}
LL km(){
cl(linker,-1);
cl(ly,0);
for(int i=0;i<nx;i++){
lx[i]=-inf;
for(int j=0;j<ny;j++)if(w[i][j]>lx[i]){
lx[i]=w[i][j];
}
}
for(int x=0;x<nx;x++){
fill(slack,slack+ny+1,inf);
while(true){
cl(visx,false);
cl(visy,false);
if(dfs(x))break;
int d=inf;
for(int i=0;i<ny;i++)if(!visy[i]&&d>slack[i]){
d=slack[i];
}
for(int i=0;i<nx;i++)if(visx[i]){
lx[i]-=d;
}
for(int i=0;i<ny;i++)if(visy[i])ly[i]+=d;
else slack[i]-=d;
}
}
LL ans=0;
cl(visx,false);///用于下面判断每个学生是不是都安排了住宿
for(int i=0;i<ny;i++)if(linker[i]!=-1){//注意循环的上限是ny
ans+=w[linker[i]][i];
visx[linker[i]]=true;
}
for(int i=0;i<nx;i++)if(visx[i]==0)return -1;//检查每个学生是不是都安排了宿舍
return ans;
}
int main(){
int cas=1;
int n,m,e;
while(~scanf("%d%d%d",&n,&m,&e)){
if(e==0){
printf("Case %d: -1\n",cas++);
continue;
}
cl(w,-1);
bool ok=true;
while(e--){
int s,r,v;
scanf("%d%d%d",&s,&r,&v);
if(v>=0)w[s][r]=v;//不要负数的边
}
nx=n;ny=m;
LL ans=km();
printf("Case %d: %lld\n",cas++,ans);
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
HDU2426 Interesting Housing Problem(KM匹配 )
标签:hdu-2426
原文地址:http://blog.csdn.net/u013167299/article/details/48132143