2020 年机考试题
A、斗牛
#include <iostream> using namespace std; int cal(int* nums) { int sum = 0; for (int i = 0; i < 5; i++) sum += nums[i]; for (int i = 0; i < 5; i++) { for (int j = i + 1; j < 5; j++) { for (int k = j + 1; k < 5; k++) { int temp = nums[i] + nums[j] + nums[k]; if (temp % 10 == 0) { return(sum - temp) % 10; } } } } return -1; } int main() { int n; cin >> n; for (int i = 0; i < n; i++) { int nums[5] = { 0 }; for (int i = 0; i < 5; i++) cin >> nums[i]; cout << cal(nums) << endl; } return 0; }
B、打地鼠
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int n, d; cin >> n >> d; vector<int> nums(n); for (int i = 0; i < n; i++) cin >> nums[i]; sort(nums.begin(), nums.end()); int num = nums[0], cnt = 1; for(int i : nums) if (i - num >= d) { num = i; cnt++; } cout << cnt << endl; return 0; }
C、排队打饭
#include <iostream> using namespace std; int main() { int n; cin >> n; int a, t, b; int time = -1; for (int i = 0; i < n; i++) { cin >> a >> t >> b; if (time == -1) time = a; if (time > a + b) cout << -1 << endl; else { cout << time << endl; time += t; } } return 0; }
D、二叉搜索树
#include <iostream> #include <vector> using namespace std; struct TreeNode { int val; TreeNode* left, * right; TreeNode(int v) : val(v), left(NULL), right(NULL){} }; int fa = 0; vector<int> father; TreeNode* insert(TreeNode* root, int data) { if (root == NULL) { father[data] = fa; return new TreeNode(data); } if (root->val > data) { fa = root->val; root->left = insert(root->left, data); } if (root->val < data) { fa = root->val; root->right = insert(root->right, data); } return root; } void inOrder(TreeNode* root) { if (root == NULL) return; inOrder(root->left); cout << root->val << " "; inOrder(root->right); } int main() { int n, num; cin >> n; TreeNode* root = NULL; father.assign(n + 1, 0); for (int i = 0; i < n; i++) { cin >> num; root = insert(root, num); } //inOrder(root); for (int i = 1; i <= n; i++) cout << father[i] << " "; return 0; }
E、序列
dp[i][j] 代表处理到第 i 个数时填 j 的当前最小权值和
#include <iostream> #include <vector> #include <algorithm> #include <climits> using namespace std; #define N 10 int main() { int n; cin >> n; vector<int>A(n); for (int i = 0; i < A.size(); i++) cin >> A[i]; vector<vector<int>>dp(n, vector<int>(N, INT_MAX)); for (int i = 0; i < N; i++) dp[0][i] = abs(i - A[0]); for (int i = 1; i < A.size(); i++) { for (int j = 0; j < N; j++) { for (int k = 0; k < N; k++) { dp[i][j] = min(dp[i][j], dp[i - 1][k] + abs(A[i] - j) + (j - k) * (j - k)); } } } int result = INT_MAX; for (int i = 0; i < N; i++) result = min(result, dp[n - 1][i]); cout << result << endl; return 0; }
复旦历年机考题解 文章被收录于专栏
复旦历年机试的一些个人题解,仅供参考,欢迎大家一起交流,868388560