POJ Evil Straw Warts Live (貪心)

Evil Straw Warts Live
Time Limit: 2000MS
Memory Limit: 65536K
Total Submissions: 850
Accepted: 239

Description

A palindrome is a string of symbols that is equal to itself when reversed. Given an input string, not necessarily a palindrome, compute the number of swaps necessary to transform the string into a palindrome. By swap we mean reversing the order of two adjacent symbols. For example, the string "mamad" may be transformed into the palindrome "madam" with 3 swaps:
swap "ad" to yield "mamda"
swap "md" to yield "madma"
swap "ma" to yield "madam"

Input

The first line of input gives n, the number of test cases. For each test case, one line of input follows, containing a string of up to 8000 lowercase letters.

Output

Output consists of one line per test case. This line will contain the number of swaps, or "Impossible" if it is not possible to transform the input to a palindrome.

Sample Input

3
mamad
asflkj
aabb

Sample Output

3
Impossible
2


題目大意:給一個單詞,爲了讓它變成一個迴文串,允許相鄰的兩個數交換。求最少的交換次數,使得單詞變成一個迴文串。


解題思路:首先判斷一下字母出現的奇數次的個數是否大於1, 大於1不滿足。然後從左右開始遍歷判斷tmp[left] 和 tmp[right]是否相同,相同跳過, 不相同的話找到從左邊開始第一個使得tmp[left + l] == tmp[right], 和從右邊開始第一個使得tmp[left] == tmp[right + r]。比較l 和 r 的大小然後考慮該移動哪一邊。

但是在這裏我只用了temp[left]==temp[right-r],將所有的r求和即可。


 #include<iostream>
 #include<cstdio>
 #include<cstring>
 #include<algorithm>
 #include<cmath>
 using namespace std;
 char arr[10000];
 int b[28];
 int solve()
 {
     int ans=0,len=strlen(arr),high=len-1;
     for(int i=0;i<(len+1)/2-1;i++){
        if(b[arr[i]-'a']>1){
            for(int j=high;j>i;j--){
                if(arr[i]==arr[j]){
                    for(int k=j+1;k<=high;k++){
                        arr[k-1]=arr[k];
                        ans++;
                    }
                    arr[high]=arr[i];
                    high--;
                    break;
                }
            }
            b[arr[i]-'a']-=2;
        }
        else{
            swap(arr[i],arr[i+1]);
            ans++;
            --i;
        }
     }
     return ans;
 }
 int main()
 {
     int n;
     scanf("%d",&n);
     while(n--){
        memset(b,0,sizeof(b));
        scanf("%s",arr);
        for(int i=0;arr[i];++i){
            ++b[arr[i]-'a'];
        }
        int cnt=0;
        for(int i=0;i<27;i++){
            if(b[i]%2) cnt++;
        }
        if(cnt>=2){
            printf("Impossible\n");
            continue;
        }
        else{
            printf("%d\n",solve());
        }
     }
     return 0;
 }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章