【每日一题】补档 CF296 B. Yaroslav and Two Strings | 构造 | 中等

文章讨论了给定两个字符串s和t,如何在满足特定条件(存在大于和小于的字符对)下计算将?字符替换为数字字符的方案数,采用排除法和容斥原理优化算法,时间复杂度为O(n)

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目内容

原题链接

给定两个长度均为 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 1n105

题解

因为只考虑大于和小于这两种情况太多了,很难处理。

不妨考虑去除全大于等于,全小于等于的情况。

  • 如果本身已经有 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值