# HDU 5183 Negative and Positive (NP) --Hashmap

1.起点x为奇，那么就看有没有a[j]-a[x-1] = K的，即a[j] = a[x-1]+K。因为奇数位置的ai数符为正。

2.起点x为偶，那么就看有没有a[j]-(-K) = a[x-1]，即a[j] = a[x-1]-K。因为偶数位置ai数符为负，即x到j这一段的数是负的 选x为起点的x到j的这一段和，所以中间实际上是-K。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#define Mod 1000000007
#define lll __int64
#define ll long long
using namespace std;
#define N 1000007

lll sum[N];
const unsigned long long SMod=1000007;
struct hashmap{
struct Edge
{
long long num;
int next;
};
Edge edge[2*N];
int countedge;

void init()
{
countedge=0;
}

{
int start=num%SMod;
edge[countedge].num=num;
countedge++;
}

int Find(long long num)
{
int start=num%SMod;
int ind;
{
if(edge[ind].num==num)break;
}
return ind;
}
}ST;

int main()
{
int n,i,j,cs = 1,t,x,K;
scanf("%d",&t);
while(t--)
{
ST.init();
scanf("%d%d",&n,&K);
sum[0] = 0;
for(i=1;i<=n;i++) {
scanf("%d",&x);
if(i%2) sum[i] = sum[i-1] + x;
else    sum[i] = sum[i-1] - x;
}
int tag = 0;
for(i=n-1;i>=0;i--) {
if(i%2 == 0 && ST.Find(sum[i]+K) != -1) { tag = 1; break; }
if(i%2 && ST.Find(sum[i]-K) != -1) { tag = 1; break; }
}
printf("Case #%d: ",cs++);
if(tag) puts("Yes.");
else    puts("No.");
}
return 0;
}
View Code

...以此类推，归为两类 ：

1. XX-sum[0] , XX-sum[2] , ... XX-sum[偶数] 是否为K

2. -XX+sum[1], -XX+sum[3], ... -XX+sum[奇数] 是否为K

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#define Mod 1000000007
#define lll __int64
#define ll long long
using namespace std;
#define N 1000007

const unsigned long long SMod=1000007;
struct hashmap{
struct Edge
{
long long num;
int next;
};
Edge edge[2*N];
int countedge;

void init()
{
countedge=0;
}

{
int start=num%SMod;
edge[countedge].num=num;
countedge++;
}

int Find(long long num)
{
int start=num%SMod;
int ind;
{
if(edge[ind].num==num)break;
}
return ind;
}
}mpe,mpo;

int main()
{
int n,i,j,cs = 1,t,x,K;
scanf("%d",&t);
for(cs=1;cs<=t;cs++)
{
mpo.init();
mpe.init();
scanf("%d%d",&n,&K);
lll sum = 0;
int tag = 0;
for(i=1;i<=n;i++) {
scanf("%d",&x);
if(i&1) sum += x;
else    sum -= x;
if(mpe.Find(sum-K) != -1) { tag = 1; }
if(mpo.Find(sum+K) != -1) { tag = 1; }
}
printf("Case #%d: ",cs);
if(tag) puts("Yes.");
else    puts("No.");
}
return 0;
}
View Code

hashmap模板借鉴了love_dn的代码。

posted @ 2015-03-08 15:28 whatbeg 阅读(...) 评论(...) 编辑 收藏