3种数,分成两个目标,先排列较少的那个目标,并且输出了交换步骤,然后统计另外一个目标,得出结果。
程序代码:
#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(1000*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++)
{
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; 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]) total++;
}
} // how many target2 were not be the right locality!
printf("%d\n", total);
free(store);
}
void main()
{
sort_function();
}
我自己都跪了,估计这种代码没人愿意看吧。
[
本帖最后由 demonleer 于 2012-7-24 10:16 编辑 ]