Блог пользователя codeworrior

Автор codeworrior, 16 лет назад, По-английски
i  m doing this (spoj SUBSEQ) problem on spoj...my algo is n*logn bt its giving me TLE ...hw this problem is to b solved ..i m using map...
here is the code...

int main()
{
     map<int,int>list;
    int t;
    scanf("%d",&t);
    while(t--)
    {
        list.clear();
        int n;
        scanf("%d",&n);
        int tmp;
        VI a,sum(n+1);
        a.pb(0);
        FOR(i,1,n)
        {
            scanf("%d",&tmp);
            a.pb(tmp);
            sum[i]=tmp+sum[i-1];
            list[sum[i]]++;
        }
        list[0]++;
        int64 ans=0;
        int val;
        for(int i=n;i>=0;i--)
        {
            list[sum[i]]--;
            val=list[sum[i]-47];
            if(val>0)
                ans+=val;
        }
        printf("%lld\n",ans);
    }
}
  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

16 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится
Sum[i..j]=S[j]-S[i-1]...
Using Hash...

AC code down:

#include<iostream>
#include<cstdio>
#include<map>
#define REP(i,n) for(int i=0;i<n;i++)
using namespace std;
typedef long long LL;
typedef map<LL,int>::iterator It;
int t;
void solve()
{
     scanf("[^/n]");
     int n;scanf("%d",&n);
     LL s=0,ans=0,t;
     map<LL,int> M;
     M[0]=1;
     REP(i,n)
     {
       scanf("%lld",&t);s+=t;
       It a=M.find(s-47);
       if(a!=M.end()) ans+=(*a).second;
       a=M.find(s);
       if(a!=M.end()) (*a).second++;
       else M[s]=1;
     }
     cout<<ans<<endl;
}
int main()
{
    cin>>t;
    while(t--)
    {
       solve();
    }
}
16 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится
here is the code ..previous one was incorrect..
int main()
{
  map<int,int>list;
int t;
scanf("%d",&t);
while(t--)
{
list.clear();
int n;
scanf("%d",&n);
int tmp;
VI sum(n+1);
list[0]++;
int64 ans=0,val;
FOR(i,1,n)
{
scanf("%d",&tmp);
sum[i]=tmp+sum[i-1];
            val=list[sum[i]-47];
ans+=val;
list[sum[i]]++;
}
printf("%lld\n",ans);
}
}

16 лет назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится
i got AC in 7.44 sec.. jst took the declaration of map inside the while loop and removed list.clear() statement..

bt the bst solution in this prob is 0.66 sec..hw to achieve time of under 2 sec...
thnx in advance...