C++普及组复赛模拟试卷
时间: 2023-06-18 07:06:18 浏览: 50
很高兴能为你提供C++普及组复赛模拟试卷,以下是题目及参考答案。
题目一:
输入一个正整数n,输出其各位数字之和。
输入格式:
一个正整数n,0<n<1000000000。
输出格式:
一个整数,表示n的各位数字之和。
样例输入:
12345
样例输出:
15
参考答案:
```c++
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
cout << sum << endl;
return 0;
}
```
题目二:
输入一个字符串,判断其是否为回文串。
输入格式:
一个字符串,长度不超过100。
输出格式:
如果是回文串,输出"Yes",否则输出"No"。
样例输入:
level
样例输出:
Yes
参考答案:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char s[101];
cin >> s;
int len = strlen(s);
bool flag = true;
for (int i = 0; i < len / 2; i++) {
if (s[i] != s[len - i - 1]) {
flag = false;
break;
}
}
if (flag) cout << "Yes" << endl;
else cout << "No" << endl;
return 0;
}
```
题目三:
定义一个二叉树的节点,包括左右子节点和节点权值。给定一棵二叉树的根节点和两个整数x和y,求x和y在该二叉树中的最近公共祖先。
输入格式:
一行,包括整数序列和两个整数x和y,整数之间用空格隔开,-1表示空节点,其中根节点的权值为1。
输出格式:
输出一个整数,表示x和y的最近公共祖先节点的权值。
样例输入:
1 2 3 4 5 -1 -1 -1 -1 6 7 -1 -1 -1
2 3
样例输出:
1
参考答案:
```c++
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x): val(x), left(NULL), right(NULL) {}
};
TreeNode* buildTree() {
int val;
cin >> val;
if (val == -1) return NULL;
TreeNode* root = new TreeNode(val);
root->left = buildTree();
root->right = buildTree();
return root;
}
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == NULL) return NULL;
if (root == p || root == q) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left != NULL && right != NULL) return root;
if (left == NULL) return right;
else return left;
}
int main() {
TreeNode* root = buildTree();
int x, y;
cin >> x >> y;
TreeNode* p = new TreeNode(x);
TreeNode* q = new TreeNode(y);
TreeNode* lca = lowestCommonAncestor(root, p, q);
cout << lca->val << endl;
return 0;
}
```
题目四:
有一个长度为n的整数序列,求其中最长的严格上升子序列的长度。
输入格式:
第一行一个整数n,1≤n≤1000。
第二行为n个用空格隔开的整数,表示整数序列。
输出格式:
一个整数,表示最长的严格上升子序列的长度。
样例输入:
5
1 3 2 3 4
样例输出:
4
参考答案:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main() {
int n;
cin >> n;
int a[n], dp[n];
for (int i = 0; i < n; i++) {
cin >> a[i];
dp[i] = 1;
}
int ans = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
if (a[j] < a[i]) {
dp[i] = max(dp[i], dp[j] + 1);
}
}
ans = max(ans, dp[i]);
}
cout << ans << endl;
return 0;
}
```
题目五:
有n个数,每个数都在[1,100]范围内,问有多少个数出现了至少两次。
输入格式:
第一行一个整数n,1≤n≤1000。
第二行为n个用空格隔开的整数,表示n个数。
输出格式:
一个整数,表示至少出现两次的数的个数。
样例输入:
5
1 2 3 1 4
样例输出:
1
参考答案:
```c++
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int a[101] = {0};
for (int i = 0; i < n; i++) {
int x;
cin >> x;
a[x]++;
}
int ans = 0;
for (int i = 1; i <= 100; i++) {
if (a[i] >= 2) ans++;
}
cout << ans << endl;
return 0;
}
```