nszkay 2024-01-25 16:10 采纳率: 0%
浏览 13

Vasya and Petya have invented a new game.

Vasya and Petya have invented a new game. Vasya takes a stripe consisting of 1 × n square and paints the squares black and white. After that Petya can start moves — during a move he may choose any two neighboring squares of one color and repaint these two squares any way he wants, perhaps in different colors. Petya can only repaint the squares in white and black colors. Petya’s aim is to repaint the stripe so that no two neighboring squares were of one color. Help Petya, using the given initial coloring, find the minimum number of moves Petya needs to win.

Input
The first line contains number n (1 ≤ n ≤ 1000) which represents the stripe’s length. The second line contains exactly n symbols — the line’s initial coloring. 0 corresponds to a white square, 1 corresponds to a black one.

Output
If Petya cannot win with such an initial coloring, print -1. Otherwise print the minimum number of moves Petya needs to win.

Sample 1
Inputcopy Outputcopy
6
111010
1
Sample 2
Inputcopy Outputcopy
5
10001
1
Sample 3
Inputcopy Outputcopy
7
1100010
2
Sample 4
Inputcopy Outputcopy
5
00100
2
Note
In the first sample Petya can take squares 1 and 2. He repaints square 1 to black and square 2 to white.

In the second sample Petya can take squares 2 and 3. He repaints square 2 to white and square 3 to black。

  • 写回答

1条回答 默认 最新

  • 叫兽-郭老师 新星创作者: Java技术领域 2024-01-25 16:21
    关注

    以下是一个可能的C++实现,我们可以遍历这条彩带,统计满足两个相邻颜色一样的方案数目,由彩带长度的奇偶性,我们会有两种不同的上色方案,那么最后答案就是取这两种方案里面最小的。

    #include<bits/stdc++.h>
    using namespace std;
    
    const int maxn = 1e3+100;
    char s[maxn];
    
    int main(){
        int n;
        cin>>n>>s;
        int case1=0,case2=0;
        for(int i = 0;i<n;i++){
            if(i%2==0){
                // 假设第一个位置为黑色
                if(s[i]=='1') ++case1;
                // 假设第一个位置为白色
                else ++case2;
            }
            else{
                if(s[i]=='1') ++case2;
                else ++case1;
            }
        }
        cout<<min(case1,case2);
        return 0;
    }
    
    

    在这里,case1和case2都表示可能的变化次数,它们分别对应两种上色方案,一种是奇数位为黑,另一种是奇数位为白,最后输出变化次数较少的方案的次数即可。
    希望这个答案能帮到你,如果你还有其他问题,欢迎随时提问。

    评论

报告相同问题?

问题事件

  • 创建了问题 1月25日