HDU5183Negative and Positive (NP)(哈希表)
来源:互联网 发布:java入门视频百度网盘 编辑:程序博客网 时间:2024/04/30 12:49
题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=5183
题意:
给定一个长度为n的序列,判断是否存在
一段序列 sum(i,j)=a i −a i+1 +a i+2 +⋯+(−1) j−i aj = k;
分析:
我们维护一段前缀和
sum[j]表示从开始到第j个元素, 即 sum(0,j);
然后我们将其加入到哈希表中
因为不同要么是正负正 。。。。,要么就是负正负。。。。的结构
因此我们维护两个哈希表
表1插入 sum ,表2插入-sum;
当i为奇数的时候在表2中查询 sum-k;
当i为偶数的时候在表1中查询 sum+k
然后判断存不存在就好
代码如下:
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;typedef long long LL;const int MAXN=1000010;const int HASH=1000007;inline LL read()//输入外挂{ char ch=getchar();LL x=0,f=1; while(ch>'9'||ch<'0'){if(ch=='-')f=-1;ch=getchar();} while(ch<='9'&&ch>='0'){x=x*10+ch-'0';ch=getchar();} return x*f;}struct hashmap//建立哈希表{ LL a[MAXN]; int head[HASH],next[MAXN],size; void init(){//初始化 memset(head,-1,sizeof(head)); size=0; } bool find(LL val){//查找一个元素是否在哈希表内 int tmp = (val%HASH + HASH)%HASH; for(int i = head[tmp];i!=-1;i=next[i]) if(val==a[i]) return true; return false; } void add(LL val){//添加元素到哈希表中 int tmp =(val%HASH+HASH)%HASH; if(find(val)) return; a[size]=val; next[size]=head[tmp]; head[tmp]=size++; }}h1,h2;LL a[MAXN];int main(){ int t,n,cas=1,k; t=read(); while(t--){ n=read(); k=read(); for(int i=0;i<n;i++) a[i]=read(); LL sum=0; h1.init(),h2.init(); h1.add(0),h2.add(0); bool flag = 0; for(int i=n-1;i>=0;i--){ if(i&1) sum-=a[i]; else sum+=a[i]; if(i%2==0){ if(h1.find(sum-k)) flag=1; } else{ if(h1.find(sum+k)) flag=1; } h1.add(sum); h2.add(-sum); if(flag) break; } printf("Case #%d: ",cas++); if(flag)puts("Yes."); else puts("No."); } return 0;}
0 0
- HDU5183Negative and Positive (NP)(哈希表)
- 手写hash(hdu5183Negative and Positive (NP))
- 【HDU5183】Negative and Positive (NP)
- hdoj5183Negative and Positive (NP)【set】
- hdu 5183 Negative and Positive (NP)【fast IO +哈希表】
- hdu 5183 Negative and Positive (NP)
- HDU 5183 Negative and Positive (NP)
- hdu5138 Negative and Positive (NP) 快速读入
- HDU 5183 - Negative and Positive (NP)(Hash)
- hdu 5183 Negative and Positive (NP)
- Negative and Positive (NP) HDU5183 && Bestcoder#32
- hdu5183---Negative and Positive (NP)(HASHMAP)
- HDU 5183 Negative and Positive (NP) (hash)
- hdu 5183-Negative and Positive (NP)
- Negative and Positive (NP) ( Hash 维护 )
- hdu 5183 Negative and Positive (NP)
- 【Best Coder 】 32 B Negative and Positive (NP)
- hdu 5183 Negative and Positive (NP) (hash大法)
- 设计模式之迭代器模式
- IoCompleteRequest的实现逻辑
- day28_struts2(全天)のPPT学习——06 使用Struts2的输入校验
- hadoop-2.X启动后用JPS命令查看,resourcemanger无法启动:地址已被使用
- Spring 4.x+Spring MVC 4.x+MyBatis 3.x 整合(四)Spring 3.1.0 整合
- HDU5183Negative and Positive (NP)(哈希表)
- POJ2965 The Pilots Brothers' refrigerator(枚举+思维题)
- 地址宏定义
- 通过jni实现c++和java互调
- LightOJ 1422 - Halloween Costumes(区间DP)
- The container 'Android Dependencies' references non existing library
- 莀莂蚈肃腿莄螄蝿聿莇袀羈
- 羆膁葿蚁羅芄芁薇肄羃蒇蒃
- 衿膅肇蚆袁芁芆蒆螄袄莅莅