Test instructions: N students arranged to M dormitory, each student to the dormitory has a rating, positive, 0, negative, now the evaluation is negative, can not let this student go to this room, ask how to arrange to let all the students live in the dormitory and the most evaluation.
Idea: When building the weight of a graph, filter out negative edges.
#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 intmaxn=505;ConstLL inf=9999999999; LL W[MAXN][MAXN];intLINKER[MAXN],LX[MAXN],LY[MAXN],SLACK[MAXN];BOOLVISX[MAXN],VISY[MAXN];intNx,ny;BOOLDfsintx) {visx[x]=true; for(inty=0; y<ny;y++)if(w[x][y]>=0){/// Edge Restrictions if(Visy[y])Continue;intTmp=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(intI=0; i<nx;i++) {lx[i]=-inf; for(intj=0; j<ny;j++)if(W[i][j]>lx[i]) {LX[I]=W[I][J]; } } for(intx=0; x<nx;x++) {Fill (slack,slack+ny+1, INF); while(true) {cl (VISX,false); CL (Visy,false);if(Dfs (x)) Break;intD=inf; for(intI=0; i<ny;i++)if(!visy[i]&&d>slack[i]) {D=slack[i]; } for(intI=0; i<nx;i++)if(Visx[i]) {Lx[i]-=d; } for(intI=0; i<ny;i++)if(Visy[i]) Ly[i]+=d;ElseSlack[i]-=d; }} LL ans=0; CL (VISX,false);/// for the following to determine if each student has arranged a lodging for(intI=0; i<ny;i++)if(linker[i]!=-1){//Note that the upper limit of the loop is NYAns+=w[linker[i]][i]; visx[linker[i]]=true; } for(intI=0; i<nx;i++)if(visx[i]==0)return-1;//Check if each student has a dorm returnAns;}intMain () {intcas=1;intN,m,e; while(~scanf("%d%d%d", &n,&m,&e)) {if(e==0){printf("Case%d: -1\n", cas++);Continue; } cl (w,-1);BOOLok=true; while(e--) {intS,r,v;scanf("%d%d%d", &s,&r,&v);if(v>=0) W[s][r]=v;//Do not negative side} nx=n;ny=m; LL ans=km ();printf("Case%d:%lld\n", Cas++,ans); }return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
HDU2426 interesting Housing problem (km matches)