顾名思义:用某一个数组来记录数组a前i项和,这个还可以用来求区间[l,r]的和:s[r]-s[l-1](因为第l项也在区间内)
话不多说,直接上例题:LeetCode 5393
AC代码:
const int MAXN = 1e5 + 5;
class Solution {
public:
int pre[MAXN],suf[MAXN];
int maxScore(vector<int>& cardPoints, int k) {
int n = cardPoints.size();
memset(pre,0,sizeof(pre));
memset(suf,0,sizeof(suf));
for(int i = 1;i <= n;++i){
pre[i] += (pre[i - 1] + cardPoints[i - 1]);
suf[i] += (suf[i - 1] + cardPoints[n - i]); //!!!
}
int ans = 0;
for(int i = 0;i <= k;++i){ //枚举左边拿的张数
ans = max(ans,pre[i] + suf[k - i]);
}
return ans;
}
};
传送门:洛谷P3397
下面贴下AC代码(后面有利用差分的优化):
#include
#include
#include
using namespace std;
const int maxn = 1000 + 5;
int n,m;
int ans[maxn][maxn];
int main(void){
scanf("%d%d",&n,&m);
memset(ans,0,sizeof(ans));
int x1,y1,x2,y2;
for(int i = 0;i < m;++i){
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
for(int x = x1;x <= x2;++x){
for(int y = y1;y <= y2;++y) ans[x][y]++;
}
}
for(int x = 1;x <= n;++x){
for(int y = 1;y <= n;++y){
if(y == 1) printf("%d",ans[x][y]);
else printf(" %d",ans[x][y]);
}
printf("\n");
}
return 0;
}
#include
#include
#include
using namespace std;
const int maxn = 1000 + 5;
int n,m;
int ans[maxn][maxn],p[maxn][maxn];
int main(void){
scanf("%d%d",&n,&m);
memset(ans,0,sizeof(ans));
memset(p,0,sizeof(p));
int x1,y1,x2,y2;
for(int i = 0;i < m;++i){
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
for(int row = y1;row <= y2;row++){
p[x1][row]++; p[x2 + 1][row]--; //注意这边是x2+1
}
}
for(int x = 1;x <= n;++x){
for(int y = 1;y <= n;++y){
ans[x][y] = ans[x-1][y] + p[x][y];
if(y == 1) printf("%d",ans[x][y]);
else printf(" %d",ans[x][y]);
}
printf("\n");
}
return 0;
}
AC代码:
#include
#include
#include
#include
#define LL long long
using namespace std;
const int maxn = 1e5 + 5;
LL a[maxn],b[maxn],c[maxn],times[maxn],city[maxn];
int n,m;
int main(void){
memset(times,0,sizeof(times));
scanf("%d%d",&n,&m);
for(int i = 1;i <= m;++i) cin >> city[i];
for(int i = 1;i <= n - 1;++i) cin >> a[i] >> b[i] >> c[i];
//次数
for(int i = 2;i <= m;++i){
if(city[i] < city[i-1]){
times[city[i-1]]--; times[city[i]]++;
}
else if(city[i] > city[i-1]){
times[city[i]]--; times[city[i-1]]++;
}
}
LL ans = 0;
for(int i = 1;i < n;++i){
times[i] += times[i-1]; ans += min(times[i]*a[i],c[i] + b[i] * times[i]);
}
cout << ans;
return 0;
}