8 条题解
-
1
提供一种大炮打蚊子方法 用序列线段树或树状数组维护01数组 计算 1~n 总和 时间复杂度 O(n+logn) 建树 O(n),计算 O(log n)
#include<bits/stdc++.h> using namespace std; const int inf=0; int tree[2000005]; int a[2000005]; int n,q; inline int f(int a,int b) { return a+b; } inline void init(int p,int l,int r) { if(l==r) tree[p]=a[l]; else { int mid=(l+r)/2; init(p*2,l,mid); init(p*2+1,mid+1,r); tree[p]=f(tree[p*2],tree[p*2+1]); } } inline void replace(int x,int y) { int posx=1,posy=n,pos=1; while(posx<posy) { if(x>(posx+posy)/2) { posx=(posx+posy)/2+1; pos=pos*2+1; } else { posy=(posx+posy)/2; pos*=2; } } tree[pos]+=y; pos>>=1; while(pos>0) { tree[pos]=f(tree[pos*2],tree[pos*2+1]); pos>>=1; } } inline int cal(int l,int r,int x,int y,int p) { if(x>=l&&y<=r) return tree[p]; else if(x>r||l>y) { return inf; } else { int left = cal(l,r,x,(x+y)/2,p*2); int right = cal(l,r,(x+y)/2+1,y,p*2+1); return f(left,right); } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); string s; cin>>s; n=s.size(); for(int i = 1;i<=n;i++) { a[i]=(s[i-1]=='1'); } init(1,1,n); cout<<cal(1,n,1,n,1); return 0; } -
1
A. 数字游戏 · 题解
CSP-J 2019 第二轮认证
解题思路
把输入读成字符串,从左到右检查每个字符。遇到字符
1,计数器加一;遇到0,计数器不变。例如
00110100中有三个1,答案就是 。使用字符串读取可以自然保留开头的零。正确性与复杂度
处理完前 个字符后,计数器恰好等于这 个字符中
1的数量。每次检查保持这一性质,因此遍历结束时得到所求答案。字符串长度固定为 ,时间和空间复杂度均为 。
参考代码(C++11)
#include <bits/stdc++.h> using namespace std; int main() { string s; cin >> s; int ans = 0; for (char c : s) ans += (c == '1'); cout << ans << '\n'; } -
0
A. 数字游戏 · 题解 CSP-J 2019 第二轮认证
解题思路 把输入读成字符串,从左到右检查每个字符。遇到字符 1,计数器加一;遇到 0,计数器不变。
例如 00110100 中有三个 1,答案就是 33。使用字符串读取可以自然保留开头的零。
正确性与复杂度 处理完前 ii 个字符后,计数器恰好等于这 ii 个字符中 1 的数量。每次检查保持这一性质,因此遍历结束时得到所求答案。
字符串长度固定为 88,时间和空间复杂度均为 O(1)O(1)。
#include<bits/stdc++.h> using namespace std; char c[10]; int cnt=0; int main(){ for(int i=1;i<=8;i++){ cin>>c[i]; if(c[i]=='1'){ cnt++; } } cout<<cnt; }
- 1
信息
- ID
- 2216
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 5
- 标签
- 递交数
- 70
- 已通过
- 29
- 上传者