题意:给定一个 n * m 的矩阵,有一些格子有目标,每次可以消灭一行或者一列,问你最少要几次才能完成。
析:把 行看成 X,把列看成是 Y,每个目标都连一条线,那么就是一个二分图的最小覆盖数,这个答案就是二分图的最大匹配,在输出解的时候,就是从匈牙利树上,从X的未盖点出发,然后标记X和Y,最后X中未标记的和Y标记的就是答案。
代码如下:
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <cstring>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
#include <cctype>
#include <cmath>
#include <stack>
#include <sstream>
#include <list>
#include <assert.h>
#include <bitset>
#define debug() puts("++++");
#define gcd(a, b) __gcd(a, b)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define fi first
#define se second
#define pb push_back
#define sqr(x) ((x)*(x))
#define ms(a,b) memset(a, b, sizeof a)
#define sz size()
#define pu push_up
#define pd push_down
#define cl clear()
#define all 1,n,1
#define FOR(i,x,n) for(int i = (x); i < (n); ++i)
#define freopenr freopen("in.txt", "r", stdin)
#define freopenw freopen("out.txt", "w", stdout)
using namespace std; typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const double inf = 1e20;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int maxn = 2000 + 10;
const LL mod = 1e9 + 7;
const int dr[] = {-1, 0, 1, 0};
const int dc[] = {0, 1, 0, -1};
const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};
int n, m;
const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
inline bool is_in(int r, int c) {
return r >= 0 && r < n && c >= 0 && c < m;
} struct Edge{
int to, next;
};
Edge edge[maxn*maxn/4];
int head[maxn], cnt;
int match[maxn];
bool used[maxn];
bool visx[maxn], visy[maxn]; void addEdge(int u, int v){
edge[cnt].to = v;
edge[cnt].next = head[u];
head[u] = cnt++;
} bool dfs(int u){
used[u] = true;
for(int i = head[u]; ~i; i = edge[i].next){
int v = edge[i].to, w = match[v];
if(w < 0 || !used[w] && dfs(w)){
match[u] = v;
match[v] = u;
return true;
}
}
return false;
} void dfs1(int u){
visx[u] = 1;
for(int i = head[u]; ~i; i = edge[i].next){
int v = edge[i].to;
if(visy[v]) continue;
visy[v] = 1;
dfs1(match[v]);
}
} int main(){
int r, c;
while(scanf("%d %d %d", &r, &c, &m) == 3 && r+c+m){
ms(head, -1); cnt = 0;
for(int i = 0; i < m; ++i){
int u, v;
scanf("%d %d", &u, &v);
--u, --v;
addEdge(u, v + r);
}
n = r + c;
ms(match, -1);
int ans = 0;
for(int i = 0; i < n; ++i) if(match[i] < 0){
ms(used, 0); if(dfs(i)) ++ans;
}
printf("%d", ans);
ms(visx, 0); ms(visy, 0);
ms(used, 0);
for(int i = 0; i < r; ++i) if(match[i] != -1) used[i] = 1;
for(int i = 0; i < r; ++i) if(!used[i]) dfs1(i);
for(int i = 0; i < r; ++i) if(!visx[i]) printf(" r%d", i + 1);
for(int i = r; i < n; ++i) if(visy[i]) printf(" c%d", i + 1 - r);
printf("\n");
}
return 0;
}