2025暑假c++算法笔记📕

输入输出方式

cin cout scanf() printf()

格式:

cin >> cout << 慢(关闭同步流) ios ::sync_with_stdio(false); cin.tie(0);

scanf(“%d”, &x); printf(“%d”,x); 高

效率:数据量在万级一下不明显

cin 返回的是否与容器内容 scanf

空白文档 - 图1

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. const int N = 105;
  4. char arr[N];
  5. int main(){
  6. int n;
  7. char x;
  8. cin >> n;
  9. for(int i = 1 ; i <= n ; i ++){
  10. scanf("%c",&x); // 可读取所有字符
  11. arr[i] = x;
  12. }
  13. for(int i = n ; i > 0 ; i --){
  14. int idx = arr[i]+1;
  15. if (idx%2 == 0){
  16. printf("%d ",i);
  17. }
  18. }
  19. }

空白文档 - 图2

  1. int n;
  2. vector <int> a;
  3. while (cin >> x){
  4. a.push_back(x);
  5. }
  6. sort(a.begin(),a.end());
  1. int x ;
  2. while(cin >> x){ // cin 自动忽略空格,输入数据与容器类型是否一致
  3. }
  4. while(scanf("%d",&x) == 1){ // 判断有效的获取数据数量
  5. }
  6. ``
  7. ![](/projects/book/202507/185095ea352277ad.png)
  8. int n;
  9. while(cin >> n && n !=0 ){
  10. }

空白文档 - 图3

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int main(){
  4. int p,x,sum;
  5. p=1;
  6. x=15;
  7. sum=x;
  8. do{
  9. p++;
  10. x+=2;
  11. sum+=x;
  12. }while(sum!=312);
  13. // cout<<x<<endl;
  14. // cout<<p<<endl;
  15. printf("%d\n%d\n",x,p);
  16. return 0;
  17. }
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int main(){
  4. int x = 0 ;
  5. do{
  6. x++;
  7. }while((x+6)%13 != 0 || (x-6)%12 != 0);
  8. cout << x << endl;
  9. }

拍手游戏

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int main(){
  4. int time,count,teacher,mingming,meimei;
  5. bool flag;
  6. time = 0;
  7. count = 1;
  8. teacher = mingming = meimei = 0;
  9. do{
  10. flag = 0;
  11. time++;
  12. if(teacher < 9){
  13. flag = 1;
  14. teacher ++;
  15. }
  16. if(mingming < 9 && time%4 == 0){
  17. flag = 1;
  18. mingming ++;
  19. }
  20. if(meimei < 9 && time % 4 == 0){
  21. flag = 1;
  22. meimei ++;
  23. }
  24. if(flag) count++;
  25. }while(teacher + mingming + meimei < 9 * 3);
  26. cout << count << endl;
  27. return 0;
  28. }

课堂练习

  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int main(){
  4. int n,t,ans;
  5. n = 1;
  6. t = 2;
  7. ans = 0;
  8. do{
  9. n=n*t;
  10. ans += n;
  11. }while(n <= 1e + 3);
  12. cout << ans << endl;
  13. return 0;
  14. }