UVALive 4627 Islands(BFS+并查集)

题目链接:【UVALive 4627】

输入n*m的数字矩阵,矩阵上的数字表示的是水的深度,在第i年,水的深度应该是i,输入num个年份,输出每个年份里,水的深度高出的区块有几个


第二年,水的最高深度是2,超出的部分就是上述的阴影区域,是3块,输出3

先用优先队列,按水的深度排序,深度大的在前面,并查集是用来记录他们是不是属于同一个区块

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
using namespace std;
const int inf=1e5+10;
int t, n, m, num;
int p[1010][1010], fa[10*inf];
int a[inf], b[inf], f[4][2] = {0,1,1,0,0,-1,-1,0};
int ans;
struct node
{
	int x, y, h;
	friend bool operator < (const node n1, const node n2)
	{
		return n1.h<n2.h;
	}
}s, e;
priority_queue<node>q;
int find(int x)  
{  
    if(x!=fa[x]) fa[x] = find(fa[x]);  
    return fa[x];  
}
void father(int x, int y)
{
	int fx = find(x), fy = find(y);
	if(fx!=fy)
	{
		ans--;
		fa[fy]=fx;
	}
}
void bfs()
{
	int k=num;
	ans=0;
	while(!q.empty())
	{
		s = q.top(), q.pop();
		while(k && s.h<=a[k]) b[k]=ans, k--;
		if(k==0) break;
		ans++;
		for(int i=0; i<4; i++)
		{
			e.x = s.x+f[i][0];
			e.y = s.y+f[i][1];
			if(e.x<1||e.x>n||e.y<1||e.y>m||p[e.x][e.y]<=a[k]) continue;
			father((s.x-1)*m+s.y, (e.x-1)*m+e.y);
		}
	}
	for(int i=1; i<=k; i++) b[i]=ans;
}
int main()
{
	scanf("%d", &t);
	while(t--)
	{
		while(!q.empty()) q.pop();
		scanf("%d%d", &n, &m);
		for(int i=1; i<=n*m; i++) fa[i] = i;
		for(int i=1; i<=n; i++)
		{
			for(int j=1; j<=m; j++)
			{
				scanf("%d", &p[i][j]);
				s.x=i, s.y=j, s.h=p[i][j];
				q.push(s);
			}
		}
		scanf("%d", &num);
		for(int i=1; i<=num; i++)
		{
			scanf("%d", &a[i]);
		}
		bfs();
		for(int i=1; i<=num; i++)
		{
			printf("%d ", b[i]);
		}
		printf("\n");
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值