2025暑假c++算法笔记📕
输入输出方式
cin cout scanf() printf()
格式:
cin >> cout << 慢(关闭同步流) ios ::sync_with_stdio(false); cin.tie(0);
scanf(“%d”, &x); printf(“%d”,x); 高
效率:数据量在万级一下不明显
cin 返回的是否与容器内容 scanf
#include<bits/stdc++.h>
using namespace std;
const int N = 105;
char arr[N];
int main(){
int n;
char x;
cin >> n;
for(int i = 1 ; i <= n ; i ++){
scanf("%c",&x); // 可读取所有字符
arr[i] = x;
}
for(int i = n ; i > 0 ; i --){
int idx = arr[i]+1;
if (idx%2 == 0){
printf("%d ",i);
}
}
}
int n;
vector <int> a;
while (cin >> x){
a.push_back(x);
}
sort(a.begin(),a.end());
int x ;
while(cin >> x){ // cin 自动忽略空格,输入数据与容器类型是否一致
}
或
while(scanf("%d",&x) == 1){ // 判断有效的获取数据数量
}
``

int n;
while(cin >> n && n !=0 ){
}
#include<bits/stdc++.h>
using namespace std;
int main(){
int p,x,sum;
p=1;
x=15;
sum=x;
do{
p++;
x+=2;
sum+=x;
}while(sum!=312);
// cout<<x<<endl;
// cout<<p<<endl;
printf("%d\n%d\n",x,p);
return 0;
}
#include<bits/stdc++.h>
using namespace std;
int main(){
int x = 0 ;
do{
x++;
}while((x+6)%13 != 0 || (x-6)%12 != 0);
cout << x << endl;
}
拍手游戏
#include<bits/stdc++.h>
using namespace std;
int main(){
int time,count,teacher,mingming,meimei;
bool flag;
time = 0;
count = 1;
teacher = mingming = meimei = 0;
do{
flag = 0;
time++;
if(teacher < 9){
flag = 1;
teacher ++;
}
if(mingming < 9 && time%4 == 0){
flag = 1;
mingming ++;
}
if(meimei < 9 && time % 4 == 0){
flag = 1;
meimei ++;
}
if(flag) count++;
}while(teacher + mingming + meimei < 9 * 3);
cout << count << endl;
return 0;
}
课堂练习
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,t,ans;
n = 1;
t = 2;
ans = 0;
do{
n=n*t;
ans += n;
}while(n <= 1e + 3);
cout << ans << endl;
return 0;
}
#include<bits/stdc++.h>
using namespace std;
int main(){
int num=0,glair=1,nike=1;
for(int i = 1 ; i <= 1000 ;i ++){
nike ++;
glair ++;
if(nike > 20){
nike = 1;
}
if(glair > 30){
glair = 1;
}
if (nike == glair){
num ++;
}
}
cout << num;
return 0;
}