Going Home
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 20115 | Accepted: 10189 |
Description
On a grid map there are n little men and n houses. In each unit time, every little man can move one unit step, either horizontally, or vertically, to an adjacent point. For each little man, you need to pay a $1 travel fee for every step he moves, until he enters a house. The task is complicated with the restriction that each house can accommodate only one little man. Your task is to compute the minimum amount of money you need to pay in order to send these n little men into those n different houses. The input is a map of the scenario, a '.' means an empty space, an 'H' represents a house on that point, and am 'm' indicates there is a little man on that point. You can think of each point on the grid map as a quite large square, so it can hold n little men at the same time; also, it is okay if a little man steps on a grid with a house without entering that house.
Input
There are one or more test cases in the input. Each case starts with a line giving two integers N and M, where N is the number of rows of the map, and M is the number of columns. The rest of the input will be N lines describing the map. You may assume both N and M are between 2 and 100, inclusive. There will be the same number of 'H's and 'm's on the map; and there will be at most 100 houses. Input will terminate with 0 0 for N and M.
Output
For each test case, output one line with the single integer, which is the minimum amount, in dollars, you need to pay.
Sample Input
2 2.mH.5 5HH..m...............mm..H7 8...H.......H.......H....mmmHmmmm...H.......H.......H....0 0
Sample Output
21028 题解:这个题意就是,m个人都进入不同的房子的步数和最小;那么求负的步数的最大匹配就可以了;km算法;
代码:
1 #include2 #include 3 #include 4 #include 5 using namespace std; 6 #define mem(x,y) memset(x,y,sizeof(x)) 7 const int MAXN=110; 8 const int INF=1e4; 9 char s[MAXN][MAXN];10 int mp[MAXN][MAXN],lx[MAXN],ly[MAXN],usdx[MAXN],usdy[MAXN],mat[MAXN];11 struct Node{12 int x,y;13 }hou[MAXN],man[MAXN];14 int k;15 bool dfs(int x){16 usdx[x]=1;17 for(int i=1;i<=k;i++){18 if(!usdy[i]&&lx[x]+ly[i]==mp[x][i]){19 usdy[i]=1;20 if(!mat[i]||dfs(mat[i])){21 mat[i]=x;return true;22 }23 }24 }25 return false;26 }27 int km(){28 mem(mat,0);mem(lx,0);mem(ly,0);29 for(int i=1;i<=k;i++)30 for(int j=1;j<=k;j++)31 lx[i]=max(lx[i],mp[i][j]);32 for(int i=1;i<=k;i++){33 mem(usdx,0);mem(usdy,0);34 while(!dfs(i)){35 int d=INF;36 for(int j=1;j<=k;j++)37 if(usdx[j])38 for(int b=1;b<=k;b++)39 if(!usdy[b])40 d=min(d,lx[j]+ly[b]-mp[j][b]);41 for(int j=1;j<=k;j++){42 if(usdx[j])lx[j]-=d;43 if(usdy[j])ly[j]+=d;44 }45 mem(usdx,0);mem(usdy,0);46 }47 }int ans=0;48 for(int i=1;i<=k;i++)ans+=lx[i]+ly[i];49 return INF*k-ans;50 }51 int main(){52 int N,M;53 while(scanf("%d%d",&N,&M),N|M){54 int k1=0,k2=0;55 for(int i=0;i