本文最后更新于 2026年2月3日 晚上
CF 266B - Queue at the School (800)
题意:队伍只含 B/G,进行 t 秒;每秒同时把所有 “BG” 变成 “GB”。输出最终队形。
思路:模拟 t 轮;每轮从左到右扫描,遇到 BG 交换,并 i += 2 跳过下一位,避免本秒重复参与。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| #include<iostream> #include<string> using namespace std; int main(){ string s; int n,t; cin >> n >> t; cin >> s; while(t--){ for(int i=0;i<n;){ if(s[i]=='B'&&s[i+1]=='G'){ s[i]='G'; s[i+1]='B'; i+=2; } else i++; } } cout << s; return 0; }
|
CF 228A - Is your horseshoe on the other hoof? (800)
题意:给定4个整数,表示4只马蹄铁的颜色,求至少需要换多少只马蹄铁,使得4只马蹄铁颜色都不同。
思路:用 set 存颜色,最后 4 - set.size() 即为答案。
1 2 3 4 5 6 7 8 9 10 11 12 13
| #include<iostream> #include<set> using namespace std; int main(){ set<int> colors; for(int i=1;i<=4;i++){ int x; cin >> x; colors.insert(x); } cout << 4 - colors.size(); return 0; }
|
不用set也可以:可以使用排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| #include<iostream> #include<algorithm> using namespace std; int main(){ int a[4]; for(int i=0;i<4;i++){ cin >> a[i]; } sort(a,a+4); int count=0; for(int i=1;i<4;i++){ if(a[i]==a[i-1])count++; } cout << count; return 0; }
|
CF 977B - Two-gram (800)
题意:给定一个字符串,找出出现次数最多的连续两个字符组成的的子串。
思路:遍历字符串,统计每个长度为2的子串出现次数,最后找出出现次数最多的子串。
“最优解”:unordered_map 统计频次,遍历字符串时直接更新频次并记录最大值对应的子串。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| #include<iostream> #include<string> #include<unordered_map> using namespace std; int main(){ string s,res; unordered_map<string,int> cnt; int n,best=-1; cin >> n >> s; for(int i=0;i<n-1;i++){ string temp = s.substr(i,2); int c = ++cnt[temp]; if(c>best)best=c,res=temp; } cout << res; return 0; }
|
也可以使用map
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| #include<iostream> #include<string> #include<map> using namespace std; int main(){ string s,res; map<string,int> cnt; int n,best=0; cin >> n >> s; for(int i=0;i+1<n;i++) cnt[s.substr(i,2)]++; for(auto &kv:cnt){ if(kv.second>best){ res=kv.first; best=kv.second; } } cout << res; return 0; }
|
其中
1 2 3 4 5 6
| for(auto &kv:cnt){ if(kv.second>best){ res=kv.first; best=kv.second; } }
|
的部分是现代写法,等价于
1 2
| for(map<string,int>::iterator it=cnt.begin();it!=cnt.end();it++) res=max(res,it->second);
|