文章目录
牛客小白月赛101(栈、差分、调和级数、滑动窗口)
A. tb的区间问题
维护连续 (n-k)个元素的sum,取max即可。
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn = 1e5 + 5;
ll a[maxn];
int main(){
int n, k;
cin >> n >> k;
for(int i = 1; i <= n; i++) cin >> a[i];
ll sum = 0;
for(int i = 1; i <= n-k; i++) sum += a[i];
ll res = sum;
for(int i = 1; i <= k; i++){
sum -= a[i];
sum += a[n-(k-i)];
res = max(res, sum);
}
cout << res << endl;
return 0;
}
B. tb的字符串问题(栈)
考虑需要不断弹出已经遍历部分子串的尾部,使用栈维护即可。
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
string s;
cin >> s;
stack<char> st;
for(auto c : s){
if(c == 'c'){
if(!st.empty() && st.top() == 'f') st.pop();
else st.push(c);
}
else if(c == 'b'){
if(!st.empty() && st.top() == 't') st.pop();
else st.push(c);
}
else st.push(c);
}
cout << st.size() << endl;
return 0;
}
C. tb的路径问题(思维)
打表:
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 2 1 2 1 2 1 2 1 2 1 2 1 2 1
1 1 3 1 1 3 1 1 3 1 1 3 1 1 3
1 2 1 4 1 2 1 4 1 2 1 4 1 2 1
1 1 1 1 5 1 1 1 1 5 1 1 1 1 5
1 2 3 2 1 6 1 2 3 2 1 6 1 2 3
1 1 1 1 1 1 7 1 1 1 1 1 1 7 1
1 2 1 4 1 2 1 8 1 2 1 4 1 2 1
1 1 3 1 1 3 1 1 9 1 1 3 1 1 3
1 2 1 2 5 2 1 2 1 10 1 2 1 2 5
1 1 1 1 1 1 1 1 1 1 11 1 1 1 1
1 2 3 4 1 6 1 4 3 2 1 12 1 2 3
1 1 1 1 1 1 1 1 1 1 1 1 13 1 1
1 2 1 2 1 2 7 2 1 2 1 2 1 14 1
1 1 3 1 5 3 1 1 3 5 1 3 1 1 15
可以发现,当 n 比较大时一定存在如下路径,
- n % 2 = 0时:起点 -> 1 —> 2 —> 2(传送) —> 1 - > n
- n % 2 = 1时:起点 -> 1 —> 2 —> 2(传送,上一个偶数行的2) —> 1 or 3 —> 1 —> 1 —> n
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn = 1e5 + 5;
int gcd(int x, int y){
if(y) return gcd(y, x%y);
return x;
}
void func(){ // 打表用
int n = 15;
for(int i = 1; i <= n; i++){
for(int j = 1; j <= n; j++){
printf("%-3d", gcd(i, j));
}
printf(&