bestcoder#37_1001 字符串,贪心

bestcoder#37_1001 字符串,dfs

Rikka with string

Accepts: 395
Submissions: 2281
Time Limit: 2000/1000 MS (Java/Others)
Memory Limit: 65536/65536 K (Java/Others)
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(1n1000). 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
题意:在问号中填上字母,使字符串不是回文且字典序最小
思路:贪心,考虑到字典序最小,先扫一遍贪心地在问号处填上'a',再扫一遍判断是否回文,如果不是直接输出,如果是回文,考虑到字典序最小,只需更改最右端的问号处的a为b即可输出,但如果最右端的问号恰好在字符串的中点,特判跳过即可。
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<string>
#include<vector>

using namespace std;

const int maxn=1000100;
const int INF=(1<<29);

int n;
string s;
vector<int> v;

bool ispalin(string s)
{
    for(int i=0;i<s.length();i++){
        if(s[i]!=s[n-1-i]) return false;
    }
    return true;
}

int main()
{
    while(cin>>n>>s){
        v.clear();
        bool flag=0;
        for(int i=0;i<n;i++){
            if(s[i]=='?'){
                s[i]='a';
                v.push_back(i);
            }
        }
        if(!ispalin(s)) cout<<s<<endl;
        else{
            for(int i=(int)v.size()-1;i>=0;i--){
                if(v[i]!=n/2||n%2==0){
                    s[v[i]]='b';
                    flag=1;
                    break;
                }
            }
            if(flag) cout<<s<<endl;
            else cout<<"QwQ"<<endl;
        }
    }
    return 0;
}
View Code

 

posted @ 2015-04-11 23:15  __560  阅读(230)  评论(0编辑  收藏  举报