Leyanshi
Articles12
Tags6
Categories2

Categories

一言

Archive

C++笔记 2026-06-02

C++笔记 2026-06-02

Conception

暴力计算
鸡兔同笼求解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
int main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int head, feet; cin >> head >> feet;
if (head < feet || head * 4 < feet || head * 2 > feet || feet % 2 == 1) {
cout << "无解";
return 0;
}
for(int i = 0; i < head; i++) {
int j = head - i;
if (j * 4 + i * 2 == feet) {
cout << i << " " << j;
}
}
}

另外的方法(解方程):
设鸡x只,则兔(head-x)只, 列得方程
2x+4(head-x)=feet
2x+4*head-4x=feet
-2x=feet-4*head
x=2*head-feet/2

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;
int main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int head, feet; cin >> head >> feet;
if (head * 4 < feet || head * 2 > feet || feet % 2 == 1) {
cout << "无解";
return 0;
}
int i = 2*head-feet/2;
cout << i << " " << head - i;
}

事先补齐法

就是将有特殊性的问题预处理为没有特殊性
另外:从键盘中输入串(有空格)

  1. cin.getline(buf, len); 需要最大长度
  2. string s; getline(cin, s) C++风格,推荐(需要<string>)