24h購物| | PChome| 登入
2009-09-22 20:16:41| 人氣1,010| 回應0 | 上一篇 | 下一篇

ACM 11057 11057 - Exact Sum

推薦 0 收藏 0 轉貼0 訂閱站台

作法 :

C的MAP有點麻煩

所以就用快速排序+二分搜尋囉

/********************************************************/

#include<stdio.h>
#include<stdlib.h>
int partition(int[], int, int);   
void quicksort(int[], int, int);
int num[10001]={0};
int index1(int n,int L,int L2)  
{  
 int lower=L2, mid, high=L-1;  
 int index=-1;  
    do   /*二分搜尋*/ 
    {  
      mid=(lower+high)/2;  
      if(num[mid]<n)     lower=mid+1;  
      else if(num[mid]>n)  high=mid-1;  
      else  index=mid;  
    }  
    while(index==-1&&lower<=high);  
  return index;  

int input()  
{  
  char cha;  
  int x=0;  
  while(cha=getchar())  
     if(cha!=' '&&cha!='\n') break;  
  x=cha-48;  
  while(cha=getchar())   
    {  
     if(cha==' '||cha=='\n') break;  
      x=x*10+cha-48;  
    }  
    return x;  
}
main()
{
 int n,m,k,a,b;
 while(scanf("%d",&n)==1)
    {
       for(a=0;a<n;a++)
         num[a]=input();
       quicksort(num,0,n-1);
       scanf("%d",&m);
       for(a=n;a>=0;a--)
         {
           int index=index1(m-num[a],n,a+1);
           if(index!=-1)
              {
                 printf("Peter should buy books whose prices are %d and %d.\n\n",num[a],m-num[a]);
                 break;
              }
         } 
    }
 return 0;
}
int partition(int num[],int left,int right)   
{  
  int a=left-1,b,s=num[right];  
  for(b=left;b<right;b++)  
   {  
     if(num[b]<s)  
       {  
         a++;  
         int temp;  
         temp=num[a];  
         num[a]=num[b];
         num[b]=temp;   
       }   
   }   
         int temp;  
         temp=num[a+1];
         num[a+1]=num[right];  
         num[right]=temp;
   return a+1;   
}   
void quicksort(int num[],int left,int right)  
{  
 int q;  
 if(left<right)   
   {  
     q=partition(num,left,right);  
     quicksort(num,left,q-1);  
     quicksort(num,q+1,right);   
   }   
}

台長: 來源不明
人氣(1,010) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 數位資訊(科技、網路、通訊、家電) | 個人分類: ACM |
此分類下一篇:ACM 11059 11059 - Maximum Product
此分類上一篇:ACM 10780 Q10780: Again Prime? No time.

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文