盒子
盒子
文章目录
  1. 题目
  2. 题意
  3. 思路
  4. 代码

HDU 5183 Negative and Positive (NP)(HashTable)

题目

源地址:http://acm.hdu.edu.cn/showproblem.php?pid=5183

题意

给定n个数的序列(A0,A1,A2…,An-1) 规定NP-sum(i,j) = Ai - Ai+1 + Ai+2 + (-1)^(j-i)Aj
现在给定一个K,问是否有一个NP-sum(i,j)=K
1≤n≤1000000,−1000000000≤ai≤1000000000,−1000000000≤K≤1000000000

思路

sum[i]=a1−a2+a3…。手写一个哈希表来保存所有出现过的sum值,然后根据奇偶性分类判断在哈系表中是否存在对应的子序列满足题意

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<string>
#include<cstdio>
#include<vector>
#define pb push_back
#define debug puts("=====================");
using namespace std;
typedef long long ll;
//Hash Table
#define MAXN 1001000
#define mod 4000007
struct HashKey {
ll key;
int nxt, pos;
}e[MAXN];
int link1[MAXN * 4], p;
void init() {
memset(link1, -1, sizeof(link1));
p = 0;
}
void add(ll key, int pos) {
e[p].key = key;
e[p].pos = pos & 1;
int modKey = key % mod;
if (modKey < 0) modKey += mod;
e[p].nxt = link1[modKey];
link1[modKey] = p++;
}
bool Find(ll key, int odd) {
int modKey = key % mod;
if (modKey < 0) modKey += mod;
for (int i = link1[modKey]; i != -1; i = e[i].nxt) {
if (e[i].key == key && e[i].pos == odd) return true;
}
return false;
}
int main () {
int T, n, k, x;
scanf("%d", &T);
for (int cas = 1; cas <= T; cas++) {
scanf("%d%d", &n, &k);
ll s = 0;
init();
add(s, 0);
bool ok = false;
for (int i = 1; i <= n; i++) {
scanf("%d", &x);
if (i & 1) s += x;
else s -= x;
if (!ok) {
if (Find(s - k, 0)) ok = true;
if (Find(s + k, 1)) ok = true;
add(s, i);
}
}
printf("Case #%d: %s.\n", cas, ok ? "Yes" : "No");
}
return 0;
}