8.15 G – Asteroids

本文介绍了一种算法,用于解决太空飞船穿越布满障碍物的网格时,使用最少次数射击清除所有障碍的问题。通过建立行与列之间的关联,利用最小顶点覆盖的概念,有效地求解出所需的最少射击次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值