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 limit Memory limit Source Tag Editoria
1000 ms 262144 kB Codeforces Round #163 (Div. 2) simplementation *800 Announcement

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

input output
3 RRG 1
5 RRRRR 4
4 BRBG 0

问题链接: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++;

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

猜你喜欢

转载自blog.csdn.net/qq_43736451/article/details/84873590