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.
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

問題鏈接(https://vjudge.net/problem/CodeForces-266A)

問題簡述:桌子上n個(gè)(i<=n=50)有三種顏色的石頭,記紅色為"R",綠色為"G",藍(lán)色為“B",需要計(jì)算要從桌子上取最少數(shù)量的石頭。才能使桌子上剩下的石頭相鄰之間不會(huì)有顏色相同,桌子上的顏色及個(gè)數(shù)由自己輸入,最后輸出答案

問題分析;當(dāng)n=3,石頭的顏色為RRG時(shí),輸出的答案為1,即只需拿一個(gè)石頭出來即可滿足條件。當(dāng)n=5,石頭的顏色為RRRRR時(shí),輸出答案為4。當(dāng)n=4,石頭的顏色為BRBG時(shí),輸出的答案為0;可以發(fā)現(xiàn),我們要拿出的石頭個(gè)數(shù)為桌子上相同顏色石頭個(gè)數(shù)減去一

程序分析:定義一個(gè)動(dòng)態(tài)數(shù)組,長度為n(桌子上的石頭的個(gè)數(shù));定義一個(gè)函數(shù)find,函數(shù)中通過for語句來對(duì)桌子上的所有石頭的顏色進(jìn)行判斷,如果相同,則局部變量count+1,最后通過函數(shù)調(diào)用把結(jié)果輸出
AC的C++代碼如下;

#include <iostream>
using namespace std;
int find(char*S,const int n)
{
    int count = 0;
    for (int i = 0; i <= n - 1; i++)
    {
        
        if (S[i] ==S[i + 1])
        {
            count++;
        }
    }
    return count;
}
int main()
{
    int n;
    
    while (cin >> n)
    {
        char* S = new char[n];
        cin >> S;
        cout<<find(S, n);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容