当前位置: 首页 > 工具软件 > WARTS > 使用案例 >

uva 10716 - Evil Straw Warts Live(greedy)

郁光熙
2023-12-01

Problem D: Evil Straw Warts Live

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"

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 100 lowercase letters. 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

Output for Sample Input

3
Impossible
2
 
#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
#include <cmath>
using namespace std;

const int maxn = 110;
string str;
int letter[30];

void initial(){
   for(int i = 0; i < 30; i++){
        letter[i] = 0;
   }
   str.clear();
}

void computing(){
    for(int i = 0; i < str.length(); i++){
        letter[str[i]-'a']++;
    }
    int odd = 0;
    for(int i = 0; i < 30; i++){
        if(letter[i]%2) odd++;
        if(odd > 1){
            printf("Impossible\n");
            return;
        }
    }
    int l = 0 , r = str.length()-1 , ans = 0;
    while(l < r){
           // cout << l << " " << r << endl;
        if(str[l] != str[r]){
            int tl = 100000 , tr = 100000;
            for(int i = l+1; i < r; i++){
                if(str[i] == str[l]) tr = i;
                if(str[i] == str[r] && tl == 100000) tl  = i;
            }
            if(abs(tl - l) >= abs(r - tr)){
                ans += r-tr;
                for(int i = tr; i < r; i++){
                    str[i] = str[i+1];
                }
                str[r] = str[l];
            }else{
                ans += tl-l;
                for(int i = tl; i > l; i--){
                    str[i] = str[i-1];
                }
                str[l] = str[r];
            }
        }
        l++;
        r--;
    }
    printf("%d\n" , ans);
}

int main(){
    int t;
    cin >> t;
    while(t--){
        initial();
        cin >> str;
        computing();
    }
    return 0;
}


 类似资料:

相关阅读

相关文章

相关问答