题目内容
给定两个长度均为
n
n
n 的字符串
s
s
s 和
t
t
t ,字符集只包括数字字符和 '?'
。
现在要求将两个字符串中的所有 '?'
都变成数字字符。
问有多少种方案使得存在两个不同的下标 i , j i,j i,j ,有 s i > t i s_i>t_i si>ti 且 s j < t j s_j<t_j sj<tj ,答案对 1 0 9 + 7 10^9+7 109+7 取模。
数据范围
- 1 ≤ n ≤ 1 0 5 1\leq n\leq 10^5 1≤n≤105
题解
因为只考虑大于和小于这两种情况太多了,很难处理。
不妨考虑去除全大于等于,全小于等于的情况。
- 如果本身已经有 s i > t i s_i>t_i si>ti 的下标,那么就不可能存在全小于等于的情况,只需要拿所有的可能情况减去全大于等于的情况即可。
- 如果本身已经有 s i < t i s_i<t_i si<ti 的下标,那么就不可能存在全大于等于的情况,只需要拿所有的可能情况减去全小于等于的情况即可。
- 如果本身既有
s
i
>
t
i
s_i>t_i
si>ti 的下标,也有
s
j
<
t
j
s_j<t_j
sj<tj 的下标,那么所有的
'?'
都可以任选,即 10 10 10 种选择。 - 如果既没有 s i > t i s_i>t_i si>ti 的下标,也没有 s j < t j s_j<t_j sj<tj 的下标,那么就需要拿所有的可能情况减去全大于等于和全小于等于的情况,注意,这里两部分对于全等于的部分可能会重复,所以需要去重,类似容斥的思想。
时间复杂度: O ( n ) O(n) O(n)
代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MOD = 1e9 + 7;
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
string s, t;
cin >> s >> t;
ll all = 1;
ll same = 1;
bool lt = false;
bool gt = false;
for (int i = 0; i < n; ++i) {
if (s[i] == '?') all = all * 10 % MOD;
if (t[i] == '?') all = all * 10 % MOD;
if (s[i] == '?' && t[i] == '?') same = same * 10 % MOD;
if (s[i] != '?' && t[i] != '?') {
if (s[i] > t[i]) gt = true;
else if (s[i] < t[i]) lt = true;
}
}
if (lt && gt) {
cout << all << "\n";
return 0;
}
// ans1: leq
// ans2: geq
ll ans1 = 1, ans2 = 1;
for (int i = 0; i < n; ++i) {
if (s[i] == '?') {
if (t[i] == '?') {
ans1 = ans1 * 55 % MOD;
ans2 = ans2 * 55 % MOD;
} else {
ans1 = ans1 * (t[i] - '0' + 1) % MOD;
ans2 = ans2 * ('9' - t[i] + 1) % MOD;
}
} else if (t[i] == '?') {
ans1 = ans1 * ('9' - s[i] + 1) % MOD;
ans2 = ans2 * (s[i] - '0' + 1) % MOD;
}
}
if (!gt) {
all -= ans1;
}
if (!lt) {
all -= ans2;
}
if (!gt && !lt) {
all += same;
}
all = (all % MOD + MOD) % MOD;
cout << all << "\n";
return 0;
}