Problem Description
There are n numbers
A1,A2....An
,your task is to check whether there exists there different positive integers i, j, k (
1≤i,j,k≤n
) such that
Ai−Aj=Ak
Input
There are multiple test cases, no more than 1000 cases.
First line of each case contains a single integer n. (3≤n≤100) .
Next line contains n integers A1,A2....An . (0≤Ai≤1000)
First line of each case contains a single integer n. (3≤n≤100) .
Next line contains n integers A1,A2....An . (0≤Ai≤1000)
Output
For each case output "YES" in a single line if you find such i, j, k, otherwise output "NO".
Sample Input
3 3 1 2 3 1 0 2 4 1 1 0 2
Sample Output
YES NO YES
题目大意:给出 n 个数,问能不能找到三个满足Ai - Aj = Ak。
乍一看没思路,一看数据范围100就呵呵了。给这些数从小到大排个序,Ai - Aj = Ak 也可以看成是找 Ai + Aj = Ak。Ak 一定是由比它小的 Ai 和 Aj 加起来得到的,从前往后枚举即可。枚举 Ai 和 Aj 再从数列里二分找 Ak,复杂度最坏 O(n^2logn)。
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int maxn = 100 + 5; int a[maxn]; int main() { int n; while(scanf("%d",&n) != EOF) { for(int i = 0;i < n; ++i) scanf("%d",&a[i]); sort(a,a + n); bool ok = false; for(int i = 0;i < n; ++i) { for(int j = i + 1;j < n; ++j) { int p = lower_bound(a + j + 1,a + n,a[i] + a[j]) - a; if(p < n && a[p] == a[i] + a[j]) { ok = true; break; } } if(ok) break; } printf("%s\n",ok ? "YES" : "NO"); } return 0; }