Stones on the Table【CodeForces - 266A】

Stones on the Table问题解析

题目

There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.

Time limitMemory limitSourceTagEditoria
1000 ms262144 kBCodeforces Round #163 (Div. 2)simplementation *800Announcement

input

The first line contains integer n (1 ≤ n ≤ 50) — the number of stones on the table.
The next line contains string s, which represents the colors of the stones. We’ll consider the stones in the row numbered from 1 to n from left to right. Then the i-th character s equals “R”, if the i-th stone is red, “G”, if it’s green and “B”, if it’s blue.

output

Print a single integer — the answer to the problem.

Examples

inputoutput
3 RRG1
5 RRRRR4
4 BRBG0
问题链接:CodeForces - 266A

问题描述

桌面上有一排石头,每个石头可能是红绿蓝(用字符RGB表示)三种颜色,问至少要取走多少块石头才能使每一块相邻的石头都不同色。

问题分析

可以用字符串存储那一排石头,然后对字符串中的每一个元素进行判断,从头开始,若要相邻的石头都不同色,只需要当后一个石头与当前石头是同色时取走当前石头即可,于是计算要取走的石头数量便是答案。

AC通过的C++语言程序代码如下:

#include<iostream>
using namespace std;
int main()
{
	int counter = 0;
	int n;
	cin >> n;
	char *stone = new char[n];
	cin >> stone;
	for (int i = 0; i < n; i++)
		if (stone[i] == stone[i + 1])
			counter++;
	cout << counter;
}

代码分析

首先声明了计数器变量和石头总数变量,再根据输入的石头总数创建了字符串,然后输入石头的颜色

	int counter = 0;
	int n;
	cin >> n;
	char *stone = new char[n];
	cin >> stone;

计算需要取走多少石头:

	for (int i = 0; i < n; i++)
		if (stone[i] == stone[i + 1])
			counter++;

如果下一个石头颜色与此石头相同,计数器自增,判断完所有石头后输出计数器的值即可。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值