題意:
在每組輸入數據給出的最多1萬個整數裏面找出三個數A, B, C滿足 C = A + B。
如果能夠找出,輸出滿足次條件的最大的C
否則輸出-1。
解答:
思路很巧妙,特寫題解
暴力n^3必然超時 (3<=n<=10000)
先從小到大排序,然後枚舉C(這裏用a[i]表示),兩個指針j,k分別在開始和結束位置。
如果a[j]+a[k]<a[i],則表示A + B<C,和需要更大一點,所以j++,往後移動;
同理,如果a[j]+a[k]>a[i],則表示A + B>C,和需要更小一點,所以k--,往前移動;
否則,找到C = A + B,並繼續尋找最大的C
時間複雜度n^2
參考:felix021的題解
/*
* Author: NICK WONG
* Created Time: 2/22/2016 00:21:31
* File Name: woj1074.cpp
*/
#include<iostream>
#include<sstream>
#include<fstream>
#include<vector>
#include<list>
#include<deque>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cctype>
#include<cmath>
#include<ctime>
#include<iomanip>
using namespace std;
#define out(x) cout<<#x<<": "<<x<<endl
const double eps(1e-8);
const int maxn=10100;
const long long maxint=-1u>>1;
const long long maxlong=maxint*maxint;
typedef long long lint;
int n,a[maxn];
void init()
{
cin>>n;
for (int i=1; i<=n; i++)
cin>>a[i];
}
void work()
{
int ans=-1;
sort(a+1,a+n+1);
bool flag=true;
for (int i=n; i>=1 && flag; i--)
for (int j=1,k=n; j<k; )
{
if (a[j]+a[k]==a[i])
{
ans=max(ans,a[i]);
flag=false;
break;
} else
if (a[j]+a[k]<a[i])
{
j++;
} else
{
k--;
}
}
cout<<ans<<endl;
}
int main()
{
int t;
cin>>t;
while(t--)
{
init();
work();
}
return 0;
}
Problem 1074 - ABC
Time Limit: 1000MS Memory Limit: 65536KB Difficulty: 3
Total Submit: 1530 Accepted: 613 Special Judge: No
Description
Given an array consists of n positive integers,your task is to find the largest C which makes C=A+B. A,B,C are all in the given array.
Input
Standard input will contain multiple test cases. The first line of the input is an integer T (1 <= T <= 20) which is the number of test cases.
For each test case,there is an integer n (3<=n<=10000) in the first line,indicating the number of elements in the array.The next line contains
n positive integers.You can assume all the integers will be less then 10^9.
Output
For each test case,if you can find the largest integer C=A+B, output C. Notice, A and B should be different elements in the array.If there isn't
such integer C,output -1 instead.
Sample Input
3
10
1 1 1 4 5 5 6 6 10 9
3
5 5 10
3
1 3 6
Sample Output
10
10
-1
Hint
Optimize your algorithm,make it as fast as possible!
Source
cowork@whu