• HDU 2549 Sumset Hash+枚举


    经典的3-sum问题,写了个hash400ms过,但是写的n^3的暴力枚举特么居然0ms,让我非常不能容忍。

    Hash代码

    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <iostream>
    
    using namespace std;
    const int maxn = 1005;
    const int mod = 1000007;
    typedef long long LL;
    
    int head[mod], nxt[mod * 10], sz;
    LL A[mod * 10], B[mod * 10];
    LL val[mod * 10];
    int n, S[maxn];
    
    void clear() {
    	memset(head, -1, sizeof(head));
    	sz = 0;
    }
    
    LL mabs(LL x) {
    	return x < 0 ? -x : x;
    }
    
    int get_hash(LL x) {
    	return mabs(x) % mod;
    }
    
    void insert(LL x, LL a, LL b) {
    	int pos = get_hash(x);
    	A[sz] = a; B[sz] = b; nxt[sz] = head[pos];
    	val[sz] = x; head[pos] = sz++;
    }
    
    bool check(LL x, LL a, LL b) {
    	int pos = get_hash(x);
    	for (int i = head[pos]; ~i; i = nxt[i]) {
    		if (val[i] == x && A[i] != a && A[i] != b &&
    			B[i] != a && B[i] != b) {
    			return true;
    		}
    	}
    	return false;
    }
    
    int main() {
    	while (scanf("%d", &n), n) {
    		clear();
    		for (int i = 0; i < n; i++) {
    			scanf("%d", &S[i]);
    		}
    		for (int i = 0; i < n; i++) {
    			for (int j = 0; j < n; j++) if(S[i] != S[j]) {
    				insert(S[i] + S[j], S[i], S[j]);
    			}
    		}
    
    		LL ans = -1e17; bool ok = false;
    		for (int i = 0; i < n; i++) {
    			for (int j = 0; j < n; j++) if (S[i] != S[j]) {
    				if (check(S[i] - S[j], S[i], S[j])) {
    					ans = max(ans,(LL)S[i]); ok = true;
    				}
    			}
    		}
    
    		if (ok) cout << ans << endl;
    		else cout << "no solution" << endl;
    	}
    	return 0;
    }
    

      

  • 相关阅读:
    python2.7升python3.2
    SQL-基础学习使用的数据库资料
    SQL-基础学习2--ORDER BY ,DESC,WHERE, BETWEEN,AND ,OR ,IN ,NOT
    SQL-基础学习1--SELECT,LIMIT,DISTINCT,注释
    Python之Django-part 1
    python--文本处理1
    EXTJS4.2——8.Form+gride+linq进行前后端传输
    LINQ的实例
    高级委托使用
    C# 委托
  • 原文地址:https://www.cnblogs.com/rolight/p/3941636.html
Copyright © 2020-2023  润新知