您的位置:首页 > 其它

UVa:10716 Evil Straw Warts Live

2014-01-17 13:40 447 查看
如果出现奇数次的字母个数大于1那说明不能形成回文。

然后按照回文字母一半在左一半在右的原则构造一个回文串,然后用原串依次交换每个字母最后得到回文串的交换次数就是答案。

因为越界RE了3次。。



#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
#define MAXN 105
#define MOD 1000000007
#define INF 2139062143
#define ll long long
using namespace std;
int cnt[MAXN];
string Makestr(string str)
{
    string aim;
    int num[MAXN]= {0};
    for(int i=0; i<26; ++i)
        num[i]=cnt[i]/2;
    for(int i=0; i<str.size(); ++i)
        if(num[str[i]-'a']>0)
        {
            aim=aim+str[i];
            num[str[i]-'a']--;
        }
    bool c=false;
    for(int i=0; i<26; ++i)
        if(cnt[i]%2)
        {
            aim=aim+(char)(i+'a');
            for(int i=aim.size()-2; i>=0; --i)
                aim=aim+aim[i];
            c=true;
            break;
        }
    if(!c)
    {
        for(int i=aim.size()-1; i>=0; --i)
            aim=aim+aim[i];
    }
    return aim;
}
int Search(int k,char c,string str)
{
    for(int i=k; i<str.size(); ++i)
        if(c==str[i])
            return i;
    return -1;
}
int Getstep(int ed,int st,string &str)
{
    int step=0;
    for(int i=st; i>ed; --i)
    {
        swap(str[i],str[i-1]);
        step++;
    }
    return step;
}
int solve(string st,string ed)
{
    int ans=0;
    for(int i=0; i<st.size();)
    {
        while(i<st.size()&&st[i]==ed[i]) ++i;
        if(i>=st.size()) break;
        int j=Search(i,ed[i],st);
        ans=ans+Getstep(i,j,st);
    }
    return ans;
}
int main()
{
    std::ios::sync_with_stdio(false);
    int T;
    cin>>T;
    while(T--)
    {
        string str;
        cin>>str;
        memset(cnt,0,sizeof(cnt));
        for(int i=0; i<str.size(); ++i)
            cnt[str[i]-'a']++;
        int n=0;
        for(int i=0; i<26; ++i)
            if(cnt[i]%2) n++;
        if(n>1)
        {
            cout<<"Impossible"<<endl;
            continue;
        }
        else if(str.size()==1)
        {
            cout<<0<<endl;
            continue;
        }
        string aim=Makestr(str);
        cout<<solve(str,aim)<<endl;
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: