[CF从零单排#9]266A - Stones on the Table

题目来源:http://codeforces.com/problemset/problem/266/A

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.

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
3
RRG
output
1
input
5
RRRRR
output
4
input
4
BRBG
output
0

题目大意:

桌子上有三种颜色的石头,R(红色)G(绿色)B(蓝色),它们排成一排。不能调整石头的顺序,只能拿掉石头,问至少要拿掉多少块石头,才能保证相邻两块石头颜色是不同的。

题目分析:

模拟题,实际上就是问后面的石头颜色是否和前面的石头一样,如果一样,就需要拿掉这块。扫描一遍n块石头,可以得出。

参考代码:

#include <bits/stdc++.h>
using namespace std;
int main(){
	int n;
	char s[100];
	cin >> n;
	cin >> s;
	int k = 0, ans = 0;
	for(int i=1; i<n; i++){
		if(s[i]==s[k])
			ans ++;
		else
			k = i;
	}
	cout << ans;
	return 0;
}
posted @ 2020-07-24 16:37  gdgzliu  阅读(181)  评论(0编辑  收藏  举报