HDU 2819 Swap (二分匹配+破输出)

时间:2022-04-22 17:44:52

题意:给定上一个01矩阵,让你变成一个对角全是 1 的矩阵。

析:二分匹配,把行和列看成两个集合,用匈牙利算法就可以解决,主要是在输出解,在比赛时一紧张不知道怎么输出了。

输出应该是要把 match[i] = i 这样的输出,然后再改掉后面那个,真是个大傻逼输出,气死了。。。。。

代码如下:

#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>
#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 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 LL LNF = 1e17;
const double inf = 0x3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int maxn = 200 + 10;
const int mod = 10000007;
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;
} int match[maxn];
bool vis[maxn];
vector<int> G[maxn]; void add(int u, int v){
G[u].push_back(v);
G[v].push_back(u);
} bool dfs(int u){
vis[u] = true;
for(int i = 0; i < G[u].size(); ++i){
int v = G[u][i];
int w = match[v];
if(w == -1 || (!vis[w] && dfs(w))){
match[u] = v;
match[v] = u;
return true;
}
}
return false;
} int main(){
while(scanf("%d", &n) == 1){
for(int i = 0; i < n * 2; ++i) G[i].clear();
for(int i = 0; i < n; ++i)
for(int j = 0; j < n; ++j){
int x;
scanf("%d", &x);
if(x == 1) add(i, j+n);
} memset(match, -1, sizeof match);
int ans = 0;
n <<= 1;
for(int i = 0; i < n; ++i) if(match[i] == -1){
memset(vis, 0, sizeof vis);
if(dfs(i)) ++ans;
}
if(ans * 2 != n){ printf("-1\n"); continue; }
int t = n / 2;
for(int i = 0; i < t; ++i) match[i] -= t;
printf("%d\n", t);
for(int i = 0; i < t; ++i){
printf("C %d %d\n", i+1, match[i]+1);
for(int j = i+1; j < t; ++j)
if(match[j] == i){ match[j] = match[i]; break; }
}
}
return 0;
}