ACM训练3

Stone on the tables

Problem Description

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.

问题连接:

问题分析:先判断n是否在1-50的范围内,因为字符个数是个变量所建立指向字符数组的指针来存储这些字符。用循环比较一个字符跟前一个字符是否相等,如果相等则要拿到,用sum这个变量来统计需要拿掉的个数。

AC代码如下:

#include <iostream>
using namespace std;
int main()
{
	int n = 0,sum=0;
	cin >> n;
	while(n < 1 || n>50) 
	{ cout << "please input again" << endl; cin >> n; }
	char *p = NULL;
	p = new char[n];
	cin >> p;
	for (int i = 1; i < n; i++)
	{
		p[i] == p[i - 1] ? sum++:sum = sum;
	}
	cout << sum;
	p = NULL;
	delete[]p;
    
}

猜你喜欢

转载自blog.csdn.net/weixin_43966635/article/details/84844472