Coloring Colorfully
题目描述
N块瓦片从左到右排成一行。每个块的初始颜色由长度为N的字符串S表示。
如果S的第i个字符为0,则左边的第i个平铺将被漆成黑色,如果该字符为1,则漆成白色。
你想重新油漆一些瓷砖黑色或白色,使任何两个相邻的瓷砖有不同的颜色。
至少需要重新粉刷多少瓷砖才能满足条件?
Constraints
1≤|S|≤105
Si is 0 or 1.
输入
Input is given from Standard Input in the following format:
S
S
输出
Print the minimum number of tiles that need to be repainted to satisfy the condition.
样例输入 Copy
000
样例输出 Copy
1
提示
The condition can be satisfied by repainting the middle tile white\
解析:1.从前向后枚举时:如果两个都是相同的,就变后面的,因为保证前面是可以的那么后面也是行的
2.从后往前枚举一次,如果相同就变前面的
3.两种情况取最小值
AC代码:
#include<cstdio> #include<iostream> #include<algorithm> #include<map> #include<bits/stdc++.h> using namespace std; typedef long long ll; inline int read() { int x=0,f=1;char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} return x*f; } const int INF=0x3f3f3f3f; const int maxn=5e5; char a[maxn]; char b[maxn]; int sum[maxn]; int len; void inint(){ scanf("%s",a+1); len=strlen(a+1); for(int i=1;i<=len;i++){ b[i]=a[i]; } } int main(){ inint(); int ans1=0; for(int i=2;i<=len;i++){ if(a[i]=='1'&&a[i-1]=='1'){ a[i]='0'; ans1++; } else if(a[i]=='0'&&a[i-1]=='0'){ a[i]='1'; ans1++; } } int ans2=0; for(int i=len-1;i>=1;i--){ if(b[i]=='1'&&b[i+1]=='1'){ b[i]='0'; ans2++; } else if(b[i]=='0'&&b[i+1]=='0'){ b[i]='1'; ans2++; } } printf("%d",min(ans1,ans2)); }