1898E - Sofia and Strings - CodeForces Solution


data structures greedy strings

Please click on ads to support us..

Python Code:

def solve():
    n, m = map(int,input().split())
            a = input()
    b = input()
    
    V = [[] for _ in range(26)]

    for i in range(26):
        V[i].clear()

    for i in range(n, 0, -1):
        V[ord(a[i - 1]) - ord('a')].append(i)

    for i in range(1, m + 1):
        u = ord(b[i - 1]) - ord('a')
        if not V[u]:
            print("NO")
            return

        now = V[u].pop()

        for v in range(u):
            while V[v] and V[v][-1] < now:
                V[v].pop()

    print("YES")

t = int(input())
for _ in range(t):
        solve()

C++ Code:

#include <bits/stdc++.h>
#define ll long long
#define inf 0x3f3f3f3f
#define pll pair<ll, ll>
using namespace std;
const int mod = 1e9 + 7;
const int N = 2e5 + 7;
ll n, m;

void Z()
{
    cin >> n >> m;
    string a,b;
    cin >> a >> b;
    set<int> s[26];
    for (int i = 0;i < n;i ++)
    {
        s[a[i] - 'a'].insert(i);
    }

    for (auto x:b)
    {
        if (!s[x - 'a'].size())
        {
            cout << "No" << "\n";
            return;
        }
        int pos = *s[x - 'a'].begin();
        s[x - 'a'].erase(*s[x - 'a'].begin());
        int len = x - 'a';
        for (int i = 0;i < len;i ++)
        {
            while (!s[i].empty() && *s[i].begin() < pos)
            {
                s[i].erase(*s[i].begin());
            }
        }

    }
    cout << "Yes" << "\n";
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int t = 1;
    cin >> t;
    while (t--)
    {
        Z();
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

One String No Trouble
Help Jarvis!
Lift queries
Goki and his breakup
Ali and Helping innocent people
Book of Potion making
Duration
Birthday Party
e-maze-in
Bricks Game
Char Sum
Two Strings
Anagrams
Prime Number
Lexical Sorting Reloaded
1514A - Perfectly Imperfect Array
580A- Kefa and First Steps
1472B- Fair Division
996A - Hit the Lottery
MSNSADM1 Football
MATCHES Playing with Matches
HRDSEQ Hard Sequence
DRCHEF Doctor Chef
559. Maximum Depth of N-ary Tree
821. Shortest Distance to a Character
1441. Build an Array With Stack Operations
1356. Sort Integers by The Number of 1 Bits
922. Sort Array By Parity II
344. Reverse String
1047. Remove All Adjacent Duplicates In String