hdu 4334

来源:互联网 发布:查看系统版本 linux 编辑:程序博客网 时间:2024/06/08 17:24

题目:http://acm.hdu.edu.cn/showproblem.php?pid=4334

题意:

题意:

给定五个集合,从五个集合中分别取出5个数,如果存在满足a1 + a2 + a3 + a4 +a5 == 0  输出yes,否则no; 集合的大小小于200 ai的取值为 [-10^15, 1 0^15]


解法:

If we have two sorted lists of integers A and B, we can easily find in linear time by keeping two pointers if there are a in A and b in B such that a+b=c (c is given).
Now, for this problem, we create a sorted list of all sums for S[0] and S[1] (call it M[0]), and a sorted list of all sums for S[2] and S[3] (call it M[1]). We can do this in O(n^2 log n).
Then, for each member c of S[4], we find if there's a in M[0] and b in M[1] such that a+b+c=0 using the method described in paragraph one. Sinc each search takes O(n^2) time (because the size of lists are O(n^2)), and we have O(n) members in S[4], total time complexity of this algorithm will be O(n^3).

代码:

#include <iostream>#include <cstring>#include <algorithm>using namespace std;typedef long long int64;const int N = 200;int n, t;int64 S[5][N];int64 M[2][N*N];inline int64 sum(int i, int j, int k) {return M[0][j] + M[1][k-1] + S[4][i];}int main() {for(cin >> t; t--; ) {cin >> n;int n2 = n * n;for(int i = 0; i < 5; i ++)for(int j = 0; j < n; j ++)cin >> S[i][j];for(int i = 0; i < 2; i ++) {for(int j = 0; j < n; j ++)for(int k = 0; k < n; k ++)M[i][j * n + k] = S[i * 2][j] + S[i * 2 + 1][k];sort(M[i], M[i] + n2);}bool result = false;for(int i = 0; i < n && !result; i ++) {int k = n2 - 1;for(int j = 0; j < n2 && !result; j ++) {while(k > 0 && sum(i, j, k-1) >= 0) {k --;}if(sum(i, j, k) == 0) result = true;}}if( result ) {//cerr << n << " Yes" << endl;cout << "Yes" << endl;} else {//cerr << n << " No" << endl;cout << "No" << endl;}}return 0;}


原创粉丝点击