uva-10202-Pairsumonious Numbers

来源:互联网 发布:淘宝店铺推广工具 编辑:程序博客网 时间:2024/05/17 03:08

The analysis:

       This is not a so difficult problem. As we know, we know all the pairwise sums of N numbers, then the matter is to get the N numbers. Firstly, we let N[0..n] denots the N numbers,and Sum[0...] denots the sums.then we can sort the N*(N-1)/2 sums. so we known Sum[0]=N[0]+N[1] and Sum[1]=N[0]+N[2]. if we know N[0],Then we can Know N[1] and N[2].secondly, we can remove all the sums of N[1...] and N[2], then we can get The min of the sums now is the sum of N[0] and N[3], go on as this......thirdly, we must try the N[0], but we do not know it,s rang. however , if  we Know the sum of N[1],and N[2] , then we can Know N[0]. then the sum of N[1]and N[2] is in the Sum[2....].we can Try all of them.

 

 

The code:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int sum[50],num[10];
int used[50],n;

int cmp(const void *a,const void *b)
{
 return *(int *)a-*(int *)b;
}

int solve()
{
 int i,j,k,l,flag=0,su;
 memset(num,0,sizeof(num));
 
 for(i=2;i<n*(n-1)/2&&!flag;i++)
 {
  memset(used,0,sizeof(used));
  if((sum[0]+sum[1]-sum[i])%2==0)
  {
   num[0]=(sum[0]+sum[1]-sum[i])/2;
   num[1]=sum[0]-num[0];
   flag=1;
   for(j=2;j<n&&flag;j++)
   {
    for(k=j-1;k<n*(n-1)/2&&used[k];k++)
    {}
    num[j]=sum[k]-num[0];
    used[k]=1;
    for(l=1;l<j&&flag;l++)
    {
     su=num[j]+num[l];
     for(++k;k<n*(n-1)/2&&(sum[k]!=su||used[k]);++k)
     {}
     if(k!=n*(n-1)/2)
      used[k]=1;
     else
      flag=0;
    }
   }
  }
 }
 return flag;
}

int main()
{
 int i;
 while(scanf("%d",&n)!=EOF)
 {
  for(i=0;i<n*(n-1)/2;i++)
  {
   scanf("%d",&sum[i]);
  }
  qsort(sum,n*(n-1)/2,sizeof(sum[0]),cmp);
  if(solve())
  {
   for(i=0;i<n;i++)
   {
    if(i==0)
     printf("%d",num[0]);
    else
     printf(" %d",num[i]);
   }
   printf("/n");
  }
  else
   printf("Impossible/n");
  
 }
 return 0;

}