ZOJ 2962 Stack By Stack(递归)

题目描述了在一个有n个栈的系统中,按照特定规则进行操作,直到最后一个栈填满。问题求解栈n中第x到第y个数的和。解决方法是通过观察栈间关系,发现每个栈的内容可以通过栈前一个栈的状态递归计算得出,因此使用递归算法来实现。提供的代码实现了这个递归过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2962

题意:给你n个栈,每个栈给定大小为Ci,现在进行这样的操作:

情况1,当没有栈是满的情况,将第一个栈装入1~C1的数,也就是装满;

情况2,有一个栈i已经装满,那么将栈i的内容逐个弹出,装到下一个栈i+1中,直到栈i+1满了,或者栈i空了,注意如果栈i+1先满,且栈i不为空,则清空栈i

所有操作进行到栈n满为止

最后询问栈n中第x到第y个数的和


分析:仔细模拟一遍,发现每个栈i的内容,只和它前一个栈i-1内容有关,即为零个到多个的前一个栈倒置+前一个栈末尾的几个数倒置,也就是要知道栈i的内容,可以去栈i-1找,这样很容易想到用递归来做,具体看代码吧,很短。。。。除了头文件

ps:好久没更新了,一直在刷专题,做训练赛,过一阵子再做些专题总结吧T_T

代码:

/** head files*/
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <fstream>
#include <numeric>
#include <iomanip>
#include <bitset>
#include <list>
#include <stdexcept>
#include <functional>
#include <utility>
#include <ctime>
using namespace std;

/** some operate*/
#define REP(i,n) for(int i=0;i<(n);++i)
#define FOR(i,l,h) for(int i=(l);i<=(h);++i)
#define DWN(i,h,l) for(int i=(h);i>=(l);--i)
#define CLR(arr) memset(arr,0,sizeof(arr))
#define MAX3(a,b,c) max(a,max(b,c))
#define MAX4(a,b,c,d) max(max(a,b),max(c,d))
#define MIN3(a,b,c) min(a,min(b,c))
#define MIN4(a,b,c,d) min(min(a,b),min(c,d))

/** some const*/
#define N 200010
#define PI acos(-1.0)
#define oo 1000000000
#define loo 1000000000000000000LL
#define eps 1e-8
/** some alias*/
typedef long long LL;

int dx[]={0,0,-1,1};
int dy[]={-1,1,0,0};
/** Global variables*/

/** some template names, just push ctrl+j to get it in*/
//getint 读入优化
//manacher 求最长回文子串
//pqueue 优先队列
//combk n元素序列的第m小的组合和
//pmatrix n个点的最大子矩阵
//suffixarray 后缀数组
//sbtree 平衡树
LL sum[N];
int c[N];
LL Query(int n, int x)
{
    if(!n)return (LL)x*(x+1)/2;
    return (LL)sum[n-1]*(x/c[n-1])+sum[n-1]-Query(n-1,c[n-1]-(x%c[n-1]));
}
int main()
{
    int n,x,y;
    while(~scanf("%d",&n))
    {
        REP(i,n)
        {
            scanf("%d",&c[i]);
            sum[i]=Query(i,c[i]);
        }
        scanf("%d%d",&x,&y);
        printf("%lld\n",Query(n-1,y)-Query(n-1,x-1));
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值