51nod 1267 4个数和为0 - 二分+排序

分析:

将四个数字相加,分解成两个数相加,排序  找答案

注意:比较四个数是否相等  不能直接四个数!=  不要偷懒!

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstring>
 4 using namespace std;
 5 const int maxn = 1e6+5;
 6 
 7 struct node{
 8     int a;
 9     int b;
10     int sum;
11 }a[maxn];
12 int n, f[1005];
13 bool cmp(node a, node b)
14 {
15     return a.sum < b.sum;
16 }
17 bool check(int i, int j)
18 {    
19     if(a[i].a != a[j].b && a[i].a != a[i].b && a[i].b != a[j].b && a[i].b != a[j].b) return true;
20     else return false;
21 }
22 int main()
23 {
24     int k = 0;
25     cin >> n;
26     for(int i = 1; i <= n; i++){
27         cin >> f[i];
28          for(int j = 1; j < i; j++){
29             a[k].a = i;
30             a[k].b = j;
31             a[k++].sum = f[i]+f[j];
32         }
33     }
34     sort(a,a+k,cmp);
35     int x = 0, y = k - 1, flag = 0;
36     while(x < y){
37         if(a[x].sum + a[y].sum == 0){
38             if(check(x,y)){
39                 flag = 1;
40                 break;
41             }
42             else if(a[x].sum == a[x+1].sum) x++;
43             else if(a[y].sum == a[y-1].sum) y--;
44             else{ 
45                 x++, y--;
46             }
47         }
48         else if(a[x].sum + a[y].sum < 0) x++;
49         else y--;
50     }
51     if(flag) cout << "Yes" << endl;
52     else cout << "No" << endl;
53     return 0;
54 }

猜你喜欢

转载自www.cnblogs.com/JiaaaaKe/p/9468172.html