550A - Two Substrings - CodeForces Solution


brute force dp greedy implementation strings *1500

Please click on ads to support us..

Python Code:

import sys,os,math,cmath,timeit,functools,operator,bisect
from sys import stdin,stdout,setrecursionlimit
from io import BytesIO, IOBase
from collections import defaultdict as dd , Counter
from math import factorial , gcd
from queue import PriorityQueue
from heapq import merge, heapify, heappop, heappush
try :
    from functools import cache , lru_cache
    from sortedcontainers import *
except :
    pass 

ONLINE_JUDGE = __debug__

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        import os
        self.os = os
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
        self.BUFSIZE = 8192

    def read(self):
        while True:
            a = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
            if not a:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(a), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            a = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE))
            self.newlines = a.count(b"\n") + (not a)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(a), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            self.os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


stdin, stdout = IOWrapper(stdin), IOWrapper(stdout)

input = lambda: stdin.readline().rstrip("\r\n")

start = timeit.default_timer()

primes = []
mod=10**9+7
MOD=998244353


def seive(n):
    a = []
    prime = [True for i in range(n+1)] 
    p = 2
    while (p * p <= n): 
        if (prime[p] == True): 
            for i in range(p ** 2,n + 1, p): 
                prime[i] = False
        p = p + 1
    for p in range(2,n + 1): 
        if prime[p]: 
            primes.append(p)

def lower_bound(arr, n, k):
    start = 0
    end = n-1
    while start <= end:
        mid = (start+end)//2
        if arr[mid] == k:
            return mid
        elif arr[mid] > k:
            if mid > 0:
                if arr[mid-1] < k:
                    return (mid-1)
            else:
                return -1
        else:
            if mid < (n-1):
                if arr[mid+1] > k:
                    return mid
            else:
                return mid

def upper_bound(arr, n, k):
    start = 0
    end = n-1
    while start <= end:
        mid = (start+end)//2
        if arr[mid] == k:
            return mid
        elif arr[mid] > k:
            if mid > 0:
                if arr[mid-1] < k:
                    return (mid)
            else:
                return mid
        else:
            if mid < (n-1):
                if arr[mid+1] > k:
                    return (mid+1)
            else:
                return -1

def is_sorted(arr):
    return all(arr[i]<=arr[i+1] for i in range(len(arr)-1))

def invmod(n):
    return pow(n,mod-2,mod)

def binary_search(a,x,lo=0,hi=None):
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        midval = a[mid]
        if midval < x:
            lo = mid+1
        elif midval > x: 
            hi = mid
        else:
            return mid
    return -1

def ceil(a:int,b:int)->int :
    return (a+b-1)//b

def yn(x):
    if x :
        print("YES")
    else :
        print("NO")

def nCr(n,r):
    return factorial(n)//(factorial(r)*factorial(n-r))


def solve():
    s=strin()
    if len(s) <= 3 :
        yn(0)
        return
    mp = [[],[]]
    for i,c in enumerate(s) :
        if i+1<len(s) and s[i]=='A' and s[i+1]=='B' :
            mp[0].append(i)
        if i+1<len(s) and s[i]=='B' and s[i+1]=='A' :
            mp[1].append(i)
    mp[0].sort() ; mp[1].sort()
    if not mp[0] or not mp[1] :
        yn(0)
        return
        for x in mp[0] :
        if bisect.bisect_right(mp[1],x+1)!=len(mp[1]):
            yn(1)
            return
    for x in mp[1] :
        if bisect.bisect_right(mp[0],x+1)!=len(mp[0]):
            yn(1)
            return
    yn(0)

def main():
    tc=1
        for _ in range(tc):
        solve()
    stop = timeit.default_timer()
    if not ONLINE_JUDGE :
        print("Time Elapsed :" , str(stop-start) , "seconds")


def lst()->list :
    return list(map(int,input().split()))

def rowinp() :
    return map(int,input().split())

def strin()->str :
    return input()

def chlst()->list :
    return [x for x in input()]

def sint()->int :
    return int(input())


main()

C++ Code:

#include <iostream>
#include <algorithm>

using namespace std;

string s;

bool check(const string& a, const string& b) {
    bool a_happened = false;
    string ans;
    for(int i = 0; i < s.length() - 1; i++) {
        string temp;
        temp += s[i];
        temp += s[i + 1];
        if(temp == a && !a_happened) {
            a_happened = true;
            i++;
        } else if(temp == b && a_happened) {
            return true;
        }
    }
    return false;
}

int main() {
    cin >> s;
    cout << (check("AB", "BA") || check("BA", "AB") ? "YES\n" : "NO\n");
}


Comments

Submit
1 Comments
  • 2/2/2024 19:48 - Africa/Cairo

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string s;
    cin >> s;
    int found1 = s.find("AB");
    int found2 = s.find("BA");
    if (found1 != -1 && found2 != -1 && (found2 - found1) != 1)
    {
        cout << "YES";
    }
    else
        cout << "NO";
    return 0;
}


More Questions

3C - Tic-tac-toe
1669F - Eating Candies
1323B - Count Subrectangles
991C - Candies
1463A - Dungeon
1671D - Insert a Progression
1671A - String Building
1671B - Consecutive Points Segment
1671C - Dolce Vita
1669G - Fall Down
4D - Mysterious Present
1316B - String Modification
1204A - BowWow and the Timetable
508B - Anton and currency you all know
1672A - Log Chopping
300A - Array
48D - Permutations
677C - Vanya and Label
1583B - Omkar and Heavenly Tree
1703C - Cypher
1511C - Yet Another Card Deck
1698A - XOR Mixup
1702E - Split Into Two Sets
1703B - ICPC Balloons
1702F - Equate Multisets
1700A - Optimal Path
665C - Simple Strings
1708A - Difference Operations
1703E - Mirror Grid
1042A - Benches