試題 基礎練習 完美的代價
資源限制
時間限制:1.0s 內存限制:512.0MB
問題描述
迴文串,是一種特殊的字符串,它從左往右讀和從右往左讀是一樣的。小龍龍認爲迴文串纔是完美的。現在給你一個串,它不一定是迴文的,請你計算最少的交換次數使得該串變成一個完美的迴文串。
交換的定義是:交換兩個相鄰的字符
例如mamad
第一次交換 ad : mamda
第二次交換 md : madma
第三次交換 ma : madam (迴文!完美!)
輸入格式
第一行是一個整數N,表示接下來的字符串的長度(N <= 8000)
第二行是一個字符串,長度爲N.只包含小寫字母
輸出格式
如果可能,輸出最少的交換次數。
否則輸出Impossible
樣例輸入
5
mamad
樣例輸出
3
實現代碼
#include<iostream>
#include<string>
using namespace std;
int jud[26] = { 0 };
int main() {
int n, ans = 0, cnt = 0;
string str;
cin >> n >> str;
for (int i = 0; i < n; i++) jud[str[i] - 'a']++;
for (int i = 0; i < 26; i++) if (jud[i] & 1) cnt++;
if (cnt >= 2) cout << "Impossible" <<endl; //只要出現兩個單獨存在的字母就不可能迴文
else {
for (int i = 0; i < n / 2; i++) { // 只用排一半
int endpos = n - 1 - i; // 匹配的字母要從最右邊找,i表示已經排好的位置
int pos = str.rfind(str[i], endpos); // 所以後面的排好的部分也要減去,避免受到干擾
if (pos == i) swap(str[pos], str[pos + 1]), ans++, i--; //如果出現單獨數字,就先後退一格
else while (pos != endpos) swap(str[pos], str[pos + 1]), pos++, ans++;
}
cout << ans << endl;
}
return 0;
}