跳到正文

个人记录

清点人数题解

HenryG约 2 分钟
原文
文章信息与版本

文章信息

发布
2019年8月3日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 2 分钟

版本

  1. v1当前

〖算法分析〗

模拟题。

我们看到车厢编号m是递增的, 所以用一个变量ans记录前m个车厢人数的部分和;以后每次有上下车,如果在 m 之前就直接在 ans 上加减,m 移动时,把新走过的车厢上的人数都加到 ans 上去就行了。

参考程序 Code:

C++
#include <cstdio> 
#include <cstring> 
using namespace std; 
const int maxn=500500; 
int n, k, now, ans=0, a[maxn];
void doa() { 
 int x; 
 scanf("%d", &x); 
 for(int i=now; i<=x; i++) 
  ans += a[i]; 
 now=x; 
 printf("%d\n", ans); 
 ans -= a[x];
}
void dob() { 
 int x, y; 
 scanf("%d%d", &x, &y); 
 if (x<now) ans+=y; else a[x]+=y; 
}
void doc() { 
 int x, y; 
 scanf("%d%d", &x, &y); 
 if (x<now) ans-=y; 
 else a[x]-=y; 
}
void work() { 
 ans=0; 
 now=1; 
 for (int i=0; i<k; i++) { 
  getchar();
  char ch=getchar();   
  if(ch=='A') doa(); 
  if(ch=='B') dob(); 
  if(ch=='C') doc();
 } 
}
int main() { 
 freopen("number.in", "r", stdin); 
 freopen("number.out", "w", stdout); 
 scanf("%d%d", &n, &k); 
 work(); 
 fclose(stdin); 
 fclose(stdout);
 return 0; 
}
原文