HDU 4334 Trouble(哈希|线性查找)
2015-08-01 19:32
429 查看
给定五个集合,问能否从五个集合各取一个元素,使得元素之和为0.
这道题有两种做法,一种是哈希,然而之前没写过哈希.....比赛后从大神那copy了一份。
这里说另一种,
对于这五个集合分为三组,1,2组求和为一组,3,4组求和分为一组,5为一组。
那么现在转化为了能否从前两组中各取一个元素,使得这两个值和为第三组一个元素的相反数。
那么对于第一组我们升序排序,第二组我们降序排序。
对于第三组里的任一元素,假如第一组队首加第二组队首之和大于第三组的元素,那么第二组游标往后移一位,反之第一组移一位,
那么这个查找时间就为O(m),m为数组元素个数,
那么总的时间复杂度为O(n*n*n).
这道题有两种做法,一种是哈希,然而之前没写过哈希.....比赛后从大神那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; }
相关文章推荐
- 插入排序C语言实现
- 问题解决——关闭子进程
- sql-update语句多表级联更新
- codeforces 558B Amr and The Large Array
- EJB学习(六)——Entity Bean 和 Hibernate的比较
- HDOJ1059(多重部分和问题)
- (转)进程的状态
- (一〇一)集成静态库RHAddressBook实现OC访问通讯录
- (一〇一)集成静态库RHAddressBook实现OC访问通讯录
- 岁月的剪影【八月Sha La La】
- SDUT2015暑假集训14级周赛1 B - 皇马(组合数)
- 树状数组
- iOS8开发-- 如何在Xcode6中添加pch全局引用文件
- 多线程使用信号量sem_init,sem_wait,sem_post
- Http协议的请求头信息与返回头信息详解
- mysql之DML(SELECT DELETE INSERT UPDATE)
- 控制echo显示字体的颜色和效果
- 小鑫与地板砖 SDUT2849
- Several ports (8005, 8080, 8009) required by Tomcat v7.0 Server at localhost are already in use. The
- android自定义view--指南针背景