语法周赛 Round 29 题解
2024年12月25日大约 3 分钟
A. 初赛估分
- 子任务 1:必然能过,输出
Yes
即可。 - 子任务 2:直接分别除以
和 就行,不用担心整型相除自动取整。 - 子任务 3:建议能只用整型就只用整型。
#include <bits/stdc++.h>
using namespace std;
int x, y, z, a;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin >> x >> y >> z >> a;
// x + y / 2 + z / 4 >= a
// 4x + 2y + z >= 4a
if (4 * x + 2 * y + z >= 4 * a)
cout << "Yes\n";
else
cout << "No\n";
return 0;
}
B. 第 n 个质数
当题目给你一个不可能完成的任务时,注意有没有奇怪的数据规模约定。
- 子任务 1:暴力枚举即可。
- 子任务 2:显然没法在规定的时间空间限制下算出来,那么可以本地用暴力程序跑出来第
个质数是 。直接暴力跑的程序在我的电脑上花了不到 分钟跑出来了这个结果,如果你会筛法会更快(欧拉筛就更更快了)。然后直接输出这个结果就好。这个做法我们一般叫“打表”或者广义的“离线处理”。 - 子任务 3:既然最多只在子任务 2 的基础上往后数
个数,直接往后暴力枚举就好了(如果你用函数判断质数,下面的代码会更简洁)。当然你也可以继续往后打表,打出来这 101 个数。
#include <bits/stdc++.h>
using namespace std;
const int P1 = 2;
const int P83 = 640663963;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int n, start;
cin >> n;
if (n > 100)
{
start = P83;
// 把 33333333 对应到 1
n = n - 33'333'332;
}
else
start = P1;
for (int i = 1; i <= n - 1; i++)
{
// 变成下一个质数
start++;
while (1)
{
// 检查是否为质数
bool flag = true;
for (int j = 2; j * j <= start; j++)
if (start % j == 0)
{
flag = false;
break;
}
// 是质数就停,否则变成下一个数
if (flag)
break;
else
start++;
}
}
cout << start;
return 0;
}
C. 连续打卡与累计打卡
简单场的第二题已经这么难了,后两题我自然出的就简单了。
- 子任务 1:输出
即可。 - 子任务 2:根据
输出 或者 即可。 - 子任务 3:按题意模拟计数即可。
#include <bits/stdc++.h>
using namespace std;
int n;
string s;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
cin >> s;
int now, all;
now = all = 0;
for (int i = 0; i < s.size(); i++)
{
if (s[i] == 'o')
now++;
else
break;
}
for (int i = 0; i < s.size(); i++)
if (s[i] == 'o')
all++;
cout << now << " " << all;
return 0;
}
D. 冒泡排序步骤
有同学可能会问这道题有什么意义,实际上有下面几个意义:
凑数- 教大家怎么通过中间加输出语句,观察程序的运行流程,进而调试代码。
- 初赛阅读程序训练。
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1000;
int n;
int a[MAXN + 5];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
for (int i = 1; i <= n; i++)
cin >> a[i];
bool flag = true;
while (flag)
{
flag = false;
for (int i = 1; i <= n - 1; i++)
{
cout << "cmp,a[" << i << "],a[" << i + 1 << "]\n";
if (a[i] > a[i + 1])
{
cout << "swp,a[" << i << "],a[" << i + 1 << "]\n";
swap(a[i], a[i + 1]);
flag = true;
}
}
}
/*
for (int i = 1; i <= n; i++)
cout << a[i] << " ";
*/
return 0;
}