您的位置:首页 > 其它

UVALive 11419 SAM I AM (最小点覆盖输出)

2016-05-14 03:30 465 查看
题目链接:

UVALive 11419 SAM I AM

题意:

在一个R*C的网格上放了一些目标.可以在网格外发射子弹,子弹会沿着垂直或者水平方向飞行,并打掉飞行路径上的所有目标.

计算最少需要多少子弹,各从哪些位置发射,才能把所有目标全部打掉.

输入第一行为R,C,N(R,C<=1000,N <= 100000)表示网格的大小和目标个数.接下来N行每行包含两个正数r[i]和c[i]表示

第i个目标所在的行列编号.各行从上到下编号为1~R,各列从左到右编号为1~C,输出结束标志为R=C=N=0.

每组测试数据输出一行首先是一个整数表示最少需要的子弹数目,接下来是这些子弹的发射位置.用rx表示第x行,cx表示第x列.

分析:

建图:将每一行看作一个X结点,每一列看作一个Y结点,每个目标对应一条边.这样,子弹打掉所有目标意味着每条边至少有一个结点被选中.

需要特别注意的是:各行从上到下编号为1~R,各列从左到右编号为1~C!

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <climits>
#include <cmath>
#include <ctime>
#include <cassert>
#define IOS ios_base::sync_with_stdio(0); cin.tie(0);
using namespace std;
typedef long long ll;
const int MAX_N = 1010;

int n, m, k, total;
int head[MAX_N], visx[MAX_N], visy[MAX_N], matchx[MAX_N], matchy[MAX_N];

struct Edge{
int to, next;
}edge[MAX_N*MAX_N];

inline void AddEdge(int from, int to)
{
edge[total].to = to;
edge[total].next = head[from];
head[from] = total++;
}

inline bool dfs(int u)
{
visx[u] = 1;
for(int i = head[u]; i != -1; i = edge[i].next){
int v = edge[i].to;
if(visy[v]) continue;
visy[v] = 1;
if(matchy[v] == -1 || dfs(matchy[v])){
matchx[u] = v;
matchy[v] = u;
return true;
}
}
return false;
}

inline int Hungary()
{//匈牙利算法求最大匹配
int res = 0;
memset(matchy, -1, sizeof(matchy));
memset(matchx, -1, sizeof(matchx));
for(int i = 1; i <= n; i++){
memset(visx, 0, sizeof(visx));
memset(visy, 0, sizeof(visy));
if(dfs(i)) res++;
}
return res;
}

int main()
{
IOS;
while(cin >> n >> m >> k && (n || m || k)){
total = 0;
memset(head, -1, sizeof(head));
for(int i = 0; i < k; i++){
int tmpx, tmpy;
cin >> tmpx >> tmpy;
AddEdge(tmpx, tmpy);
}
int ans = Hungary();
//将所有的X顶点和Y顶点标记状态清0
memset(visx, 0, sizeof(visx));
memset(visy, 0, sizeof(visy));
for(int i = 1; i <= n; i++){
if(matchx[i] == -1){ //对所有不在最大匹配中的X顶点扩展匈牙利树,标记树中顶点
dfs(i);
}
}
cout << ans ;
for(int i = 1; i <= n; i++){ //X顶点中所有没被标记的顶点
if(visx[i] == 0) cout << " r" << i ;
}
for(int i = 1; i <= m; i++){ //Y顶点中所有被标记的顶点
if(visy[i] == 1) cout << " c" << i ;
}
cout << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: