8.15 G – Asteroids

来源:互联网 发布:vc界面编程经典实例 编辑:程序博客网 时间:2024/06/14 14:13

G – Asteroids

Bessie wants to navigate her spaceship through adangerous asteroid field in the shape of an N x N grid (1 <= N <= 500).The grid contains K asteroids (1 <= K <= 10,000), which are convenientlylocated at the lattice points of the grid. 

Fortunately, Bessie has a powerful weapon that can vaporize all the asteroidsin any given row or column of the grid with a single shot.This weapon is quiteexpensive, so she wishes to use it sparingly.Given the location of all theasteroids in the field, find the minimum number of shots Bessie needs to fireto eliminate all of the asteroids.

Input

* Line 1: Two integers N and K, separated by a singlespace. 
* Lines 2..K+1: Each line contains two space-separated integers R and C (1<= R, C <= N) denoting the row and column coordinates of an asteroid,respectively.

Output

* Line 1: The integer representing the minimum number oftimes Bessie must shoot.

Sample Input

3 4

1 1

1 3

2 2

3 2

Sample Output

2

Hint

INPUT DETAILS: 
The following diagram represents the data, where "X" is an asteroidand "." is empty space: 
X.X 
.X. 
.X. 

OUTPUT DETAILS: 
Bessie may fire across row 1 to destroy the asteroids at (1,1) and (1,3), andthen she may fire down column 2 to destroy the asteroids at (2,2) and (3,2).


题意:一个飞船在飞,N*N的网格里面有障碍,一个子弹可以打穿一行或者一列,让找消除所有障碍的最小子弹
思路:以行作为x集合,以列作为y集合,一个行星在(x,y),则x对应X中的点向y对应y中的点连一条边,则某个顶点一旦被选,则与之相连的边(也就是行星)都会被选,也就是选出最少的顶点覆盖所有的边,即最小顶点覆盖。

#include<stdio.h>#include<string.h>int a[1000][1000],s[1000],b[1000];int m,n;int dfs(int x){int i;for(i=1;i<=n;i++){if(b[i]==0&&a[x][i]==1){b[i]=1;if(s[i]==-1||dfs(s[i])){s[i]=x;return 1;}}}return 0;}int main(){int i,j,k,t1,t2,sum;while(scanf("%d%d",&n,&m)!=EOF){memset(a,0,sizeof(a));memset(s,-1,sizeof(s));for(i=1;i<=m;i++){scanf("%d%d",&t1,&t2);a[t1][t2]=1;}sum=0;for(i=1;i<=n;i++){memset(b,0,sizeof(b));if(dfs(i))sum++;}printf("%d\n",sum);}return 0;}



原创粉丝点击