eoj 3451

題意:給定一個長度爲n(n<105) 且僅由小寫英文字母構成的字符串,求它的一個重排列,使得構成的字符串於之前字符串上每個對應位置上的字母都不一樣。

思路:貪心,找到出現次數最多的字母,然後把它優先填到出現次數少的字母那裏,然後其餘字符串整個右移「出現最多的字母出現次數」位,得到的就是結果。

(開始我想的是按字母次數多少倒過來擺放,例如aabbccc變成cccbbaa,但是這樣不行,於是就猜想如何在這個倒過來擺放的序列上優化修改。殊不知一開始這樣的想法就錯了。以後不能總在自己的思路上往下走,應當質疑原先思路是否正確。)

代碼:

#include <cstdio>
#include <cstring>
#include <algorithm>
#define LL long long
#define ull unsigned long long

using namespace std;
const int maxn = 100010;

int cnt[30], pos[maxn];
char s[maxn], ans[maxn];

bool cmp(int a, int b) {
    int x = s[a] - 'a', y = s[b] - 'a';
    if(cnt[x] == cnt[y])
        return x < y;
    return cnt[x] < cnt[y];
}

int main() {
    //freopen("in.txt","r",stdin);
    while(scanf("%s",s) == 1) {
        memset(cnt, 0, sizeof(cnt));
        int len = strlen(s);
        for(int i=0; i<len; i++) {
            cnt[s[i]-'a'] ++;
            pos[i] = i;
        }
        int alpha = 0, mx = -1;
        for(int i=0; i<26; i++) if(cnt[i] >= mx) {
            mx = cnt[i];
            alpha = i;
        }
        sort(pos, pos+len, cmp);
        for(int i=0; i<len; i++) {
            if(i < mx)
                ans[pos[i]] = alpha + 'a';
            else
                ans[pos[i]] = s[pos[i-mx]];
        }
        bool f = 1;
        for(int i=0; i<len; i++)
            if(s[i] == ans[i]) f = 0;
        if(f) {
            for(int i=0; i<len; i++)
                putchar(ans[i]);
            puts("");
        }
        else
            puts("impossible");
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章