CFGym - 100712C.Street Lamps 贪心+模拟

本文介绍了一道关于在街道上安装路灯的算法题目,通过贪心算法确保每个街区都被照亮,给出了AC代码实现。

1.题目描述:

C. Street Lamps

Bahosain is walking in a street of N​blocks. Each block is either empty or has one lamp. If there is a lamp in ablock, it will light it’s block and the direct adjacent blocks. For example, if there is a lamp at block 3, it will lightthe blocks 2, 3, and 4.Given the state of the street, determine the minimum number of lamps to be installed such that each block islit.

Input

The first line of input contains an integer T (1 ≤ T ≤ 1025)​that represents the number of test cases.

The first line of each test case contains one integer N (1 ≤ N ≤ 100)​that represents the number of blocks inthe street.

The next line contains N​characters, each is either a dot ’.’ or an asterisk ’*’.A dot represents an empty block, while an asterisk represents a block with a lamp installed in it.

Output

For each test case, print a single line with the minimum number of lamps that have to be installed so that allblocks are lit.

Sample Input 

3

6

......

3

*.*

8

.*.....*

Sample Output

2

0

1

2.题目大意:

一条街上若干点(‘*’点)有路灯,路灯照亮的半径是1,问还能在‘.’处至少安装多少盏路灯使得全街被照亮

3.解题思路:

贪心地从左边开始判断,如果没被照亮则放路灯,这样可以保证第i点的前i - 1个位置都是被照亮的

4.AC代码:

#include <stdio.h>
#include <string.h>
#define maxn 101
using namespace std;
int vis[maxn];
char mp[maxn];


int main()
{
	int t;
	scanf("%d", &t);
	while (t--)
	{
		memset(vis, 0, sizeof(vis));
		int n, ans = 0;
		scanf("%d", &n);
		scanf("%s", mp);
		for (int i = 0; i < n; i++)
			if (mp[i] == '*')
			{
				vis[i] = 1;
				if (i - 1 >= 0)
					vis[i - 1] = 1;
				if (i + 1 < n)
					vis[i + 1] = 1;
			}
		for (int i = 0; i < n; i++)
		{
			if (!vis[i])
			{
				ans++;
				if (i + 1 < n && mp[i + 1] != '*')
				{
					vis[i] = vis[i + 1] = 1;
					if (i + 2 < n)
						vis[i + 2] = 1;
				}
				else
				{
					vis[i] = 1;
					if (i + 1 < n)
						vis[i + 1] = 1;
				}
			}
		}
		printf("%d\n", ans);
	}
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值