蓝桥杯历届试题翻硬币解题报告---贪心策略

版权声明:转载请注明出处:https://blog.csdn.net/qq1013459920 https://blog.csdn.net/qq1013459920/article/details/88084615

                                               历届试题 翻硬币  

问题描述

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

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

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

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

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

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

输入格式

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

输出格式

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

扫描二维码关注公众号,回复: 5392666 查看本文章

样例输入1

**********
o****o****

样例输出1

5

样例输入2

*o**o***o***
*o***o**o***

样例输出2

1

贪心策略:从0下标开始匹配两行字符串,第一次出现字符不同位置为s 下一次出现字符不同位置为e,把所有的(e - s)累加即为最小操作步数。

 AC Code: 

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <climits>
#include <list>
using namespace std;
typedef long long ll;
#define lowbit(x) x & -x;
#define INF 0x3f3f3f3f;
#define PI 3.1415927 
const static int MAX_N = 1e4 + 5;
int a[MAX_N];
int main() {
	char s1[1005], s2[1005];
	while (scanf("%s%s", s1, s2) != EOF) {
		int len = strlen(s1);
		int res = 0;
		int i = 0;
		while (i < len) {
			if (s1[i] == s2[i]) {
				i++;
			}
			else {
				i++;
				if (i < len) {
					while (i < len && s1[i] == s2[i]) {
						res++;
						i++;
					}
					if (s1[i] != s2[i]) {
						res++;
						i++;
					}
				}
			}
		}
		printf("%d\n", res);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq1013459920/article/details/88084615