[51NOD1090] 3个数和为0(水题,二分)

题目链接:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1090

找到所有数的和,然后再原数组里二分找符合条件的第三个数。

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 const int maxn = 1010;
 5 const int maxm = maxn * maxn;
 6 typedef struct R {
 7   int x, y, z;
 8   R(){}
 9   R(int x, int y, int z) : x(x), y(y), z(z) {}
10   bool operator == (R t) {
11     return x == t.x && y == t.y && z == t.z;
12   }
13 }R;
14 typedef struct S {
15   int i, j;
16   int s;
17 }S;
18 
19 vector<R> ret;
20 int n, m;
21 int a[maxn];
22 S s[maxm];
23 
24 bool cmp(R a, R b) {
25   if(a.x == b.x) {
26     if(a.y == b.y) return a.z < b.z;
27     return a.y < b.y;
28   }
29   return a.x < b.x;
30 }
31 
32 int main() {
33   // freopen("in", "r", stdin);
34   while(~scanf("%d", &n)) {
35     m = 0; ret.clear();
36     for(int i = 0; i < n; i++) {
37       scanf("%d", &a[i]);
38     }
39     sort(a, a+n);
40     for(int i = 0; i < n; i++) {
41       for(int j = i+1; j < n; j++) {
42         s[m].i = i; s[m].j = j; s[m].s = a[i] + a[j];
43         m++;
44       }
45     }
46     for(int i = 0; i < m; i++) {
47       int x = -s[i].s;
48       int id = lower_bound(a, a+n, x) - a;
49       if(a[id] == x && id != s[i].i && id != s[i].j) {
50         int x = a[s[i].i], y = a[s[i].j], z = a[id];
51         if(x > y) swap(x, y);
52         if(x > z) swap(x, z);
53         if(y > z) swap(y, z);
54         ret.push_back(R(x,y,z));
55       }
56     }
57     if(ret.size() == 0) {
58       puts("No Solution");
59       continue;
60     }
61     sort(ret.begin(), ret.end(), cmp);
62     ret.erase(unique(ret.begin(), ret.end()), ret.end());
63     for(int i = 0; i < ret.size(); i++) {
64       printf("%d %d %d
", ret[i].x, ret[i].y, ret[i].z);
65     }
66   }
67   return 0;
68 }
原文地址:https://www.cnblogs.com/kirai/p/5993530.html