A336-前缀和
2025-07-28 15:10:07
发布于:广东
2阅读
0回复
0点赞
对于这道题有两种方法
1.暴力
时间复杂度:
#include<bits/stdc++.h>
using namespace std;
long long a[100010];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int m;
int n;
cin>>n>>m;
for(int i=1;i<=n;i++){
cin>>a[i];
}
while(m--){
int l,r;
cin>>l>>r;
int sum=0;
for(int i=l;i<=r;i++){
sum+=a[i];
}
cout<<sum<<endl;
}
return 0;
}
2.前缀和
时间复杂度:
#include<bits/stdc++.h>
using namespace std;
long long a[100010];
long long s[100010];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int m;
int n;
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--){
int l,r;
cin>>l>>r;
cout<<s[r]-s[l-1]<<endl;
}
return 0;
}
这里空空如也
有帮助,赞一个