Codeforce Round #557 Div.2 B - Ugly Pairs

贪心+思维

看到题目我竟然去写了个超级麻烦的枚举。。

其实我们可以先从最勉强的情况考虑,就是没一个字母与相邻的字母只要相差2就行了。

这启示我们把奇数位和偶数位的字母分开,在奇数位的字母和在偶数位的字母一定是合法的两个字符串,然后我们考虑一下怎样合并。

假设奇数位组成的字符串为a,偶数位组成的字符串位b,那么最简单的方法就是把a的尾接在b的头或者把a的头接在b的尾,让两个位数相差最多的字母接在一起。

事实上,这也是最理想的答案了,如果这样都不行,那么肯定就是No answer。

#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define full(a, b) memset(a, b, sizeof a)
using namespace std;
typedef long long ll;
inline int lowbit(int x){ return x & (-x); }
inline int read(){
    int X = 0, w = 0; char ch = 0;
    while(!isdigit(ch)) { w |= ch == '-'; ch = getchar(); }
    while(isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar();
    return w ? -X : X;
}
inline int gcd(int a, int b){ return a % b ? gcd(b, a % b) : b; }
inline int lcm(int a, int b){ return a / gcd(a, b) * b; }
template<typename T>
inline T max(T x, T y, T z){ return max(max(x, y), z); }
template<typename T>
inline T min(T x, T y, T z){ return min(min(x, y), z); }
template<typename A, typename B, typename C>
inline A fpow(A x, B p, C lyd){
    A ans = 1;
    for(; p; p >>= 1, x = 1LL * x * x % lyd)if(p & 1)ans = 1LL * x * ans % lyd;
    return ans;
}

int main(){

    int _ = read();
    for(; _; _ --){
        string s, o, e; cin >> s;
        for(int i = 0; i < s.size(); i ++){
            (s[i] - 'a' + 1) % 2 ? o.push_back(s[i]) : e.push_back(s[i]);
        }
        bool flag = false;
        sort(o.begin(), o.end()), sort(e.begin(), e.end());
        if(!o.empty() && !e.empty() && abs(e.back() - o.front()) != 1){
            cout << e + o << endl;
            flag = true;
        }
        else if(!o.empty() && !e.empty() && abs(o.back() - e.front()) != 1){
            cout << o + e << endl;
            flag = true;
        }
        else if(o.empty() || e.empty()){
            cout << s << endl;
            flag = true;
        }
        if(!flag) cout << "No answer" << endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/onionQAQ/p/10809673.html
今日推荐