DP34. 【模板】前缀和
描述
输入描述
输出描述
示例1
输入:
3 2 1 2 4 1 2 2 3
输出:
3 6
C++ 解法, 执行用时: 20ms, 内存消耗: 2956KB, 提交时间: 2021-12-03
#include <bits/stdc++.h> using namespace std; template <typename T> inline void read(T &f) { f=0;T fu=1;char c=getchar(); while(c<'0'||c>'9') {if(c=='-'){fu=-1;}c=getchar();} while(c>='0'&&c<='9') {f=(f<<3)+(f<<1)+(c&15);c=getchar();} f*=fu; } template <typename T> void print(T x) { if(x<0) putchar('-'),x=-x; if(x<10) putchar(x+48); else print(x/10),putchar(x%10+48); } template <typename T> void print(T x, char t) { print(x);putchar(t); } typedef long long ll; const int maxn=1e5+50; int n,q,a[maxn]; ll sum[maxn]; void solve() { read(n),read(q); for(int i=1;i<=n;++i) read(a[i]); for(int i=1;i<=n;++i) sum[i]=sum[i-1]+a[i]; while(q--) { int l,r; read(l),read(r); print(sum[r]-sum[l-1],'\n'); } } int main() { #ifdef AC freopen("in.txt","r",stdin); freopen("out.txt","w",stdout); #endif clock_t program_start_clock=clock(); solve(); #ifdef NO_TLE fprintf(stderr,"\nTotal Time: %lf ms",double(clock()-program_start_clock)/(CLOCKS_PER_SEC/1000)); #endif return 0; }
C++ 解法, 执行用时: 22ms, 内存消耗: 2596KB, 提交时间: 2022-04-12
#include<bits/stdc++.h> #define int long long using namespace std; inline int read(){ int x = 0,f = 1; char ch = getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9')x=(x<<1)+(x<<3)+(ch^48),ch=getchar(); return x*f; } const int MAX = 1e5+10; int n,q,l,r; int a[MAX]; signed main(){ // freopen(".in","r",stdin); // freopen(".out","w",stdout); n = read(),q = read(); for(int i = 1;i<=n;i++) a[i]=a[i-1]+read(); while(q--){ l = read(),r = read(); printf("%lld\n",a[r]-a[l-1]); } return 0; }
C++ 解法, 执行用时: 27ms, 内存消耗: 2576KB, 提交时间: 2022-05-08
#include<bits/stdc++.h> #define int long long using namespace std; inline int read() { int x = 0, f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-')f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9')x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar(); return x * f; } const int MAX = 1e5 + 10; int n, q, s, r; int a[MAX]; signed main() { n = read(), q = read(); for (int i = 1; i <= n; i++) a[i] = a[i - 1] + read(); while (q--) { s = read(), r = read(); printf("%lld\n", a[r] - a[s - 1]); } return 0; }
C++ 解法, 执行用时: 32ms, 内存消耗: 2592KB, 提交时间: 2022-02-10
#include<cstdio> #include<iostream> #include<algorithm> using namespace std; int n,q; long long int a[100005]; int main(){ scanf("%d%d",&n,&q); a[0]=0; for(int i=1;i<=n;i++){ scanf("%lld",&a[i]); a[i]+=a[i-1]; } for(int i=1;i<=q;i++){ int l,r; scanf("%d%d",&l,&r); printf("%lld\n",a[r]-a[l-1]); } return 0; }
C++ 解法, 执行用时: 32ms, 内存消耗: 2992KB, 提交时间: 2021-11-17
#include<iostream> #include<cstdio> using namespace std; const int N=100010; int n,q,a[N]; long long s[N]; int main() { scanf("%d%d",&n,&q); for(int i=1;i<=n;i++){ scanf("%d",&a[i]);s[i]=s[i-1]+a[i]; } for(int i=1;i<=q;i++){ int l,r; scanf("%d%d",&l,&r); printf("%lld\n",s[r]-s[l-1]); } return 0; }