hdu 4334

题目: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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值