You know that the first problem of an online judge system should be the "A+B Problem", but TOJ not. What a terrible! So now it comes...
Given a series of numbers, your task is to find the largest number C in the sequence, which is the sum of two other numbers A and B in the sequence. Please note that A and B may have the same value, but cannot be the same number.
Input
The first line of each test case is an integer N (1 ≤ N ≤ 1000), which is the amount of the numbers, followed by a line of N numbers.
You can assume all the numbers in the sequence are positive and not more than 108.
The input will be terminated by a zero.
Output
Output one line for each test case, indicating the largest number. If there is no such number, output "-1".
Sample Input
5 8 3 4 3 6 0
Sample Output
6Author: Roba
题意概述:给定一列正整数,在其中找到满足C=A+B的最大的C,其中A、B、C都要在这一列数中,并且A、B可以大小相同但却不是同一个数。如 3 8 6 3 4 ,满足条件的 是:6=3+3。
解题思路:用标准库中的multiset,之所以用multiset是因为这一列数中可能会有相同的数,如:3 8 6 3 4中的两个3. 将输入的书 递减排序。每次用最大的值减去其他值,然 后检查所得的书是否存在multiset中。如果在,则立刻终止循环;如果不在,则将multiset中最大的值弹出,继续循环。
源代码:
#include<iostream>
#include<set>
using namespace std;
int main()
{
int N;
multiset<int,greater<int> >IntSet; //定义IntSet,按递减方式存放数据
while(cin>>N&&N>0)
{
int temp;
for(int i=0;i<N;++i) //完成输入操作
{
cin>>temp;
IntSet.insert(temp);
}
int max=0; //初始化max=0
multiset<int,greater<int> >::iterator pos1,pos2; //定义迭代器
for(pos1=IntSet.begin();pos1!=IntSet.end();pos1=IntSet.begin()) //使pos1指向最大的元素
{
for(pos2=IntSet.begin(),++pos2;pos2!=IntSet.end();++pos2) //使pos2指向pos1的下一个元素
{
//找到则立刻终止内层for循环
if(IntSet.find(*pos1 - *pos2)!=IntSet.end()&&IntSet.find(*pos1 - *pos2)!=pos2){max=*pos1;break;}
}
if(max!=0)break; //找到则立刻终止外层for循环
else IntSet.erase(IntSet.begin()); //找不到则删除头元素
}
IntSet.clear(); //清空IntSet,为下一次输入做准备
cout<<max<<endl;
}
return 0;
}