基本能实现最优就要想了
程序代码:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
bool Check(char* p)
{
char* pHead = p;
char* pTail = p+strlen(p) - 1;
while(*(pHead++) == *(pTail--))
{
if(pHead == pTail || (pHead + 1) == pTail)
{
return true;
}
}
return false;
}
bool CheckChange(char* p)
{
int a[100][2] = {0};
char* pTmp = p;
char c = '0';
int n = 0;
while(*pTmp)
{
for(int i = 0; i < 100; i++)
{
if(a[i][0] == 0)
{
a[i][0] = *pTmp;
a[i][1] = 1;
break;
}else if(a[i][0] == *pTmp)
{
a[i][1]++;
break;
}
}
pTmp++;
}
for(int i = 0; i < 100; i++)
{
if(a[i][0] == 0)
{
break;
}
if(a[i][1]%2 != 0)
{
n++;
}
}
if(n >= 2)
{
return true;
}
else
{
return false;
}
}
int main()
{
char* pIn = (char*)malloc(9000);
memset(pIn, '\0', sizeof(pIn));
scanf("%s", pIn);
int n = 0;
char* p1 = pIn+strlen(pIn)-1;
char* p2 = pIn+strlen(pIn)-2;
char c = '0';
int t = 0;
if(Check(pIn))
{
printf("%d\n", n);
return 0;
}
else if(CheckChange(pIn))
{
printf("Impossible\n");
return 0;
}
while(1)
{
n++;
c = *p1;
*p1 = *p2;
*p2 = c;
if(Check(pIn))
{
printf("%d\n", n);
break;
}
if(p2 == (pIn+t))
{
p1 = pIn+strlen(pIn)-(1+t);
p2 = pIn+strlen(pIn)-(2+t);
}
else
{
p1--;
p2--;
}
if(*(pIn+t) == *(pIn+strlen(pIn)-(1+t)))
{
t++;
p1 = pIn+strlen(pIn)-(1+t);
p2 = pIn+strlen(pIn)-(2+t);
}
}
printf("转换后:%s\n", pIn);
free(pIn);
return 0;
}
[此贴子已经被作者于2017-3-23 00:58编辑过]