下面的代码可以输出完整的交换步骤:
又丑又长啊,fuck!
程序代码:
#include<stdio.h>
#include<stdlib.h>
int number[3];
int position[3];
#define STATE(x,y,z) x>y?(x>z?1:3):(y>z?2:3)
#define SWAP(x,y) do{x^=y;y^=x;x^=y;}while(0)
void printf_store(int *p , int n)
{
int i = 0;
while (i<n)
{
printf("%d ",*(p+i++));
}
printf("\n");
}
int belongto(int i)
{
if (i<position[1])return 1;
if (i>=position[2])return 3;
else return 2;
}
void sort_function()
{
int N, *store, target1, target2, chg, state;
int i = 0, j = 0, t = 0, m = 0, flag = 0, total = 0;
if (NULL==(store=(int *)malloc(1001*sizeof(int)))) return;
for (scanf("%d",&N); i<N; scanf("%d",store+i++));
for (i=0; i<N; number[*(store+i++)-1]++); // learned this skill from BEYONDYF!!
state = STATE(number[0],number[1],number[2]);
position[1] = number[0], position[2] = position[1] + number[1];
target1 = state%3 + 1;
target2 = target1%3 + 1;
if (number[target1-1]>number[target2-1]) SWAP(target1,target2);
for(i=0; number[target1-1]!=0&&i<N; i++)
{
if(*(store+i)==target1)
{
if (i>=position[target1-1] && i<position[target1-1]+number[target1-1])
{
t++;
printf("no change!\n");
printf_store(store,N);
if (t==number[target1-1]) break;
}
else
{
while (target1==*(store+position[target1-1]+j)) j++;
chg = belongto(i);
for (m=j,flag=0; m<number[target1-1]; m++)
{
if (chg==*(store+position[target1-1]+m))
{
flag = 1;
break;
}
}
flag<1?(m=j):1;
*(store+i) = *(store+position[target1-1]+m);
*(store+position[target1-1]+m) = target1;
total++;
printf("be changed!\n");
printf_store(store,N);
if (j==number[target1-1]-1) break;
}
}
} //target1 has been stored!
for (i=0,t=0,j=0; i<N; i++)
{
if (i == position[target1-1]) i += number[target1-1];
if (i>=N) break;
if(*(store+i)==target2)
{
if (i>=position[target2-1] && i<position[target2-1]+number[target2-1])
{
t++;
printf("no change!\n");
printf_store(store,N);
if (t==number[target2-1]) break;
}
else
{
while (target2==*(store+position[target2-1]+j)) j++;
chg = belongto(i);
for (m=j,flag=0; m<number[target2-1]; m++)
{
if (chg==*(store+position[target2-1]+m))
{
flag = 1;
break;
}
}
flag<1?(m=j):1;
*(store+i) = *(store+position[target2-1]+m);
*(store+position[target2-1]+m) = target2;
total++;
printf("be changed!\n");
printf_store(store,N);
if (j==number[target2-1]-1) break;
}
}
}
printf("the result is %d\n", total);
free(store);
}
void main()
{
sort_function();
}