zoukankan      html  css  js  c++  java
  • HDU 4334 Trouble(哈希|线性查找)

    给定五个集合。问是否能从五个集合各取一个元素,使得元素之和为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;
    }

    
    

  • 相关阅读:
    Redis使用手册
    log4j.properties 输出指定类日志
    Maven中Jar包冲突,不让某个Jar包打入到工程中
    Cannot refer to the non-final local variable user defined in an enclosing scope
    PANIC: Missing emulator engine program for ‘x86’ CPU.
    Android studio 不能创建Activity等文件
    jenkins打maven包,出现Module Builds里面部分模块没有启动问题
    CentOS7 SFTP服务安装和使用
    记一次阿里云服务器被挖矿程序植入处理(简单记录下)
    利用阿里云高可用虚拟ip+keepalived+mha实现两台mysql的高可用
  • 原文地址:https://www.cnblogs.com/yutingliuyl/p/6800923.html
Copyright © 2011-2022 走看看