uva 1152(4 values whose sum is zero)
2015-10-05 10:35
417 查看
题目大意:
给定4个元素的集合,要求从每个元素中选出一个数字,使得4个元素之和为0;
题目分析:
4重循环暴力枚举会超时的(n^4), 那么应该怎么做呢,枚举前3个集合,在第四个集合中直接查找值,(如果将第4个集合排序,通过二分,查找的时间复杂度为(logn))总时间复杂度降到的(n^3*logn),很不错的优化,同理,如果我们将集合A与集合B中的值全部计算出来,保存到一个有序的数组中(时间复杂度(n^2*logn), 通过枚举剩下两个集合,判断这个数组当中有没有符合条件的数,或者有几个。 总的时间复杂度依旧为(n^2 *logn + n^2*logn);
给定4个元素的集合,要求从每个元素中选出一个数字,使得4个元素之和为0;
题目分析:
4重循环暴力枚举会超时的(n^4), 那么应该怎么做呢,枚举前3个集合,在第四个集合中直接查找值,(如果将第4个集合排序,通过二分,查找的时间复杂度为(logn))总时间复杂度降到的(n^3*logn),很不错的优化,同理,如果我们将集合A与集合B中的值全部计算出来,保存到一个有序的数组中(时间复杂度(n^2*logn), 通过枚举剩下两个集合,判断这个数组当中有没有符合条件的数,或者有几个。 总的时间复杂度依旧为(n^2 *logn + n^2*logn);
#include <iostream> #include <cstdio> #include <algorithm> using namespace std; const int maxn = 4010; int A[maxn], B[maxn], C[maxn], D[maxn], sum[maxn*maxn]; int main() { int T, n; scanf("%d", &T); while(T--){ scanf("%d", &n); for(int i = 0; i < n; ++i) scanf("%d%d%d%d", &A[i], &B[i], &C[i], &D[i]); int cnt = 0; for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j) sum[cnt++] = A[i]+B[j]; sort(sum, sum+cnt); long long o = 0; for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j) { o += upper_bound(sum, sum+cnt, -C[i]-D[j])-lower_bound(sum, sum+cnt, -C[i]-D[j]); } printf("%lld\n", o); if(T) printf("\n"); } }
相关文章推荐
- Quick_Power快速幂
- 报错:setValue:forUndefinedKey:]: this class is not key value coding
- hdu5496 Beauty of Sequence
- 【POJ2524】Ubiquitous Religions
- UVALive 6258 Non-boring sequences 分治
- codeforces 245H H. Queries for Number of Palindromes(区间dp)
- Android call requires API level 12 的解决方案
- UI12_UItabBarViewController
- UI_UITableView的HeaderView
- UI12_UIView动画
- UI:数据库练习、滤镜效果
- Leetcode NO.232 Implement Queue using Stacks
- UI11_UITableViewController
- UI11_TableView编辑
- 【白痴弟弟和你加强应用层】阅读 Develop API Guides 思考(一个)
- UI11_数据处理
- UI_UITableViewCell自适应高度(图片,字体)
- UI10_省市区分区跳转版
- SpriteBuilder中时间线播放音效的弊端
- SpriteBuilder中时间线播放音效的弊端