给定五个集合。问是否能从五个集合各取一个元素,使得元素之和为0.
这道题有两种做法,一种是哈希,然而之前没写过哈希.....比赛后从大神那copy了一份。
这里说还有一种。
对于这五个集合分为三组。1,2组求和为一组,3,4组求和分为一组,5为一组。
那么如今转化为了是否能从前两组中各取一个元素。使得这两个值和为第三组一个元素的相反数。
那么对于第一组我们升序排序。第二组我们降序排序。
对于第三组里的任一元素,假如第一组队首加第二组队首之和大于第三组的元素。那么第二组游标往后移一位,反之第一组移一位,
那么这个查找时间就为O(m),m为数组元素个数。
那么总的时间复杂度为O(n*n*n).
<pre class="cpp" name="code">#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<string>
#include<map>
#include<set>
#define eps 1e-6
#define LL long long
#define pii pair<int,int>
using namespace std;
//const int maxn = 100 + 5;
//const int INF = 0x3f3f3f3f;
LL s[6][205];
LL s12[200*202], s34[200*202];
int n;
bool check(LL t) {
int y12 = 0, y34 = n*n-1;
// cout << y12 << endl << y34 << endl;
while(y12<n*n && y34>=0) {
LL tmp = s12[y12] + s34[y34];
// cout << s12[y12] << endl << s34[y34] << endl;
// cout << tmp << endl;
if(tmp == t) return true;
else if(tmp < t) y12++;
else y34--;
}
return false;
}
int main() {
// freopen("input.txt", "r", stdin);
int t; cin >> t;
while(t--) {
cin >> n;
for(int i = 0; i < 5; i++) {
for(int j = 0; j < n; j++) scanf("%I64d", &s[i][j]);
}
int y1 = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
LL tmp = s[0][i]+s[1][j];
s12[y1++] = tmp;
}
}
int y2 = 0;
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
LL tmp = s[2][i]+s[3][j];
s34[y2++] = tmp;
}
}
// cout << y1 << y2 << endl;
sort(s12, s12+n*n);
sort(s34, s34+n*n);
int tag = 0;
for(int i = 0; i < n; i++) if(check(-s[4][i])) {
tag = 1; break;
}
// cout << check(4) << endl;
if(tag) puts("Yes");
else puts("No");
}
return 0;
}