1.小红与奇数
解题思路:如果给定的数是偶数, 由于1是任意正数的因子, 偶数+1=奇数
若给定的数是奇数, +1/+自身, 都变成了偶数
#include <bits/stdc++.h>
using namespace std;
void solve() {
int x;
cin >> x;
if (x & 1)
cout << "No" << '\n';
else
cout << "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;
}
感谢大家的点赞和关注,你们的支持是我创作的动力!