标签:clu == while comm integer span san lin scan
http://poj.org/problem?id=2195
Description

Input
Output
Sample Input
2 2 .m H. 5 5 HH..m ..... ..... ..... mm..H 7 8 ...H.... ...H.... ...H.... mmmHmmmm ...H.... ...H.... ...H.... 0 0
Sample Output
2 10 28
代码:
#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 1010;
int N, M;
int l1[maxn], l2[maxn], s[maxn], t[maxn];
int match1[maxn], match2[maxn];
int mp[maxn][maxn];
char maze[maxn][maxn];
int nx = 0, ny = 0;
struct Node {
int x;
int y;
}nodex[maxn], nodey[maxn];
int KM(int M, int N) {
int p, q, k, i, j;
int res = 0;
for( i = 0; i < M; i ++) {
l1[i] = -inf;
for( j = 0; j < N; j ++)
if(mp[i][j] > l1[i])
l1[i] = mp[i][j];
if(l1[i] == -inf) return -1;
}
memset(l2, 0, sizeof(l2));
memset(match1, -1, sizeof(match1));
memset(match2, -1, sizeof(match2));
for( i = 0; i < M; i ++) {
memset(t, -1, sizeof(t));
for(s[p = q = 0] = i; p <= q && match1[i] < 0; p ++) {
for(k = s[p], j = 0; j < N && match1[i] < 0; j ++) {
if(l1[k] + l2[j] == mp[k][j] && t[j] < 0) {
s[++ q] = match2[j], t[j] = k;
if(s[q] < 0)
for(p = j; p >= 0; j = p)
match2[j] = k = t[j], p = match1[k], match1[k] = j;
}
}
}
if(match1[i] < 0) {
for(i --, p = inf, k = 0; k <= q; k ++)
for( j = 0; j < N; j ++)
if(t[j] < 0 && l1[s[k]] + l2[j] - mp[s[k]][j] < p)
p = l1[s[k]] + l2[j] - mp[s[k]][j];
for( j = 0; j < N; j ++)
if(t[j] > 0) l2[j] += p;
for(k = 0; k <= q; k ++)
l1[s[k]] -= p;
}
}
for( i = 0; i <M; i ++) {
if(match1[i] < 0) return -1;
if(mp[i][match1[i]] <= -inf) return -1;
res += mp[i][match1[i]];
}
return res;
}
int main() {
while(~scanf("%d%d", &N, &M)) {
nx = 0, ny = 0;
memset(mp, 0, sizeof(mp));
if(!N && !M) break;
for(int i = 0; i < N; i ++)
scanf("%s", maze[i]);
for(int i = 0; i < N; i ++) {
for(int j = 0; j < M; j ++) {
if(maze[i][j] == ‘m‘) {
nodex[nx].x = i;
nodex[nx].y = j;
nx ++;
} else if(maze[i][j] == ‘H‘) {
nodey[ny].x = i;
nodey[ny].y = j;
ny ++;
}
}
}
for(int i = 0; i < nx; i ++) {
for(int j = 0; j < ny; j ++) {
mp[i][j] = -abs(nodex[i].x - nodey[j].x) - abs(nodex[i].y - nodey[j].y);
}
}
printf("%d\n", -KM(nx, ny));
}
return 0;
}
KM 求最小权匹配
刚刚结束携程的笔试 最后一道编程题看着乱糟糟 样例打表居然能过 85.7% 数据可以说是很水了
标签:clu == while comm integer span san lin scan
原文地址:https://www.cnblogs.com/zlrrrr/p/10673255.html