poj 3041 Asteroids

Bessie需要穿越一个充满小行星的N x N网格,使用武器清除每一行或列的小行星,目标是最少射击次数。通过建立图模型并求解最大流问题,找到最优解。

Description

Bessie wants to navigate her spaceship through a dangerous 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 conveniently located at the lattice points of the grid. 

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

Input

* Line 1: Two integers N and K, separated by a single space. 
* 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 of times Bessie must shoot.

Sample Input

3 4
1 1
1 3
2 2
3 2

Sample Output

2

你要很多个点
每个点在方格里
你每次消除可以是一行或是一列
求最小消除次数

将每个点对应的行列连边,求最大流
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<vector>
#include<queue>
#include<algorithm>
#define re return
#define inc(i,l,r) for(int i=l;i<=r;++i)
const int maxn=1505,maxm=20005;
using namespace std;
template<typename T>inline void rd(T&x)
{
	char c;bool f=0;
	while((c=getchar())<'0'||c>'9')if(c=='-')f=1;
	x=c^48;
	while((c=getchar())>='0'&&c<='9')x=x*10+(c^48);
	if(f)x=-x;
} 

int n,m,s,t,deep[maxn],k=1,hd[maxn],cur[maxn];
struct node{
	int to,nt,w;
}e[maxm];

inline void add(int x,int y,int z)
{
	e[++k].to=y;e[k].nt=hd[x];hd[x]=k;e[k].w=z;
	e[++k].to=x;e[k].nt=hd[y];hd[y]=k;e[k].w=0;
}

inline bool  bfs()
{
	queue<int>q;
	inc(i,1,t)deep[i]=0;
	deep[s]=1;
	q.push(s);
	while(!q.empty())
	{
		int u=q.front();
		q.pop();
		for(int i=hd[u];i;i=e[i].nt)
		{
			int v=e[i].to;
			if(!deep[v]&&e[i].w)
			{
				deep[v]=deep[u]+1;
				if(v==t)re 1;
				q.push(v);
			} 
		}
	}
	re 0;
}

inline int dfs(int u,int flow)
{
	if(u==t) re flow;
	int delta=flow;
	for(int &i=cur[u];i;i=e[i].nt)
	{
		int v=e[i].to;
		if(deep[v]==deep[u]+1&&e[i].w)
		{
			int d=dfs(v,min(delta,e[i].w));
			e[i].w-=d;e[i^1].w+=d;
			delta-=d;
			if(!delta)re flow;
		}
	}
	re flow-delta;
}

int main()
{
	rd(n),rd(m);
	s=(n<<1)+1;
	t=s+1;
	int x,y;
	inc(i,1,m)
	{
		rd(x),rd(y);
		add(x,y+n,1);
	}
	inc(i,1,n){
		add(s,i,1);
		add(i+n,t,1);
	}
	int ans=0;
	while(bfs())
	{
		inc(i,1,t)cur[i]=hd[i];
		ans+=dfs(s,n);
	} 
	printf("%d",ans);
	re 0;
} 

  

转载于:https://www.cnblogs.com/lsyyy/p/11291409.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值