标签:
第1行,1个数N,N为数组的长度(4 <= N <= 1000) 第2 - N + 1行:A[i](-10^9 <= A[i] <= 10^9)
如果可以选出4个数,使得他们的和为0,则输出"Yes",否则输出"No"。
5 -1 1 -5 2 4
Yes
思路:二分+折半枚举;注意不能用任何一个重复的点。
1 #include<stdio.h> 2 #include<algorithm> 3 #include<iostream> 4 #include<string.h> 5 #include<queue> 6 #include<math.h> 7 #include<set> 8 #include<vector> 9 #include<string.h> 10 using namespace std; 11 typedef long long LL; 12 typedef struct node 13 { 14 int x; 15 int y; 16 LL sum; 17 } ss; 18 ss ans[1000005]; 19 LL ak[1005]; 20 bool check(int cn,int x); 21 bool cmp(node p, node q) 22 { 23 return p.sum<q.sum; 24 } 25 int main(void) 26 { 27 int N; 28 scanf("%d",&N); 29 int i,j; 30 for(i = 0; i < N; i++) 31 { 32 scanf("%lld",&ak[i]); 33 } 34 int cn = 0; 35 for(i = 0; i < N ; i++) 36 { 37 for(j = i+1; j < N; j++) 38 { 39 ans[cn].x = i; 40 ans[cn].y = j; 41 ans[cn].sum = ak[i] + ak[j]; 42 cn++; 43 } 44 } 45 sort(ans,ans+cn,cmp); bool flag =false; 46 for(i = 0;i < cn ;i++) 47 { 48 flag = check(cn,i); 49 if(flag)break; 50 } 51 if(flag)printf("Yes\n"); 52 else printf("No\n"); 53 return 0; 54 } 55 bool check(int cn,int x) 56 { 57 int l = 0; 58 int r = cn -1; 59 int id = -1; 60 while(l <= r) 61 { int mid = (l+r)/2; 62 if(ans[mid].sum <= -ans[x].sum) 63 { 64 id = mid; 65 l = mid+1; 66 } 67 else r = mid-1; 68 } 69 int cp = -1; 70 l = 0; r = cn-1; 71 while(l <= r) 72 { 73 int mid = (l+r)/2; 74 if(ans[mid].sum >= -ans[x].sum) 75 { 76 cp = mid; 77 r = mid-1; 78 } 79 else l = mid+1; 80 } 81 if(cp !=-1&&id !=-1) 82 { 83 for(int i = cp ;i <= id;i++) 84 { 85 if(ans[i].x!=ans[x].x&&ans[i].y!=ans[x].x&&ans[x].y!=ans[i].x&&ans[x].y!=ans[i].y) 86 { 87 return true; 88 } 89 } 90 } 91 return false; 92 }
标签:
原文地址:http://www.cnblogs.com/zzuli2sjy/p/5840724.html