【POJ 1719】 Shooting Contest (二分图匹配)

题目链接

把每一列能射的两行和这一列连边,然后跑一边匈牙利就行了。

#include <cstdio>
#include <cstring>
#include <algorithm>
using std::swap;
#define Open(s) freopen(s".in","r",stdin);freopen(s".out","w",stdout);
#define Close fclose(stdin);fclose(stdout);
inline int read(){
	int s = 0;
	char ch = getchar();
	while(ch < '0' || ch > '9') ch = getchar();
	while(ch >= '0' && ch <= '9'){ s = s * 10 + ch - '0'; ch = getchar(); }
	return s;
}
const int MAXN = 2010;
int T, n, m, a[MAXN], b[MAXN], flag[MAXN], match[MAXN], c[MAXN], ans;
struct Edge{
    int next, to;
}e[MAXN << 1];
int head[MAXN], num;
inline void Add(int from, int to){
    e[++num].to = to;
    e[num].next = head[from];
    head[from] = num;
}
void print(){
	for(int i = 1; i <= m; ++i){
        if(!match[i]) match[i] = a[i];
		printf("%d ", match[i]);
    }
	puts("");
}
int find(int x){
    for(int i = head[x]; i; i = e[i].next)
       if(!flag[e[i].to]){
         flag[e[i].to] = 1;
         if(!match[e[i].to] || find(match[e[i].to])){
           match[e[i].to] = x;
           return 1;
         }
       }
    return 0;
}
int Judge(){
    for(int i = 1; i <= m; ++i)
       c[match[i]] = T;
    for(int i = 1; i <= n; ++i)
       if(c[i] != T)
         return 1;
    return 0;
}
int main(){
	Open("she");
	T = read() + 1;
	while(--T){
		num = 0; for(int i = 1; i <= (m << 1); ++i) head[i] = 0;
		n = read(); m = read();
		for(int i = 1; i <= m; ++i){
			a[i] = read(); b[i] = read(); 
			Add(a[i], i); Add(b[i], i);
			match[i] = 0;
		}
		for(int i = 1; i <= n; ++i){
           for(int i = 1; i <= m; ++i)
              flag[i] = 0;
           find(i);
        }
        if(Judge()) printf("NO
");
        else print();
	}
	return 0;
}

原文地址:https://www.cnblogs.com/Qihoo360/p/9713203.html