Rikka with string
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 581 Accepted Submission(s): 227
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?
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
a?bb?
3
aaa
Sample Output
aabba
QwQ
QwQ
Source
#include<stdio.h>
#include<string.h>
int cnt = ;
char st[ + ] ;
char rst [ + ] ;
int n , vis[ + ]; void rev (char s[ + ])
{
char tmp[ + ] ;
int k = , i ;
for (i = strlen (st) - ; i >= ; i-- , k ++) {
tmp[k] = st[i] ;
}
tmp[k] = '\0' ;
strcpy (s , tmp) ;
} int main ()
{
// freopen ("a.txt" , "r" , stdin ) ;
while (~ scanf ("%d" , &n)) {
getchar () ;
gets (st) ;
cnt = ;
for (int i = ; st[i] != '\0' ;i ++) {
if (st[i] == '?') {
vis[cnt ++] = i ;
st[i] = 'a' ;
}
}
int i ;
rev (rst) ;
if (strcmp (st , rst)== ) {
for (i = cnt - ; i >= ; i--) {
st[vis[i]] = 'b' ;
rev (rst) ;
if (strcmp (rst , st)!= ) {
break ;
}
st[vis[i]] = 'a' ;
}
if (i == - ) puts ("QwQ") ;
else puts (st) ;
}
else puts (st) ;
}
return ;
}
如果没有不是回文串的限制可以把所有的?都变成a,这样一定是字典序最小的。而现在有了回文串的限制,我们可以从小到大枚举最靠后的不在字符串正中心的问号选什么,其他的问号依然换成a,显然如果有解,这样一定可以得到字典序最小的解。注意特判没有问号以及问号在正中心的情况。
时间复杂度O(n)