1.整行读入 getline(cin,str)
正常读入string遇到空格会中断读入,这时候要用getline(cin,str)
注意如果在这之前用到过cin,要先清除缓存区cin.ignore
在string字符串中寻找子串可以用str.find(“…”),如果存在会返回子串开始的下标,如果不存在会等于 string::npos
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
int n, m;
vector<string> s;
cin >> n >> m;
// 消耗掉输入缓冲区的换行符
cin.ignore();
for (int i = 0; i < n; i++) {
string line;
getline(cin, line);
if (line.find("easy") == string::npos && line.find("qiandao") == string::npos) {
s.push_back(line);
}
}
if (m >= s.size()) {
cout << "Wo AK le" << endl;
} else {
cout << s[m] << endl;
}
return 0;
}
2.最大不相交区间
先将区间读入到vector中,再根据右端点从小到大排序,每遇到一个不相交的区间就ans++
#include <bits/stdc++.h>
using namespace std;
vector<pair<int,int>> A;
int to_int(string s){
int t = 0;
t += ((s[0] - '0') * 10 + (s[1] - '0')) * 60 * 60;
t += ((s[3] - '0') * 10 + (s[4] - '0')) * 60;
t += ((s[6] - '0') * 10 + (s[7] - '0'));
return t;
}
int main(){
int n;
int ans = 0;
cin >> n;
for(int i = 0;i < n;i++){
string a,b;
cin >> a >> b;
A.push_back({to_int(a),to_int(b)});
}
sort(A.begin(),A.end(),[](pair<int,int> a,pair<int,int> b){
return a.second < b.second;
});
int last = -100000000;
for(int i = 0;i < A.size();i++){
int l = A[i].first;
int r = A[i].second;
if(l >= last){
last = r;
ans++;
}
}
cout << ans << endl;
}
3.双dfs
这道题要注意变量
我用的是全选出,其实还有个组合,贴在下面
//全选出
#include <bits/stdc++.h>
using namespace std;
int a[5];
int st[5];
vector<int> A;
vector<int> b;
int n;
bool found;
int sum;
void dfs(int u,int t)
{
if(u == n){
sum += t * t;
A.push_back(t);
return;
}
for(int i = 0;i < n;i++){
if(!st[i]){
t = t * 10 + a[i];
st[i] = true;
dfs(u+1,t);
t = (t - a[i]) / 10;
st[i] = false;
}
}
}
void dfss(int u,int cnt){
if(found) return;
if(cnt > sum / 2) return;
if(u == A.size()){
if(cnt == sum / 2){
for(auto c : b){
cout << c << endl;
}
found = true;
return;
}else{
return;
}
}
cnt += A[u] * A[u];
b.push_back(A[u]);
dfss(u + 1,cnt);
cnt -= A[u] * A[u];
b.pop_back();
dfss(u+1,cnt);
}
int main(){
cin >> n;
for(int i = 0;i < n;i++){
cin >> a[i];
}
dfs(0,0);
dfss(0,0);
}
组合
4.模拟队+模拟栈
我这里栈和队列都是数组模拟的,比较屎山,可以吧栈优化成stack,这样可能会比较清楚些
#include <bits/stdc++.h>
using namespace std;
string str[110];
int head[1110];
int tail[1110];
char stk[110];
int ed = -1;
vector<char> c;
int n,m,s;
int main(){
cin >> n >> m >> s;
for(int i = 1;i <= n;i++){
cin >> str[i];
head[i] = 0;
tail[i] = str[i].size();
}
int op;
while(cin >> op){
if(op == -1){
break;
}else{
if(op == 0){
if(ed != -1){
c.push_back(stk[ed]);
ed--;
}
}else{
if(ed + 1>= s){
c.push_back(stk[ed]);
ed--;
}
if(head[op] < tail[op]){
ed++;
string sss = str[op];
stk[ed] = sss[head[op]++];
}
}
}
}
for(auto i : c){
cout << i;
}
}