2018_2_7_Stack By Stack _记忆递归升级_哈希

4 篇文章 0 订阅
1 篇文章 0 订阅

注意long long

There are n stacks, named in order S[1], S[2], S[3], ... ,S[n]. Initially, all of them are empty. The following process ends when S[n] is full.

If non of the stacks is full, S[1] is filled by numbers 1, 2, 3, ... in order until it's full. Else, there is a full stack S[i], it is poped and pushed into S[i+1] until S[i] is empty or S[i+1] is full, whichever comes first. If S[i+1] is full and there are numbers in S[i], the numbers in S[i] are poped away.


Input

There are multiple test cases. There are three lines for each case. The first line is an integer N (1 <= N <= 1,000), the number of stacks. The second line is N integers: C1 C2 ... CN , in which Ci (1 <= Ci <= 1,000,000,000) is the size of ith stack. The third line is two integers X and Y (1 <= X <= Y <= CN ).

Process to the end of file.

Output

For each case, print a number in one line, the sum of the numbers in S[n] from index X to Y. The index starts from 1 at the bottom of a stack. The result will fit in a signed 64-bit integer.

Sample Input

1
100
1 100
2
2 4
1 3
3
5 3 5
3 4

Sample Output

5050
5
8
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

const int maxn=1000+10;
const int maxp=1e5;

#define ll long long

struct record{
	int x,y;
	long long k;
	int next;
}p[maxp];

int used,f[maxn];
int n,c[maxn];

void insert(long long ans,int x,int y,int k){
	p[used].x=x;p[used].y=y;
	p[used].k=ans;p[used].next=f[k];
	f[k]=used++;
}

long long hash(int x,int y,int k){
	int i=f[k];
	while(i>=0){
		if(x==p[i].x&&y==p[i].y)return p[i].k;
		i=p[i].next;
	}
	return 0;
}

int relpos(int k,int len){
	return k%len==0?len:k%len; 
}

long long solve(int x,int y,int k){
	long long sum=hash(x,y,k);
	if(sum)return sum;
	if(k==1){
		sum=(long long)(x+y)*(y-x+1)/2;
		insert(sum,x,y,k);
		return sum;
	}
	int nx=relpos(x,c[k-1]);
	nx=c[k-1]-nx+1;
	int ny=relpos(y,c[k-1]);
	ny=c[k-1]-ny+1;
	if(y-x==nx-ny)return solve(ny,nx,k-1);
	int tmp=(y-x+1)-nx-(c[k-1]-ny+1);
	sum+=solve(1,c[k-1],k-1)*(tmp/c[k-1]);
	sum+=solve(ny,c[k-1],k-1)+solve(1,nx,k-1);
	insert(sum,x,y,k);
	return sum;
}

int main(){
	while(cin>>n){
		for(int i=1;i<=n;i++)
		cin>>c[i];
		int x,y;
		cin>>x>>y;
		used=0;
		memset(f,-1,sizeof(f));
		cout<<solve(x,y,n)<<endl;
	}
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值