Last active
July 20, 2018 17:22
-
-
Save sarb1208/ad3415564a3bdca4af5b1c7ccacd91e7 to your computer and use it in GitHub Desktop.
Code for spoj problem named "Cath Fish"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<bits/stdc++.h> | |
using namespace std; | |
int f[100001],s[100001]; | |
int I[100001]; | |
int memo[100001]; | |
int fun(int i,int n){ | |
int ans = 0; | |
if(i>n) | |
return 0; | |
if(memo[i]!=-1) | |
return memo[i]; | |
if(I[i]>0){ | |
ans = max(fun(i+1,n),fun(i+I[i],n)+s[i+I[i]-1]-s[i-1]); | |
}else if(I[i]<0){ | |
ans = fun(i-I[i],n)+s[i-I[i]-1]-s[i-1]; | |
}else | |
ans = fun(i+1,n); | |
memo[i] = ans; | |
return ans; | |
} | |
int main(){ | |
map<int,int> m; | |
map<int,int> :: iterator it; | |
int n,i,j,n1; | |
scanf("%d",&n); | |
for(i=1;i<=n;i++) | |
{ | |
memo[i] = -1; | |
scanf("%d",&f[i]); | |
s[i] = s[i-1] + f[i]; | |
} | |
scanf("%d",&n1); | |
while(n1--){ | |
scanf("%d%d",&i,&j); | |
m[0-i] = j; | |
} | |
int p = n+1; | |
int k,l; | |
for(it=m.begin();it!=m.end();it++){ | |
i = 0-(it->first); | |
j = it->second; | |
if(i+j-1<p){ | |
p = i; | |
k = i; | |
it++; | |
if(it!=m.end()) | |
l = 0-((it)->first); | |
else | |
l = 0; | |
while(k>l&&k>=i-j+1){ | |
I[k] = j; | |
k--; | |
} | |
I[p] = 0-j; | |
it--; | |
}else{ | |
p = p-j; | |
k = i; | |
it++; | |
if(it!=m.end()) | |
l = 0-((it)->first); | |
else | |
l = 0; | |
while(k>l&&k>=i-j+1) | |
{ | |
I[k] = j; | |
k--; | |
} | |
I[p] = 0-j; | |
it--; | |
} | |
// printf("%d %d\n",i,j); | |
} | |
/* for(i=1;i<=n;i++){ | |
printf("%d ",I[i]); | |
}*/ | |
printf("%d",fun(1,n)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment