zoj1101-----------Gamblers----------快排与折半查找

来源:互联网 发布:局域网域名软件 编辑:程序博客网 时间:2024/05/20 20:30

A group of n gamblers decide to play a game:

At the beginning of the game each of them will cover up his wager on the table and the assitant must make sure that there are no two gamblers have put the same amount. If one has no money left, one may borrow some chips and his wager amount is considered to be negative. Assume that they all bet integer amount of money.

Then when they unveil their wagers, the winner is the one who's bet is exactly the same as the sum of that of 3 other gamblers. If there are more than one winners, the one with the largest bet wins.

For example, suppose Tom, Bill, John, Roger and Bush bet $2, $3, $5, $7 and $12, respectively. Then the winner is Bush with $12 since $2 + $3 + $7 = $12 and it's the largest bet.

Input

Wagers of several groups of gamblers, each consisting of a line containing an integer 1 <= n <= 1000 indicating the number of gamblers in a group, followed by their amount of wagers, one per line. Each wager is a distinct integer between -536870912 and +536870911 inclusive. The last line of input contains 0.

Output

For each group, a single line containing the wager amount of the winner, or a single line containing "no solution".

Sample Input

52 3 5 7 1252 16 64 256 10240

Output for Sample Input

12no solution

 

先将输入的赌注存入数组,然后对其进行升序排列  用到了函数sort(),如下:

 

然后二分查找(折半查找),用到了现成的binary_search(int *a, int n, int key)函数:

  C/C++版本:

  int binary_search( int *a, int n, int key )

  {

  int mid, front=0, back=n-1;

  while (front<=back)

  {

  mid = (front+back)/2;

  if (a[mid]==key)

  return mid;

  if (a[mid]<key)

  front = mid+1;

  else back = mid-1;

  }

  return -1;

  }

 

头文件包含了#include <algorithm>以后可以直接使用这两个函数!!尼玛啊让我自己写了半天

 

代码如下:

#include <iostream>#include <algorithm> using namespace std;int main(){int n,w,m,i,j,k,l,sum;int low,high,mid;while(cin>>n&&n!=0){int a[n];for(i=0;i<n;i++)cin>>a[i];      sort(a,a+n);                     //将序列排序为递增有序 bool flag=1;for(i=n-1;i>=0&&flag;i--)  //从后向前查找符合题意的数 for(j=0;j<n&&flag;j++)for(k=0;k<n&&flag;k++){if(i!=j&&j!=k&&k!=i){int value=a[i]-a[j]-a[k];if(value!=a[i]&&value!=a[j]&&value!=a[k]&&binary_search(a,a+n,value)){flag=0;cout<<a[i]<<endl;}}}if(flag==1)cout<<"no solution"<<endl;}return 0;}