Description
Input
Output
Sample Input
Sample Output
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
using namespace std;
const int maxn = 1100;
struct Edge{
int from, to, dist, next;
Edge(){}
Edge(int _from,int _to,int _next):from(_from),to(_to),next(_next){}
}edges[maxn*maxn*3]; //direction
struct Swap{
int x,y;
}swaps[maxn*maxn];
int tot , head[maxn];
int linker[3*maxn], used[3*maxn], c[maxn];
void init(){
tot = 0;
memset(head,-1,sizeof(head));
}
void AddEdge(int _u,int _v){
edges[tot] = Edge(_u,_v,head[_u]);
head[_u] = tot++;
}
bool dfs(int u,int _n){
for(int e = head[u]; e != -1; e = edges[e].next){
int v = edges[e].to;
if(!used[v]){
used[v] = u;
if(linker[v] == -1 || dfs(linker[v],_n)){
linker[v] = u;
return true;
}
}
}
return false;
}
int hungary(int p, int n){
int ret = 0;
memset(linker,-1,sizeof(linker));
for(int i = 1; i <= p; i++){
memset(used,0,sizeof(used));
if(dfs(i,n))
ret++;
}
return ret;
}
int main(){
int n, m, T, p, k, cas = 0;
while(scanf("%d",&n)!=EOF){
int a,b;
init();
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
scanf("%d",&a);
if(a == 1){
AddEdge(i,j);
}
}
}
int ans = hungary(n,m);
if(ans < n ){
puts("-1"); continue;
}
int num = 0;
for(int i = 1; i <= n; i++){
if(linker[i] != i){
for(int j = i+1; j <= n; j++){
if(linker[j] == i){
swap(linker[i],linker[j]);
num++;
swaps[num].x = i; swaps[num].y = j;
}
}
}
}
printf("%d\n",num);
for(int i = 1; i <= num; i++){
printf("C %d %d\n",swaps[i].x,swaps[i].y);
}
}
return 0;
}
HDU 2819 ——Swap——————【最大匹配、利用linker数组、邻接表方式】
原文:http://www.cnblogs.com/chengsheng/p/4955309.html