您的位置:首页 > 其它

uva10716 - - Evil Straw Warts Live

2016-03-05 13:32 351 查看
题意:

给你一个串,问你是否能改动它们的顺序使之成为回文,能改变的话,最小改动数呢

思路:

看到题目的第一思路是能不能通过记录相同字符的位置来做,想来想去还是枪毙了,参考了他人做法,思路清晰明了(T——T,感觉我老是把简单问题想得复杂化了,终究是没想到点上。)

贪心法,主要就是从两端开始确定,慢慢向中间缩进,若两端相同,则直接缩进,若不同,则双向搜索能替换左右使其相等的最近交换距离,直到成功找到

代码如下:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 105;
char str
, ans[30];
int main(){
int cas;
scanf("%d\n", &cas);
while (cas--) {
memset(ans, 0, sizeof(ans));
scanf("%s",str);
int n = strlen(str);
for (int i = 0; i < n; i++)
ans[str[i] - 'a']++;
int t = 0;
for (int i = 0; i < 30; i++)
if (ans[i] % 2 != 0)
t++;
if (t > 1){
printf("Impossible\n");
continue;
}
int cnt = 0, start, end;
for (start = 0, end = n - 1; start < end; start++, end--){
if (str[start] != str[end]) {
int l = start;
while (str[l] != str[end])
l++;
int r = end;
while (str[r] != str[start])
r--;
char ch;
if (l - start > end - r){
ch = str[r];
for (int j = r; j < end; j++){
str[j] = str[j + 1];
}
str[end] = ch;
cnt += end - r;
}
else {
ch = str[l];
for (int j = l; j > start; j--){
str[j] = str[j - 1];
}
str[start] = ch;
cnt += l - start;
}
}
}
printf("%d\n", cnt);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: