1. 程式人生 > >Stones on the Table【CodeForces - 266A】

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++;

如果下一個石頭顏色與此石頭相同,計數器自增,判斷完所有石頭後輸出計數器的值即可。