51nod 1276:岛屿的数量 很好玩的题目

题目来源: Codility
基准时间限制:1 秒 空间限制:131072 KB 分值: 20 难度:3级算法题
 收藏
 取消关注
有N个岛连在一起形成了一个大的岛屿,如果海平面上升超过某些岛的高度时,则这个岛会被淹没。原本的大岛屿则会分为多个小岛屿,如果海平面一直上升,则所有岛都会被淹没在水下。
给出N个岛的高度。然后有Q个查询,每个查询给出一个海平面的高度H,问当海平面高度达到H时,海上共有多少个岛屿。例如:
岛屿的高度为:{2, 1, 3, 2, 3}, 查询为:{0, 1, 3, 2}。
当海面高度为0时,所有的岛形成了1个岛屿。
当海面高度为1时,岛1会被淹没,总共有2个岛屿{2} {3, 2, 3}。
当海面高度为3时,所有岛都会被淹没,总共0个岛屿。
当海面高度为2时,岛0, 1, 3会被淹没,总共有2个岛屿{3} {3}。
Input
第1行:2个数N, Q中间用空格分隔,其中N为岛的数量,Q为查询的数量(1 <= N, Q <= 50000)。
第2 - N + 1行,每行1个数,对应N个岛屿的高度(1 <= A[i] <= 10^9)。
第N + 2 - N + Q + 1行,每行一个数,对应查询的海平面高度(1 <= Q[i] <= 10^9)。
Output
输出共Q行,对应每个查询的岛屿数量。
Input示例
5 4
2
1
3
2
3
0
1
3
2
Output示例
1
2
0
2

一开始没什么思路,后来把岛屿和询问都记录位置,然后按照高低排序之后,时间减少了很多。

现在觉得这个题很水了。。。具体思路见代码。

代码:

#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <string>
#include <cstring>
#pragma warning(disable:4996)
using namespace std;

int n, q;
int question[50005];
int embz_island[50005];//表示各个位置的岛的淹没情况。embz_island[i]=1,表示位置为i的岛已经被淹没了。

struct qu
{
	int va;
	int pos;
}query[50005];

struct is
{
	int height;
	int pos;
}island[50005];

bool cmp1(is no1, is no2)
{
	return no1.height < no2.height;
}

bool cmp2(qu no1, qu no2)
{
	return no1.va < no2.va;
}

void work()
{
	int i, j, ans, pos;
	memset(embz_island, 0, sizeof(embz_island));

	j = 0;//从高度为0的岛开始搜索
	ans = 1;//一开始有1个岛站立
	for (i = 0; i < q; i++)
	{
		for (; j < n; j++)
		{
			if (query[i].va >= island[j].height)
			{
				pos = island[j].pos;
				embz_island[pos] = 1;

				if (pos == 1)//第一个岛屿与第n个岛屿在边上,需要特殊判断
				{
					if (embz_island[pos + 1] == 1)
						ans--;
					continue;
				}
				if (pos == n)
				{
					if (embz_island[pos - 1] == 1)
						ans--;
					continue;
				}
				if (embz_island[pos - 1] == 0 && embz_island[pos + 1] == 0)//左右两边都没有被淹,ans加一
				{
					ans++;
				}
				else if (embz_island[pos - 1] == 1 && embz_island[pos + 1] == 1)//左右两边都被淹了,ans减一
				{
					ans--;
				}
			}
			else
			{
				break;
			}
		}
		pos = query[i].pos;
		question[pos] = ans;
	}
}

int main()
{
	//freopen("i.txt", "r", stdin);
	//freopen("o.txt", "w", stdout);

	int i;
	scanf("%d%d", &n, &q);
	for (i = 0; i < n; i++)
	{
		scanf("%d", &island[i].height);
		island[i].pos = i + 1;
	}
	sort(island, island + n, cmp1);

	for (i = 0; i < q; i++)
	{
		scanf("%d", &query[i].va);
		query[i].pos = i;
	}
	sort(query, query + q, cmp2);

	work();

	for (i = 0; i < q; i++)
	{
		printf("%d
", question[i]);
	}

	//system("pause");
	return 0;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/lightspeedsmallson/p/4899526.html