历届试题 翻硬币-(贪心)

问题描述

小明正在玩一个“翻硬币”的游戏。

桌上放着排成一排的若干硬币。我们用 * 表示正面,用 o 表示反面(是小写字母,不是零)。

比如,可能情形是:**oo***oooo

如果同时翻转左边的两个硬币,则变为:oooo***oooo

现在小明的问题是:如果已知了初始状态和要达到的目标状态,每次只能同时翻转相邻的两个硬币,那么对特定的局面,最少要翻动多少次呢?

我们约定:把翻动相邻的两个硬币叫做一步操作,那么要求:

输入格式

两行等长的字符串,分别表示初始状态和要达到的目标状态。每行的长度<1000

输出格式

一个整数,表示最小操作步数。

样例输入1
**********
o****o****
样例输出1
5
样例输入2
*o**o***o***
*o***o**o***
样例输出2
1
解题思路:
官网显示是贪心题目。贪心?没看出贪在哪里。
每次翻2个硬币,则必须是偶数处错误才可能得到结果。一处错误,后面必然还有一处错误,则中间的都要翻一遍。从左到右翻一遍。暴力累加即可。
#include<stdio.h>
#include<algorithm>
#include<iostream>
#include<vector>
#include<stack>
#include<set>
#include<queue>
#include<cstring>
#define ll long long
using namespace std;

char a[10086];
char b[10086];

int main()
{
    scanf("%s%s",a,b);
    int len=strlen(a);
    int ans=0,x,y;
    bool flag=true;///初始化为true
    for(int i=0;i<len;i++)
    {
        if(a[i]!=b[i])
        {
            if(flag)
            {
                x=i;
                flag=false;///遇到奇数个错误改成false
            }
            else
            {
                y=i;
                flag=true;///遇到偶数个错误改成true
                ans+=y-x;///累加两个错误之间需要翻多少次  
            }
        }
    }
    printf("%d
",ans);
    return 0;
}
原文地址:https://www.cnblogs.com/shoulinniao/p/10428703.html