题解:P17036 [NWERC 2020] 键盘故障 / Keyboardd

· · 题解

P17036 [NWERC 2020] 键盘故障 / Keyboardd

题意简述

给定两个字符串 s 和 t,s 表示 Joanna 实际按键输入的文本,t 表示屏幕上显示的文本。已知 t 是将 s 中所有属于“粘滞按键”的字符(可能是小写字母或空格)在每一次出现时都重复一次(即按一次输出两个)后得到的结果。保证至少有一个粘滞按键,且 s \ne t。要求输出所有一定是粘滞按键的字符,顺序任意。

解法

问题分析

由于每个粘滞按键在输入时,其每次出现都会导致输出两个相同字符,因此对于任意字符 c:

因此我们只需分别统计 s 和 t 中每个字符(包括空格)的出现次数,然后找出所有满足 \text{cnt}_t[c] = 2 \times \text{cnt}_s[c](其实满足\text{cnt}_t[c] > \text{cnt}_s[c] 即可)的字符即可。由于数据保证合法,所有粘滞按键一定满足此条件,且不会有其他字符满足。

复杂度分析

统计次数需要遍历两个字符串,时间复杂度 O(|s| + |t|),空间复杂度 O(1)。

code

#include <bits/stdc++.h>
#define N 1010
using namespace std;
typedef long long LL;
//十年OI一场空,不开long long见祖宗
string s , t;
map<char , int> ms , mt;
set<char> ans;
int main(){
    //freopen(".in" , "r" , stdin);
    //freopen(".out" , "w" , stdout);
    getline(cin , s);
    getline(cin , t);
    for(int i = 0 ; i < s.size() ; ++i)
        ms[s[i]] += 1;
    for(int i = 0 ; i < t.size() ; ++i)
        mt[t[i]] += 1;
    for(auto i : ms){
        if(i.second < mt[i.first])
            ans.insert(i.first);
    }
    for(auto i : ans)
        printf("%c" , i);
    return 0;
}