Contest2331 - 2022年“5校联盟”蓝桥杯软件大赛训练赛1 - BUCTOJ
E
题目
解释
- 用到埃氏筛选法对1~1e6+10的数字进行了预处理
代码段
#include<iostream>
using namespace std;
#define ll long long
const int N = 1e7;
int p[N + 1];
void getprime()
{
p[1] = 1;
for (int i = 2; i <= N; i++)
{
if (!p[i])
{
for (int j = 2 * i; j <= N; j += i)
p[j] = 1;
}
}
}
int main()
{
getprime();
int num; cin >> num;
for (int i = 2; i < num; i++)
{
if (!p[i])printf("%d\n", i);
}
}
J
题目
解释
- 使用两个栈前向栈和后向栈来存放当前页面的上一个页面和下一个页面的内容
代码段
#include<iostream>
#include<stack>
#include<string>
using namespace std;
int main()
{
stack<string>a;
stack<string>b;
string s;
string c = "***###.acm.org/";
while (cin >> s && s != "QUIT")
{
if (s == "VISIT")
{
b.push(c);
while (!a.empty())
a.pop();
cin >> c;
cout << c << endl;
}
else if (s == "FORWARD")
{
if (!a.empty())
{
b.push(c);
c = a.top();
cout << c << endl;
a.pop();
}
else
{
cout << "Ignored" << endl;
}
}
else
{
if (!b.empty())
{
a.push(c);
c = b.top();
cout << c << endl;
b.pop();
}
else
{
cout << "Ignored" << endl;
}
}
}
}
L
题目
某部队进行新兵队列训练,将新兵从一开始按顺序依次编号,并排成一行横队,训练的规则如下:从头开始一至二报数,凡报到二的出列,剩下的向小序号方向靠拢,再从头开始进行一至三报数,凡报到三的出列,剩下的向小序号方向靠拢,继续从头开始进行一至二报数。。。,以后从头开始轮流进行一至二报数、一至三报数直到剩下的人数不超过三人为止。
解释
- 对于报数的次数进行奇偶分析
- 奇数为踢出报2的,偶数为踢出报2,3的
- 注意到奇数次时队列中的人数如果为奇数时,末尾会有一个报2没有被循环踢出需要特判
- 偶数次时队列人数如果不是正好为3的倍数时,末尾会有一个报2一个报3的需要特判
代码段
#include<iostream>
#include<queue>
using namespace std;
int main()
{
int t,n;
cin >> t;
while (t--)
{
queue<int>q;
cin >> n;
for (int i = 1; i <= n; i++)
q.push(i);
int p = 1, x, k;
while (q.size() > 3)
{
x = q.size();
if (p & 1)
{
for (int i = 0; i < x / 2; i++)
{
k=q.front();
q.push(k);
q.pop();
q.pop();
}
if (x & 1)
{
k = q.front();
q.push(k);
q.pop();
}//如果一开始有奇数个元素,则将最后一个没有排除的抛弃
}
else
{
for (int i = 0; i < x / 3; i++)
{
k = q.front(); q.push(k);
q.pop();
k = q.front(); q.push(k);
q.pop(); q.pop();
}
while (x % 3 != 0)
{
--x;
k = q.front();
q.push(k);
q.pop();
}
}
++p;
}
while (!q.empty())
{
cout << q.front() << ' ';
q.pop();
}
cout << endl;
}
}