51nod1090 The sum of three numbers is 0 (two points, vector)

Given an unordered array of length N, the elements in the array are integers, positive and negative, including 0, and are not equal to each other. Find all combinations of 3 numbers whose sum = 0. If there is no such combination, output No Solution. If there are more than one, sort by the smallest of the three numbers from small to large, and if the smallest numbers are equal, sort by the second smallest number.
Input
line 1, 1 number N, N is the length of the array (0 <= N <= 1000) 
Line 2 - N + 1: Aii (-10^9 <= Aii <= 10^9)
Output
if there is no A combination that meets the conditions will output No Solution. 
If there are more than one, sort by the smallest of the three numbers from small to large. If the smallest numbers are equal, continue to sort by the second smallest number. There are 3 numbers per line, separated by spaces, and the 3 numbers are arranged in ascending order.
Sample Input
7
-3
-2
-1
0
1
2
3
Sample Output
-3 0 3
-3 1 2
-2 -1 3
-2 0 2

-1 0 1

Since I used the vector, I can not open the array, and never open the array again >v<

#include<bits/stdc++.h>
using namespace std;
struct nod{ //Define a structure
	int a;
	int b;
	int c;
};
int cmp(nod a,nod b){
    if(a.a ==b.a){
    	if(a.b==b.b){
    		return ac<bc; //sort the three numbers of the structure in ascending order
		}return a.b<b.b;
	}return a.a<b.a;
}
vector<int> v;
vector<nod> s;
int main(){
    int i,j,n; //What is required is a+b+c=0; Change to ask for existence -a =b+c
    int k,sum
    nod g;
    while(cin>>n){
    for(i=0;i<n;i++){
     cin>>k;
	 v.push_back(k); //All data is stored in the array v
	}
	sort(v.begin(),v.end()); //Data sorting (ascending)
	for(i=0;i<n;i++){
		sum=-v[i]; //Take the element of the array, it turns out to be a, here we need -a;
		int l=i+1,r=n-1; //binary search
		while(l<r){
			if(v[l]+v[r]==sum){
			g.a=v[i]; g.b=v[l]; g.c=v[r];   //假如b+c==-a;
			s.push_back(g); //Store this group of b, c, a, into the s array (with the help of an intermediate structure variable g)
			}
			if(v[l]+v[r]<sum) //If b+c<-a; means the number on the left needs to be bigger
			l++; //The left coordinate is shifted to the right (l++), such as -3 + 2 < 0 ,, the right digit of -3 is a number larger than -3, and the solution can be found only by shifting to the right
			else
			r--; //Same, b+c>-a; indicates that the number on the right needs to be smaller,
		} //The right coordinate is shifted to the left (r--), such as -2 + 3 > 0 , the left digit of 3 is a number smaller than 3, and the solution can be found by shifting to the left
	}
	if(!s.empty()){ //Judging, s is not empty and then output
		sort(s.begin(),s.end(),cmp);
		for(i=0;i<s.size();i++){
			cout<<s[i].a<<" "<<s[i].b<<" "<<s[i].c<<endl;
		}
	}
	else
	cout<<"No Solution"<<endl;     
	}
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324509968&siteId=291194637