zoukankan      html  css  js  c++  java
  • POJ 2785 4 Values whose Sum is 0(哈希表)

    【题目链接】 http://poj.org/problem?id=2785

    【题目大意】

      给出四个数组,从每个数组中选出一个数,使得四个数相加为0,求方案数

    【题解】

      将a+b存入哈希表,反查-c-d

    【代码】

    #include <cstdio>
    #include <algorithm>
    #include <cstring>
    using namespace std;
    const int N=4500,mod=1<<22;
    int n,a[N],b[N],c[N],d[N],head[mod],cnt;
    struct data{int x,nxt,s;}g[mod];
    long long ans;
    inline int hash(int x){return (x+mod)&(mod-1);}
    void insert(int x){
        int key=hash(x);
        for(int i=head[key];i!=-1;i=g[i].nxt){
            if(g[i].x==x){g[i].s++;return;}
        }g[cnt].s=1; g[cnt].x=x;
        g[cnt].nxt=head[key]; head[key]=cnt++;
    }
    int search(int x){
        int key=hash(x);
        for(int i=head[key];i!=-1;i=g[i].nxt){
            if(g[i].x==x)return g[i].s;
        }return 0;
    }
    void init(){cnt=0;memset(head,-1,sizeof(head));ans=0;}
    int main(){
        while(~scanf("%d",&n)){
            init();
            for(int i=0;i<n;i++)scanf("%d%d%d%d",&a[i],&b[i],&c[i],&d[i]);
            for(int i=0;i<n;i++)for(int j=0;j<n;j++)insert(a[i]+b[j]);
            for(int i=0;i<n;i++)for(int j=0;j<n;j++)ans+=search(-c[i]-d[j]);
            printf("%lld
    ",ans);
        }return 0;
    }
  • 相关阅读:
    Document
    Document
    Document
    2.原型和原型链的关系以及查找顺序
    1.面向对象 及 相关知识点
    时间对象 <-> 定时器 <-> 电子时钟 <-> 倒计时效果
    定时器
    let var const 的区别
    ES6 中块的概念
    js中的闭包
  • 原文地址:https://www.cnblogs.com/forever97/p/poj2785.html
Copyright © 2011-2022 走看看