标签:
Negative and Positive (NP)BestCoder Round #32
Positive and Negative
维护前缀和sum[i]=a[0]-a[1]+a[2]-a[3]+…+(-1)^i*a[i]
枚举结尾i,然后在hash表中查询是否存在sum[i]-K的值。
如果当前i为奇数,则将sum[i]插入到hash表中。
上面考虑的是从i为偶数为开头的情况。
然后再考虑以奇数开头的情况,按照上述方法再做一次即可。
不同的是这次要维护的前缀和是sum[i]=-(a[0]-a[1]+a[2]-a[3]+…+(-1)^i*a[i])
I为偶数的时候将sum[i]插入到hash表。
总复杂度o(n)
#include<bits/stdc++.h>
using namespace std;
template<class T>inline T read(T&x)
{
char c;
while((c=getchar())<=32)if(c==EOF)return 0;
bool ok=false;
if(c=='-')ok=true,c=getchar();
for(x=0; c>32; c=getchar())
x=x*10+c-'0';
if(ok)x=-x;
return 1;
}
template<class T> inline T read_(T&x,T&y)
{
return read(x)&&read(y);
}
template<class T> inline T read__(T&x,T&y,T&z)
{
return read(x)&&read(y)&&read(z);
}
template<class T> inline void write(T x)
{
if(x<0)putchar('-'),x=-x;
if(x<10)putchar(x+'0');
else write(x/10),putchar(x%10+'0');
}
template<class T>inline void writeln(T x)
{
write(x);
putchar('\n');
}
//-------ZCC IO template------
const int maxn=1e6+1000;
const double inf=999999999;
#define lson (rt<<1),L,M
#define rson (rt<<1|1),M+1,R
#define M ((L+R)>>1)
#define For(i,t,n) for(int i=(t);i<(n);i++)
typedef long long LL;
typedef double DB;
typedef pair<int,int> P;
#define bug printf("---\n");
#define mod 100007
LL sum[maxn];
LL a[maxn];
vector<LL> hash_[mod];
void insert(LL key)
{
int pos=(key%mod+mod)%mod;
hash_[pos].push_back(key);
}
bool find(LL key)
{
int pos=(key%mod+mod)%mod;
int N=hash_[pos].size();
for(int i=0;i<N;i++)
if(hash_[pos][i]==key)return true;
return false;
}
bool solve(LL n,LL k)
{
for(int i=0;i<mod;i++)hash_[i].clear();
insert(0);
for(int i=0;i<n;i++)
{
if(find(sum[i]-k))return true;
if(i&1)insert(sum[i]);
}
for(int i=0;i<mod;i++)hash_[i].clear();
for(int i=0;i<n;i++)
{
if(find(-sum[i]-k))return true;
if(!(i&1))insert(-sum[i]);
}
return false;
}
int main()
{
int T,cas=1;
read(T);
while(T--)
{
LL k,n;
read_(n,k);
for(int i=0;i<n;i++)
{
read(a[i]);
}
sum[0]=a[0];
for(int i=1;i<n;i++)
if(i&1)
sum[i]=sum[i-1]-a[i];
else
sum[i]=sum[i-1]+a[i];
printf("Case #%d: %s\n",cas++,solve(n,k)?"Yes.":"No.");
}
return 0;
}
Negative and Positive (NP) ( Hash 维护 )
标签:
原文地址:http://blog.csdn.net/u013167299/article/details/45218351