Overlooking the captivating blend of myriads of vernal hues, Arkady the painter lays out a long, long canvas.
Arkady has a sufficiently large amount of paint of three colours: cyan, magenta, and yellow. On the one-dimensional canvas split into nconsecutive segments, each segment needs to be painted in one of the colours.
Arkady has already painted some (possibly none or all) segments and passes the paintbrush to you. You are to determine whether there are at least two ways of colouring all the unpainted segments so that no two adjacent segments are of the same colour. Two ways are considered different if and only if a segment is painted in different colours in them.
The first line contains a single positive integer n (1 ≤ n ≤ 100) — the length of the canvas.
The second line contains a string s of n characters, the i-th of which is either 'C' (denoting a segment painted in cyan), 'M' (denoting one painted in magenta), 'Y' (one painted in yellow), or '?' (an unpainted one).
If there are at least two different ways of painting, output "Yes"; otherwise output "No" (both without quotes).
You can print each character in any case (upper or lower).
5 CY??Y
Yes
5 C?C?Y
Yes
5 ?CYC?
Yes
5 C??MM
No
3 MMY
No
For the first example, there are exactly two different ways of colouring: CYCMY and CYMCY.
For the second example, there are also exactly two different ways of colouring: CMCMY and CYCMY.
For the third example, there are four ways of colouring: MCYCM, MCYCY, YCYCM, and YCYCY.
For the fourth example, no matter how the unpainted segments are coloured, the existing magenta segments will prevent the painting from satisfying the requirements. The similar is true for the fifth example.
思路:dfs搜索所有‘?’所在的位置,然后在每一个‘?’的位置枚举放入C/Y/M
代码:
| #include<cstdio> #include<cstring> #include<iostream> #include<algorithm> using namespace std; char str[110]; char temp[10]= {'C','Y','M'}; int num[110],cnt=0,ans=0,flag=0; void dfs(int x) ///搜索每一个‘?’的位置 { if(flag) ///用来结束搜索 return ; if(x == cnt) { ans++; if(ans >= 2) ///因为只需要大于2就可以yes了,不然会超时 { flag=1; ///标记一个flag,表示可以结束了 } return ; } for(int i=0; i<3 ; ++i) ///每个‘?’的位置都依次尝试放入C/Y/M,然后再判断是否满足 { int index=num[x]; str[index]=temp[i]; if(str[index]!=str[index-1] && str[index]!=str[index+1]) ///判断在‘?’放入字符后,是否满足和前面和后面不一样 { dfs(x+1); ///当前位置满足,则进行下一个位置搜索 str[num[x+1]]='?'; ///如果不满足,则需要把上一个位置标记回‘?’不然回溯回去再放的时候,会错误判断 } } } int main() { int n; scanf("%d",&n); scanf("%s",str+1); str[0]='#'; str[strlen(str)]='#'; ///在开头和结尾设置一个‘#’可以方便不越界 for(int i=1; str[i]!='\0' ; ++i) ///检查是否有2个相同的字符,所以不符合 { if(str[i] == str[i-1] && str[i]!='?') { printf("No\n"); return 0; } } for(int i=1; str[i]!='\0' ; ++i) { if(str[i]=='?') ///存入所有‘?’的位置 { num[cnt++]=i; } } if(cnt==0) { printf("No"); return 0; } dfs(0); if(ans < 2) { printf("No\n"); } else printf("Yes\n"); return 0; } | |
本文介绍了一道编程题目,要求在一维的画布上用三种颜色进行填色,并且不能让相邻的颜色相同。通过DFS搜索算法来寻找至少两种不同的填色方案。

552

被折叠的 条评论
为什么被折叠?



