码迷,mamicode.com
首页 > 其他好文 > 详细

bestcoder#37_1001 字符串,贪心

时间:2015-04-11 23:53:05      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:

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 ?rst 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

 

bestcoder#37_1001 字符串,贪心

标签:

原文地址:http://www.cnblogs.com/--560/p/4418706.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!