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

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

5
2 
3 
5 
7 
12
5
2 
16 
64 
256 
1024
0

Output for Sample Input

12
no 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;		
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值