1.小紅與奇數
解題思路:如果給定的數是偶數, 由于1是任意正數的因子, 偶數+1=奇數
若給定的數是奇數, +1/+自身, 都變成了偶數
#include <bits/stdc++.h>
using namespace std;
void solve() {int x;cin >> x;if (x & 1)cout << "No" << '\n';elsecout << "Yes" << '\n';
}
int main() {int t = 1;while (t--) {solve();}
}
?2. 小紅與gcd三角形
解題思路:先求gcd(x,y), 然后根據三角形的性質進行判斷?
#include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b) {int t = a % b;while (t) {t = a % b;a = b;b = t;}return b;
}
void solve() {int x, y;cin >> x >> y;if (gcd(x, y) > abs(x - y) && gcd(x, y) < x + y) {cout << "Yes" << '\n';} else {cout << "No" << '\n';}
}
int main() {int t;cin >> t;while (t--) {solve();}
}
?3.小紅與red
解題思路:如果出現兩個連續相同的字符, eg: rrd
中間字符r只要替換為前后都不同的即可
#include <bits/stdc++.h>
using namespace std;
const string t = "red";
void solve() {int n;string s;cin >> n >> s;for (int i = 1; i < n; i++) {if (s[i] == s[i - 1]) {for (char c : t) {if (c != s[i - 1] && (c != s[i + 1] || i == n - 1)) {s[i] = c;break;}}}}cout << s << endl;
}
int main() {int t = 1;while (t--) {solve();}
}
?4.?小紅與好數組
回溯即可
dfs函數
參數包括目標和?n,當前路徑?p,當前和?sum,以及前一個元素?pre。
終止條件:當當前和等于?n?時,將當前路徑加入結果集 ans 中
選擇元素:從1到剩余和(n - sum)中選擇一個不等于前一個元素的數,繼續遞歸
#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> ans;
void dfs(int n, vector<int>& p, int sum, int pre) {if (sum == n) {ans.push_back(p);return;}for (int cur = 1; cur <= n - sum; cur++) {if (cur != pre) {p.push_back(cur);dfs(n, p, sum + cur, cur);p.pop_back();}}
}
void solve() {int n;cin >> n;vector<int> p;dfs(n, p, 0, -1);sort(ans.begin(), ans.end());for (auto& x : ans) {for (int num : x) {cout << num << " ";}cout << '\n';}
}
int main() {int t = 1;while (t--) {solve();}
}
?5. 小紅與gcd和sum
?dp
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 1e6;
void solve() {int n;cin >> n;vector<ll> a(N + 1, 0);for (int i = 0; i < n; i++) {int val;cin >> val;a[val] += val;}vector<ll> dp(N + 1, 0);for (int g = 1; g <= N; g++) {for (int j = g; j <= N; j += g) {dp[g] += a[j];}}ll max_val = 0;for (int g = 1; g <= N; g++) {if (dp[g] > 0) {max_val = max(max_val, (ll)g * dp[g]);}}cout << max_val << endl;
}
int main() {int t = 1;while (t--) {solve();}return 0;
}
?感謝大家的點贊和關注,你們的支持是我創作的動力!
?