前言
整体评价
这相当于蓝桥云课 正式推出算法赛前的公测,主要面向的是大一新生。
比赛题还是以语法题为主,被戏称为"幼稚园杯",^_^。
不过这场好像稍微增加了一些难度。
链接:新生编程排位赛4
A. 魔法石制作
Q: 构造一个NxN的矩阵,其(i, j)项的值为i * j
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cout << (i * j) << " \n"[j == n];
}
}
return 0;
}
B. 小蓝的学堂
Q: x名学生,y把椅子,如果每个学生都有椅子坐,需要额外补充多少?
max(0, x - y)
有可能椅子多,学生少,这个时候,就不需要额外补充椅子了。
#include <iostream>
using namespace std;
int main()
{
int t;
cin >> t;
while (t-- > 0) {
int x, y;
cin >> x >> y;
cout << max(0, x - y) << endl;
}
return 0;
}
C. 小桥的糖果分配
Q: n颗糖,如果能平均分给3个人,就是完美结局,否则Bad End。
n % 3 == 0
#include <iostream>
using namespace std;
int main()
{
int t;
cin >> t;
while (t-- > 0) {
int n;
cin >> n;
if (n % 3 == 0) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
}
return 0;
}
D. 音乐会中的音谐度
Q: 在一个数组中,求一个因子,其是这个数组中被最多数整除的,如果有多个解,求最小的。
因为数据规模不大,所以这题,可以枚举1~1000的因子,来逐个求解
如果数组大,且数值的值域也很大,那就涉及数论中的因子拆解了。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> arr(n);
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int maxCnt = 0;
int res = 0;
// 枚举因子
for (int i = 2; i <= 1000; i++) {
int tmp = 0;
for (int v: arr) {
if (v % i == 0) {
tmp++;
}
}
if (tmp > maxCnt) {
maxCnt = tmp;
res = i;
}
}
cout << res << endl;
return 0;
}
E. 阿坤老师切割年糕
Q: 就是把n分成a+b, 且 a|b, 求一共有多少种方式
a+b=n
a % b == 0
其实可以换种思路,设a=x, 那b=tx
x(t+1) = n
这里,x>0, t>0
其实这边已经转化为n的分解因子问题,可以把它降为的时间复杂度
枚举x的值,若x|n, 则xy=n, y|n,其中x<=y
这样在x<y的情况下,必然会存在2个解,一个x=x,另一个x=y,这里有些绕。
如果x=y,则只存在一个解,需要特别注意
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
if (n == 1) {
cout << 0 << endl;
return;
}
// x * (a + 1) = n
int res = 1;
for (int i = 2; i <= n / i && 2 * i <= n; i++) {
if (n % i == 0) {
if (i * i == n) {
res++;
} else {
res += 2;
}
}
}
cout << res << endl;
return 0;
}