Rikka with string
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 561 Accepted Submission(s): 220
Problem Description
As we know, Rikka is poor at math. Yuta is worrying about this situation, so he gives Rikka some math tasks to practice. There is one of them:
One day, Yuta got a string which contains n letters but Rikka lost it in accident. Now they want to recover the string. Yuta remembers that the string only contains lowercase letters and it is not a palindrome string. Unfortunately he cannot remember some letters. Can you help him recover the string?
It is too difficult for Rikka. Can you help her?
One day, Yuta got a string which contains n letters but Rikka lost it in accident. Now they want to recover the string. Yuta remembers that the string only contains lowercase letters and it is not a palindrome string. Unfortunately he cannot remember some letters. Can you help him recover the string?
It is too difficult for Rikka. Can you help her?
Input
This problem has multi test cases (no more than
20
). For each test case, The first line contains a number
n(1≤n≤1000)
. The next line contains an n-length string which only contains lowercase letters and ‘?’ – the place which Yuta is not sure.
Output
For each test cases print a n-length string – the string you come up with. In the case where more than one string exists, print the lexicographically first one. In the case where no such string exists, output “QwQ”.
Sample Input
5 a?bb? 3 aaa
Sample Output
aabba QwQ
Source
Recommend
问题描述
众所周知,萌萌哒六花不擅长数学,所以勇太给了她一些数学问题做练习,其中有一道是这样的:
有一天勇太得到了一个长度为
n
的字符串,但是六花一不小心把这个字符串搞丢了。于是他们想要复原这一个字符串。勇太记得这个字符串只包含小写字母而且这个串不是回文串。然而不幸的是他已经不记得这个字符串中的一些字符了,你可以帮他复原这个字符串吗?
当然,这个问题对于萌萌哒六花来说实在是太难了,你可以帮帮她吗?
输入描述
多组数据,数据组数不超过 20 ,每组数据第一行两个正整数 n 。接下来一行一个长度为 n 的只包含小写字母和’?’的字符串,’?’表示勇太已经忘了这一个位置的字符了。 1≤n≤103
输出描述
每组数据输出仅一行一个长度为n的仅包含小写字母的字符串,如果有多种合法解,请输出字典序最小的,如果无解,请输出”QwQ”
分析:
深搜,对每个 ‘?’ ,要求字典序最小,从 ‘a’ 开始放置。
搜索完毕判断回文串。
代码:
#include<iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;
char ch[1010];
int ok, n;
int hui() //判断是否为回文串
{
int L = 0, R = n - 1;
while(L < R) {
if(ch[L] != ch[R]) return 0;
L++;
R--;
}
return 1;
}
void dfs(int cur)
{
if(ok) return; //若已经有满足要求的,它一定是字典序最小的,不再搜索
if(cur == n ) {
if(!hui()) {
printf("%s\n", ch);
ok = 1;
}
return;
}
if(ch[cur] != '?') {
dfs(cur + 1);
return;
}
else for(char c = 'a'; c <= 'z'; c++) { //要求字典序最小,从 a 开始尝试
ch[cur] = c;
dfs(cur + 1);
ch[cur] = '?'; //忘了此处,WA了好几次!若不修改为原值,再次递归搜到
} //此处时,它的值不再是‘?’
}
int main()
{
while(~scanf("%d", &n)) {
scanf("%s", ch);
ok = 0;
dfs(0);
if(!ok) printf("QwQ\n");
}
return 0;
}