# 通过交换，使序列a的和与序列b的和之间的差的绝对值最小（栈和队列）

a={1,2,7,8,9}；

b={3,4,5,6,10};

1 2 3 4 5

6 7 8 9 10

1 2 7 8 9

3 4 5 6 10

``````1 2 3 4 5

6 7 8 9 10 ``````

``````1 2 7 8 9

3 4 5 6 10 ``````

``````#include<stdio.h>
#include<math.h>
#define MaxSize 101
int main()
{
int suma = 0,sumb = 0;
int counta = 0,countb = 0;
int a[MaxSize],b[MaxSize];
int temp;
int pa,pb;
int i,j;
while(counta<5)
{
scanf("%d",&a[counta]);
suma+=a[counta];
counta++;
}
while(countb<5)
{
scanf("%d",&b[countb]);
sumb+=b[countb];
countb++;
}
if(suma==sumb)
{
for(i = 0;i<counta;i++)
printf("%d ",a[i]);
printf("\n");
for(j = 0;j<countb;j++)
printf("%d ",b[j]);
return 0;
}
for(i = 0;i<counta;i++)
{
for(j = 0;j<countb;j++)
{
pa = suma-a[i]+b[j];
pb = sumb-b[j]+a[i];
if(fabs(pa-pb)<fabs(suma-sumb))
{
temp = a[i];
a[i] = b[j];
b[j] = temp;
suma = pa;
sumb = pb;
}
}
}
for(j = 0;j<countb;j++)
printf("%d ",b[j]);
printf("\n\n");
for(i = 0;i<counta-1;i++)
for(j = i+1;j<counta;j++)
{
if(a[i]>a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
for(i = 0;i<counta;i++)
printf("%d ",a[i]);
}
``````

``````#include<stdio.h>
#include<math.h>
#define MaxSize 101
int main()
{
int suma = 0,sumb = 0;
int counta = 0,countb = 0;
int a[MaxSize],b[MaxSize];
int temp;
int pa,pb;
int i,j;
while(counta<5)
{
scanf("%d",&a[counta]);
suma+=a[counta];
counta++;
}
while(countb<5)
{
scanf("%d",&b[countb]);
sumb+=b[countb];
countb++;
}
if(suma==sumb)
{
for(i = 0;i<counta;i++)
printf("%d ",a[i]);
printf("\n");
for(j = 0;j<countb;j++)
printf("%d ",b[j]);
return 0;
}
for(i = 0;i<counta;i++)
{
for(j = 0;j<countb;j++)
{
pa = suma-a[i]+b[j];
pb = sumb-b[j]+a[i];
if(fabs(pa-pb)<fabs(suma-sumb))
{
temp = a[i];
a[i] = b[j];
b[j] = temp;
suma = pa;
sumb = pb;
}
}
}
for(j = 0;j<countb;j++)
printf("%d ",b[j]);
printf("\n\n");
for(i = 0;i<counta-1;i++)
for(j = i+1;j<counta;j++)
{
if(a[i]>a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
for(i = 0;i<counta;i++)
printf("%d ",a[i]);
}
``````