uva 10716 - Minimum Swap to form Palindrome

转自: http://blog.csdn.net/chenguolinblog/article/details/7908609

贪心法,从两端开始找,如果不相等,试着找最近相等的字符。

#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>
#include <climits>
using namespace std;
#define MAXN 110

int t , ans;
int  num[26];
char ch[MAXN];

bool judge()
{
    int i , cnt;
    memset(num , 0 , sizeof(num));
    for(i = 0 ; i < strlen(ch) ; i++)
        num[ch[i]-'a']++;
    for(i = 0 , cnt = 0 ; i < 26 ; i++)
    {
        if(num[i]%2 && num[i]) cnt++;
    }
    if(cnt > 1) return false;
    return true;
}

void solve()
{
    if(!judge()){
        printf("Impossible\n");
        return;
    }

    int l_pos , r_pos, i, j;
    int left = 0, right = strlen(ch)-1;
    int res = 0;	

    while(left < right)
    {
	if(ch[left] != ch[right])
	{
		l_pos = r_pos = INT_MAX;
		for(i=left+1; i<right; i++)
		{
			if(ch[i] == ch[right])
			{
				l_pos = i-left;
				break;
			}
		}
	
		for(j=right-1; j>left; j--)
		{
			if(ch[j] == ch[left])
			{
				r_pos = right-j;
				break;
			}
		}

		if(l_pos < r_pos)
		{
			res += l_pos;
			for(i = left+l_pos; i>left; i--)
			{
				swap(ch[i], ch[i-1]);
				if(ch[i] == ch[i-1])
					res--;
			}
		}
		else
		{
			res += r_pos;
			for(j=right-r_pos; j<right; j++)
			{
				swap(ch[j], ch[j+1]);
				if(ch[j] == ch[j+1])
					res--;
			}
		}
	}
	if(ch[left] == ch[right])
	{
		left++;
		right--;
	}
    }
    printf("%d\n" , res);
}

int main(){

    scanf("%d%*c" , &t);
    while(t--){
        scanf("%s" , ch);
        solve();
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值