|
发表于 2009-11-5 01:02:30
|
显示全部楼层
IP:江苏扬州
#include<stdio.h>
#define MAX 100
int index;
int sum(int *p)
{
int i,sum=0;
for(i=0;i<MAX;i++)
{
sum+=p[i];
}
return sum;
}
void print(int *p)
{
int i;
printf("{");
for(i=0;p[i]!=0;i++)
{if(p[i]!=0&&p[i+1]!=0)
printf("%d,",p[i]);
else printf("%d}",p[i]);
}
}
main()
{
int a[MAX];
int a1[MAX],a2[MAX];
int p,i=0,j,temp,min1,min2,sum1=0,sum2=0;
for(j=0;j<MAX;j++)
{a[j]=0;a2[j]=0;a1[j]=0;
}
printf("input the data:");
scanf("%d",&p);
i=0;
while(p!=0)
{
a[i]=p;
i++;
printf("input data 0 to end:");
scanf("%d",&p);
}
for(i=0;a[i]!=0;i++)
{a2[i]=a[i];}
min1=min2=sum(a);
do
{
for(i=0;a2[i]!=0;i++)
{ sum1=sum(a1);sum2=sum(a2);
temp=sum1-sum2+2*a2[i]>0?sum1-sum2+2*a2[i]:sum2-sum1-2*a2[i];
if(min1>temp)
{min1=temp;index=i;}
}
if(min1<min2){
for(i=0;i<MAX;i++)
{if(a1[i]==0){
a1[i]=a2[index];
break;}}
for(j=index;a2[j]!=0;j++)
{
a2[j]=a2[j+1];
}
min2=min1;}
else
break;
} while(1);
print(a);
printf("\n");
print(a1);
printf("\t\t");
print(a2);
printf("\n");
getch();
}
示例:input the data:45
input data 0 to end:12
input data 0 to end:41
input data 0 to end:89
input data 0 to end:0
{45,12,41,89}
{89} {45,12,41}
input the data:10
input data 0 to end:8
input data 0 to end:7
input data 0 to end:5
input data 0 to end:4
input data 0 to end:3
input data 0 to end:2
input data 0 to end:0
{10,8,7,5,4,3,2}
{10,8,2} {7,5,4,3} |
|