acwing:前缀和

//一维前缀和
# include <iostream>
using namespace std;

const int N = 1010;
int n,m;
int a[N],s[N];

int main()
{
    ios::sync_with_stdio(false);//作用:提高运行效率
    cin>>n>>m;
    for (int i = 1 ; i <= n ; ++i) cin>>a[i]; //先将输入进来

    for (int i = 1 ; i <= n ; ++i) s[i] = s[i - 1] + a[i]; //利用递归的思想

    while (m --) // 遍历m次
    {
        int l,r;
        cin>>l>>r; //输入要求和的范围
        cout<<s[r] - s[l - 1]<<"\n"; //注意这里不能用endl;
    }
    return 0;
}

//子矩阵之和
# include <iostream>
using namespace std;

const int N = 1010;
int n,m,q;
int a[N][N],s[N][N];

int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>m>>q;
    for (int i = 1 ; i <= n ; ++i)
        for (int j = 1 ; j <= m ; ++j)
            cin>>a[i][j];
    for (int i = 1 ; i <= n ; ++i)
        for (int j = 1 ; j <= m ; ++j)
            //同样也是利用了递归的思想,画图表示下就十分清晰,也可以举个矩阵的例子
            s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + a[i][j];
    
    while (q --) //遍历q次
    {
        int x1,y1,x2,y2;
        cin>>x1>>y1>>x2>>y2;
        cout<<s[x2][y2] - s[x2][y1 - 1] - s[x1 - 1][y2] + s[x1 - 1][y1 - 1]<<"\n";
    }
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值