题解:P9239 [蓝桥杯 2023 省 B] 填空问题
试题 A:日期统计
:::info[题意简述]
给定一个长度为
- 子序列的长度为
8 ; - 如果把子序列的前
4 位当作年份y ,第5\sim6 位当作月份m ,最后2 位当作日期d ,那么y=2023 并且年份y 、月份m 、日期d 合法。
求出所有子序列组成的日期去重后的数量。
:::
:::warning[关于子序列]
- 子序列是指在原数组中筛选部分数字(筛选出来的序列不一定要在原数组中连续)。
- 子串是指在原数组中筛选部分数字(筛选出来的序列必须要在原数组中连续)。
:::
思路
数据较小,直接枚举子序列即可。一些优化:
- 枚举前
4 个数时如果当前数不是2 、0 、2 、3 时显然不可能作为答案(违反题目中y=2023 的要求)。 - 枚举后
4 个数时也要排除一些显然不可能的数字(如第5 个数是2 及以上的数字)。
为了方便去重,先把所有子序列得出的数字存入一个 set 里,最后输出这个集合的大小即可。
代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
string str = "5 6 8 6 9 1 6 1 2 4 9 1 9 8 2 3 6 4 7 7 5 9 5 0 3 8 7 5 8 1 5 8 6 1 8 3 0 3 7 9 2 7 0 5 8 8 5 7 0 9 9 1 9 4 4 6 8 6 3 3 8 5 1 6 3 4 6 7 0 7 8 2 7 6 8 9 5 6 5 6 1 4 0 1 0 0 9 4 8 0 9 1 2 8 5 0 2 5 3 3";
int a[100];
set<ll> st;
void solve()
{
for (ll i = 0; i < 100; i++) // 把题目给出的数组从字符串 str 存入数组 a
{
a[i] = str[i * 2] - '0';
}
// iX 表示子序列第 X 个数的位置(下标从 0 开始标号)
for (ll i1 = 0; i1 < 93; i1++)
{
if (a[i1] != 2) // 第一个数必须是 2
{
continue;
}
for (ll i2 = i1 + 1; i2 < 94; i2++)
{
if (a[i2] != 0) // 第二个数必须是 0
{
continue;
}
for (ll i3 = i2 + 1; i3 < 95; i3++)
{
if (a[i3] != 2) // 第三个数必须是 2
{
continue;
}
for (ll i4 = i3 + 1; i4 < 96; i4++)
{
if (a[i4] != 3) // 第四个数必须是 3
{
continue;
}
for (ll i5 = i4 + 1; i5 < 97; i5++)
{
if (a[i5] > 1) // 月份的十位只能是 0 或 1
{
continue;
}
for (ll i6 = i5 + 1; i6 < 98; i6++)
{
if (!a[i5] && !a[i6] || a[i5] && a[i6] > 2) // 当月份的十位是 0 时个位不能是 0,否则十位是 2,个位只能是 0 或 1
{
continue;
}
ll mon = a[i5] * 10 + a[i6]; // 把月份存储在一个变量方便后续计算
for (ll i7 = i6 + 1; i7 < 99; i7++)
{
if (a[i7] > 3 || mon == 2 && a[i7] == 3) // 二月份天数的十位不能超过 2,其他月份天数的十位不能超过 3
{
continue;
}
for (ll i8 = i7 + 1; i8 < 100; i8++)
{
ll day = a[i7] * 10 + a[i8];
if (!day || day > 31 || mon == 2 && day > 28 || (mon == 4 || mon == 6 || mon == 9 || mon == 11) && day > 30) // 2023 是平年所以二月只有 28 天
{
continue;
}
st.insert(mon * 100 + day);
}
}
}
}
}
}
}
}
cout << st.size();
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
ll t = 1;
// cin >> t;
while (t--)
{
solve();
}
return 0;
}
输出
试题 B:\texttt{01} 串的熵
:::info[问题简述]
对于一个长度为
其中
:::
思路
为方便表述令
设要求的串中
则
:::info[关于上述公式中出现的艾弗森括号]
- 当
p 为假时:[p]=0
:::
此时,再枚举
代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll n = 23333333;
const double shang = 11625907.5798;
ll ans;
double anss;
void solve()
{
for (ll n0 = 0; n0 <= n; n0++)
{
ll n1 = n - n0;
double curs = -(n0 * n0 * log2(n0 * 1. / n) / n + n1 * n1 * log2(n1 * 1. / n) / n);
if (abs(curs - shang) < abs(anss - shang))
{
ans = n0;
anss = curs;
}
}
cout << ans;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
ll t = 1;
// cin >> t;
while (t--)
{
solve();
}
return 0;
}
答案为
AC 代码
#include<iostream>
using namespace std;
int main() {
string ans [] = {
"235",
"11027421",
};
char T;
cin >> T;
cout << ans[T - 'A'] << endl;
return 0;
}