A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules:  every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes);  each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk;  all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?InputThe first line contains an integer tt (1≤t≤5001≤t≤500) — the number of test cases to solve.Each of the remaining tt lines contains integers aa, bb and cc (0≤a,b,c≤100≤a,b,c≤10) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.OutputFor each test case print a single integer — the maximum number of visitors Denis can feed.ExampleInputCopy71 2 10 0 09 1 72 2 32 3 23 2 24 4 4OutputCopy3045557NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors.

// CF template, version 3.0

#include <bits/stdc++.h>

using namespace std;

#define improvePerformance ios_base::sync_with_stdio(false); cin.tie(0)

#define getTest int t; cin >> t

#define eachTest for (int _var=0;_var<t;_var++)

#define get(name) int (name); cin >> (name)

#define out(o) cout << (o)

#define getList(cnt, name) vector<int> (name); for (int _=0;_<(cnt);_++) { get(a); (name).push_back(a); }

#define sortl(name) sort((name).begin(), (name).end())

#define rev(name) reverse((name).begin(), (name).end())

#define forto(name, var) for (int (var) = 0; (var) < (name); (var)++)

#define int long long int

int gcd(int a, int b) {

    if (a == b) return a;

    return gcd(max(a, b), max(a, b) % min(a, b));

}

/*

Segtree:

void build(vector<int> &tree, vector<int> &array, int i, int l, int r) {

    if (l == r) {

        tree[i] = array[l];

    } else {

        int middle = (l + r) / 2;

        build(tree, array, i * 2, l, middle);

        build(tree, array, i * 2 + 1, middle + 1, r);

        tree[i] = max(tree[i * 2], tree[i * 2 + 1]);

    }

}

void set_(vector<int> &tree, int v, int l, int r, int i, int x) {

    if (l == r) {

        tree[v] = x;

    } else {

        int middle = (l + r) / 2;

        if (i <= middle) {

            set_(tree, v * 2, l, middle, i, x);

        } else {

            set_(tree, v * 2 + 1, middle + 1, r, i, x);

        }

        tree[v] = max(tree[v * 2], tree[v * 2 + 1]);

    }

}

int query(vector<int> &tree, int v, int cl, int cr, int l, int r) {

    if (l == cl && r == cr) {

        return tree[v];

    }

    if (l > r) return 0;

    int middle = (cl + cr) / 2;

    return max(

        query(tree, v * 2, cl, middle, l, min(r, middle)),

        query(tree, v * 2 + 1, middle + 1, cr, max(l, middle + 1), r)

    );

}

vector<int> tree(4 * n);

build(tree, initial, 1, 0, n-1); // replace initial with name of array

set_(tree, 1, 0, n-1, a, b);

query(tree, 1, 0, n-1, a, b); // this returns an int

data structure can be changed

*/

signed main() {

    improvePerformance;

    getTest;

    vector<vector<vector<int>>> arrs = {{{0, 0, 1}}, {{0, 1, 1}, {0, 0, 1}}, {{0, 1, 1}}, {{0, 1, 0}, {0, 0, 1}}, {{0, 1, 0}}, {{0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{0, 1, 0}, {0, 1, 1}}, {{1, 1, 1}, {0, 0, 1}}, {{1, 1, 1}}, {{1, 1, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 1, 1}, {0, 1, 1}}, {{1, 1, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 1, 1}, {0, 1, 0}}, {{1, 1, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 1, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 1, 0}, {0, 0, 1}}, {{1, 1, 0}}, {{1, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 1, 0}, {0, 1, 1}}, {{1, 1, 0}, {0, 1, 0}, {0, 0, 1}}, {{1, 1, 0}, {0, 1, 0}}, {{1, 1, 0}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 1, 0}, {0, 1, 0}, {0, 1, 1}}, {{1, 1, 0}, {1, 1, 1}, {0, 0, 1}}, {{1, 1, 0}, {1, 1, 1}}, {{1, 1, 0}, {1, 1, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 1, 0}, {1, 1, 1}, {0, 1, 1}}, {{1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 1, 0}, {1, 1, 1}, {0, 1, 0}}, {{1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 1}, {0, 0, 1}}, {{1, 0, 1}}, {{1, 0, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {0, 1, 1}}, {{1, 0, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 1}, {0, 1, 0}}, {{1, 0, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 1}, {1, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 1}}, {{1, 0, 1}, {1, 1, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 1}, {0, 1, 1}}, {{1, 0, 1}, {1, 1, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 1}, {0, 1, 0}}, {{1, 0, 1}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 1}, {1, 1, 0}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 0}}, {{1, 0, 1}, {1, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 0}, {0, 1, 1}}, {{1, 0, 1}, {1, 1, 0}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 0}, {0, 1, 0}}, {{1, 0, 1}, {1, 1, 0}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 0}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 0}, {1, 1, 1}}, {{1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 1}}, {{1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}}, {{1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {0, 0, 1}}, {{1, 0, 0}}, {{1, 0, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {0, 1, 1}}, {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {0, 1, 0}}, {{1, 0, 0}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 1}}, {{1, 0, 0}, {1, 1, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 1}, {0, 1, 1}}, {{1, 0, 0}, {1, 1, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 1}, {0, 1, 0}}, {{1, 0, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 0}}, {{1, 0, 0}, {1, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 1, 0}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 0}, {0, 1, 0}}, {{1, 0, 0}, {1, 1, 0}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 0}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 1, 0}, {1, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 0}, {1, 1, 1}}, {{1, 0, 0}, {1, 1, 0}, {1, 1, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 0}, {1, 1, 1}, {0, 1, 1}}, {{1, 0, 0}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}}, {{1, 0, 0}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {0, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {0, 1, 0}}, {{1, 0, 0}, {1, 0, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 1}, {0, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 1}, {0, 1, 0}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {0, 1, 0}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {0, 1, 0}, {0, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}, {0, 0, 1}}, {{1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1}, {0, 1, 0}, {0, 1, 1}}};

    eachTest {

        get(a);

        get(b);

        get(c);

        int maxi = 0;

        for (vector<vector<int>> cur: arrs) {

            int A=a;

            int B=b;

            int C=c;

            bool can = true;

            for (vector<int> arr: cur) {

                A-=arr[0];

                B-=arr[1];

                C-=arr[2];

                if (A<0||B<0||C<0) {

                    can = false;

                    break;

                }

            }

            if (can && cur.size() > maxi) maxi = cur.size();

        }

        out(maxi);

        out("\n");

    }

}


B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1≤|s|≤10001≤|s|≤1000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk  — the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm  — the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1≤a1<a2<⋯<am1≤a1<a2<⋯<am  — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest kk, you may print any of them.ExamplesInputCopy(()((
OutputCopy1
2
1 3
InputCopy)(
OutputCopy0
InputCopy(()())
OutputCopy1
4
1 2 5 6
NoteIn the first sample; the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '((('; and no more operations can be performed on it. Another valid answer is choosing indices 22 and 33, which results in the same final string.In the second sample, it is already impossible to perform any operations.

#include<bits/stdc++.h>

using namespace std;

int main()

{

    string s;cin>>s;

    int n = s.length();

    vector<int> a;

    vector<int> b;

    int close=0;

    for(int i=0;i<n;i++)

    {

        if(s[i]==')')

        {

            b.push_back(i);

            close++;

        }

        else

        a.push_back(i);

    }

    if(close==0)

    {

        cout<<0<<"\n";

        return 0;

    }

    int c=0;

    int ma=INT_MIN;

    for(int i=0;i<n;i++)

    {

        if(s[i]=='(')

        c++;

        else

        close--;

        if(s[i]=='(' && close>=c)

        ma  =max(ma,c);

    }

    if(ma==INT_MIN)

    {

        cout<<0<<"\n";

        return 0;

    }

    cout<<1<<"\n";

    cout<<ma*2<<"\n";

    reverse(b.begin(),b.end());

    vector<int> ans;

    for(int i=0;i<ma;i++)

    {

        ans.push_back(a[i]+1);

        ans.push_back(b[i]+1);

    }

    sort(ans.begin(),ans.end());

    for(int i=0;i<ans.size();i++)

    cout<<ans[i]<<" ";

    cout<<"\n";

}


A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3 ≤ A ≤ 1000).OutputOutput should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7/3InputCopy3OutputCopy2/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively.

#include <bits/stdc++.h>
//#include <string>
#include <algorithm>
//#include <vector>
//#include <set>
#include <numeric>
#define ll long long
using namespace std;
const int k = 1e5*2;
int arr[k];

int main() {

    int a;
    cin >> a;
    int sum = 0;
    for (int i = 2; i < a; i++) {
        int x = a;
        while (x) {
            sum += x % i;
            x /= i;
        }
    }
    int y = gcd(sum , a-2);
    cout<< sum/y << "/"<< (a-2)/y;
}


A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P":   "A" corresponds to an angry student  "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt — the number of groups of students (1≤t≤1001≤t≤100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1≤ki≤1001≤ki≤100) — the number of students in the group, followed by a string sisi, consisting of kiki letters "A" and "P", which describes the ii-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInputCopy1
4
PPAP
OutputCopy1
InputCopy3
12
APPAPPPAPPPP
3
AAP
3
PPA
OutputCopy4
1
0
NoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is:   after 11 minute — AAPAAPPAAPPP  after 22 minutes — AAAAAAPAAAPP  after 33 minutes — AAAAAAAAAAAP  after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry.

#include<bits/stdc++.h>
#define Mohamed ios_base::sync_with_stdio(false); cin.tie(NULL), cout.tie(NULL);
#define ll long long
using namespace std;
int main()
{
    Mohamed
    int t,sum=0;cin>>t;
    while(t--)
    {
        int x,c1=0,c2=0;cin>>x;
        bool bl=false;
        for (size_t i = 0; i < x; i++)
        {
            char c;cin>>c;
            if(c=='A'){bl=true; c1=0;}
            else if(bl){c1++;}
            c2=max(c1,c2)  ;
        }
        cout<<c2<<endl;
    }

}


A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.It is easy to prove that any way to transform nn to mm contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers nn and mm (1≤n≤m≤5⋅1081≤n≤m≤5⋅108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840
OutputCopy7
InputCopy42 42
OutputCopy0
InputCopy48 72
OutputCopy-1
NoteIn the first example; the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840.120→240→720→1440→4320→12960→25920→51840. The are 77 steps in total.In the second example, no moves are needed. Thus, the answer is 00.In the third example, it is impossible to transform 4848 to 7272.

#include <bits/stdc++.h>

using namespace std;

#define sz(s) (int)(s.size())

#define all(v) v.begin(),v.end()

#define clr(d, v) memset(d,v,sizeof(d))

#define ll long long

void file() {

    std::ios_base::sync_with_stdio(0);

    cin.tie(NULL);

    cout.tie(NULL);

}

int main() {

    file();

    int n, m;

    cin >> n >> m;

    int ans = INT_MAX;

    for (int i = 0; i <= 30; i++) {

        for (int j = 0; j <= 30; j++) {

            ll temp = n;

            for (int k = 0; k < i && temp < m; k++) {

                temp *= 2;

            }

            for (int k = 0; k < j && temp < m; k++) {

                temp *= 3;

            }

            if (temp == m) {

                ans = min(ans, i + j);

            }

        }

    }

    if (ans == INT_MAX)ans = -1;

    cout << ans;

}


B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4
6 10
010010
5 3
10101
1 0
0
2 0
01
OutputCopy3
0
1
-1
NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232.

#include<bits/stdc++.h>

using namespace std;

#define int long long

const int mod = 1e9 + 7;

//const int mod = 998244353;

#define PII pair<long long, long long>

#define x first

#define y second

#define pi 3.14159265359

int qpow(int a, int b)

{

    int res = 1;

    while (b != 0)

    {

        if (b & 1)res = res * a % mod;

        a = a * a % mod;

        b >>= 1;

    }

    return res;

}

int _qpow(int a, int b)

{

    int res = 1;

    while (b != 0)

    {

        if (b & 1)res = res * a;

        a = a * a;

        b >>= 1;

    }

    return res;

}

int inv(int a)

{

    return qpow(a, mod - 2);

}

int exgcd(int ai, int bi, int& xi, int& yi)

{

    if (bi == 0)

    {

        xi = 1, yi = 0;

        return ai;

    }

    int d = exgcd(bi, ai % bi, yi, xi);

    yi -= ai / bi * xi;

    return d;

}

int gcd(int a, int b)

{

    return b == 0 ? a : gcd(b, a % b);

}

/*----------------------------------------------------------------------*/

void solve()

{

    int n, x;

    cin >> n >> x;

    string s;

    cin >> s;

    int sum = 0;

    for (char c : s)

    {

        if (c == '0')sum++;

        else sum--;

    }

    int curr = 0;

    set<int> ss;

    int cnt = 0;

    if (curr == x && sum == 0)

    {

        cout << "-1\n";

        return;

    }

    if (sum != 0 && x % sum == 0 && x / sum >= 0)ss.insert(x / sum * n);

    for (int i = 0; i < n; i++)

    {

        char c = s[i];

        if (c == '0')curr++;

        else curr--;

        if (curr == x && sum == 0)

        {

            cout << "-1\n";

            return;

        }

        if (sum != 0 && (x - curr) % sum == 0 && (x - curr) / sum >= 0)

        {

            ss.insert((x - curr) / sum * n + i + 1);

        }

    }

    cout << ss.size() << "\n";

}

signed main()

{

    ios::sync_with_stdio(0);

    cin.tie(0);

    cout.tie(0);

    int tt = 1;

    cin >> tt;

    while (tt--)solve();

    return 0;

}


C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853
OutputCopy1
InputCopy2 993244853
OutputCopy6
InputCopy3 993244853
OutputCopy32
InputCopy2019 993244853
OutputCopy923958830
InputCopy2020 437122297
OutputCopy265955509
NoteFor sample input n=3n=3; let's consider all permutations of length 33:  [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66.  [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55.  [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55.  [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55.  [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55.  [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32.

#include<bits/stdc++.h>

typedef long long ll;

using namespace std;

//const ll mod = 1e9 + 7;

const ll mm = 2.5e5 + 10;

ll jc[mm];

int main() {

	std::ios::sync_with_stdio(false);

	std::cin.tie(0);

	std::cout.tie(0);

	int n;

	ll mod;

	cin>>n>>mod;

	jc[0]=1;

	for(int i=1;i<=n;i++){

		jc[i]=jc[i-1]*i%mod;

	}ll ans=0;

	for(int i=1;i<=n;i++){

		ans=(ans+jc[i]*jc[n-i+1]%mod*(n-i+1)%mod)%mod;

	}cout<<ans;

}


D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n)  — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n)  — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3
1 3 5
1 2
2 3
3 4
3 5
2 4
OutputCopy3
InputCopy5 4 2
2 4
1 2
2 3
3 4
4 5
OutputCopy3
NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33.   The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33.

// Don't Quit  O_O

#include <bits/stdc++.h>

using namespace std;

#define lli long long int

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;

template <class T>

using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

#define INF LLONG_MAX

#define pb push_back

#define ff first

#define ss second

#define mod 1000000007

// Will become Master  ^_^

vector<vector<lli>> adj(200005);

lli vis[200005];

int main()

{

    ios_base::sync_with_stdio(0);

    cin.tie(0);

    cout.tie(0);

    lli t = 1, n, i;

    // cin>>t;

    while (t--)

    {

        lli m, k;

        cin >> n >> m >> k;

        lli sp[k];

        set<lli> special;

        for (i = 0; i < k; i++)

        {

            cin >> sp[i];

            special.insert(sp[i]);

        }

        lli u[m], v[m];

        for (i = 0; i < m; i++)

        {

            cin >> u[i] >> v[i];

            adj[u[i]].pb(v[i]);

            adj[v[i]].pb(u[i]);

        }

        lli dist[n + 1];

        queue<pair<lli, lli>> q;

        q.push({1, 0});

        dist[1] = 0;

        vis[1] = 1;

        while ((int)q.size())

        {

            pair<lli, lli> p = q.front();

            q.pop();

            for (auto &x : adj[p.ff])

            {

                if (!vis[x])

                {

                    q.push({x, p.ss + 1});

                    dist[x] = p.ss + 1;

                    vis[x] = 1;

                }

            }

        }

        for (i = 1; i <= n; i++)

            vis[i] = 0;

        q.push({n, 0});

        lli distn[n + 2];

        distn[n] = 0;

        vis[n] = 1;

        while ((int)q.size())

        {

            pair<lli, lli> p = q.front();

            q.pop();

            for (auto &x : adj[p.ff])

            {

                if (!vis[x])

                {

                    q.push({x, p.ss + 1});

                    distn[x] = p.ss + 1;

                    vis[x] = 1;

                }

            }

        }

        bool flag = false;

        for (i = 0; i < m; i++)

        {

            if (special.count(u[i]) && special.count(v[i]))

                flag = true;

        }

        if (flag)

        {

            cout << dist[n];

            continue;

        }

        else

        {

            lli mx = 0, ans = 0;

            vector<pair<lli, lli>> v;

            for (i = 0; i < k; i++)

                v.pb({dist[sp[i]], distn[sp[i]]});

            sort(v.begin(), v.end());

            lli suff[k];

            suff[k - 1] = v[k - 1].ss;

            for (i = k - 2; i >= 0; i--)

                suff[i] = max(suff[i + 1], v[i + 1].ss);

            for (i = 0; i < k - 1; i++)

                ans = max(ans, v[i].ff + 1 + suff[i]);

            ans = min(ans, dist[n]);

            cout << ans;

        }

    }

}


F. Good Contesttime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn online contest will soon be held on ForceCoders; a large competitive programming platform. The authors have prepared nn problems; and since the platform is very popular, 998244351998244351 coder from all over the world is going to solve them.For each problem, the authors estimated the number of people who would solve it: for the ii-th problem, the number of accepted solutions will be between lili and riri, inclusive.The creator of ForceCoders uses different criteria to determine if the contest is good or bad. One of these criteria is the number of inversions in the problem order. An inversion is a pair of problems (x,y)(x,y) such that xx is located earlier in the contest (x<yx<y), but the number of accepted solutions for yy is strictly greater.Obviously, both the creator of ForceCoders and the authors of the contest want the contest to be good. Now they want to calculate the probability that there will be no inversions in the problem order, assuming that for each problem ii, any integral number of accepted solutions for it (between lili and riri) is equally probable, and all these numbers are independent.InputThe first line contains one integer nn (2≤n≤502≤n≤50) — the number of problems in the contest.Then nn lines follow, the ii-th line contains two integers lili and riri (0≤li≤ri≤9982443510≤li≤ri≤998244351) — the minimum and maximum number of accepted solutions for the ii-th problem, respectively.OutputThe probability that there will be no inversions in the contest can be expressed as an irreducible fraction xyxy, where yy is coprime with 998244353998244353. Print one integer — the value of xy−1xy−1, taken modulo 998244353998244353, where y−1y−1 is an integer such that yy−1≡1yy−1≡1 (mod(mod 998244353)998244353).ExamplesInputCopy3
1 2
1 2
1 2
OutputCopy499122177
InputCopy2
42 1337
13 420
OutputCopy578894053
InputCopy2
1 1
0 0
OutputCopy1
InputCopy2
1 1
1 1
OutputCopy1
NoteThe real answer in the first test is 1212.

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

typedef vector<int> vi;

typedef vector<long long> vll;

typedef pair<int, int> pii;

typedef pair<ll, ll> pll;

typedef pair<double, double> pdd;

const double PI = acos(-1);

const ll mod7 = 1e9 + 7;

const ll mod9 = 998244353;

const ll INF = 2 * 1024 * 1024 * 1023;

const char nl = '\n';

#define forn(i, n) for (int i = 0; i < int(n); i++)

#define all(v) v.begin(),v.end()

#pragma GCC optimize("O2")

#pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")

ll l, r, k, n, m, p, q, u, v, w, x, y, z;

string s, t;

vi d4x = {1, 0, -1, 0};

vi d4y = {0, 1, 0, -1};

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

// uniform_int_distribution<int>(1, 20)(rng)

////////////////////  LIBRARY CODE ////////////////////

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;

template<class T> using ordered_set = tree<T, null_type , less<T> , rb_tree_tag , tree_order_statistics_node_update>;

const ll MOD = mod9; //CHANGE MOD SETTING!!!

ll norm(ll x) { return (x + MOD) % MOD; }

template <class T>

T power(T a, ll b, T res = 1) {

  for (; b; b /= 2, (a *= a) %= MOD)

    if (b & 1) (res *= a) %= MOD;

  return res;

}

struct Mint {

  ll x;

  Mint(ll _x = 0) : x(norm(_x)) {}

  Mint operator-() const { return Mint(norm(MOD - x)); }

  Mint inv() const { return power(*this, MOD - 2); }

  Mint &operator*=(const Mint &rhs) { return x = x * rhs.x % MOD, *this; }

  Mint &operator+=(const Mint &rhs) { return x = norm(x + rhs.x), *this; }

  Mint &operator-=(const Mint &rhs) { return x = norm(x - rhs.x), *this; }

  Mint &operator/=(const Mint &rhs) { return *this *= rhs.inv(); }

  Mint &operator%=(const auto &_) { return *this; }

  friend Mint operator*(Mint lhs, const Mint &rhs) { return lhs *= rhs; }

  friend Mint operator+(Mint lhs, const Mint &rhs) { return lhs += rhs; }

  friend Mint operator-(Mint lhs, const Mint &rhs) { return lhs -= rhs; }

  friend Mint operator/(Mint lhs, const Mint &rhs) { return lhs /= rhs; }

  friend Mint operator%(Mint lhs, const auto &_) { return lhs; }

  friend istream &operator>>(istream &input, Mint &z) { return input >> z.x, input; }

};

ostream& operator<<(ostream& out, const Mint& x)

{

  return out << x.x;

}

///////////////////////////////////////////////////////

Mint calc(ll a, ll b) {

    Mint cur = 1;

    ll iter = b;

    forn(i, iter) {

        cur *= a;

        cur /= b;

        a--;

        b--;

    }

    return cur;

}

bool multiTest = 0;

void solve(int tt){

    cin >> n;

    set<int> startSet;

    startSet.insert(0);

    startSet.insert(998244352);

    vector<pii> segs(n);

    Mint divide = 1;

    forn(i, n) {

        cin >> segs[n-(i+1)].first >> segs[n-(i+1)].second;

    }

    forn(i, n) {

        startSet.insert(segs[i].first);

        startSet.insert(segs[i].second+1);

        divide *= segs[i].second + 1 - segs[i].first;

    }

    vi starts;

    for(int z : startSet) starts.push_back(z);

    m = starts.size();

    m--;

    vi sizes(m);

    int allowed[n][m];

    memset(allowed, 0, sizeof(allowed));

    forn(i, n) {

        u = segs[i].first;

        v = segs[i].second;

        forn(j, m) {

            l = starts[j];

            r = starts[j+1] - 1;

            sizes[j] = r + 1 - l;

            if(u <= l && v >= r) allowed[i][j] = 1;

        }

    }

    Mint dp[n+1][m+1];

    memset(dp, 0, sizeof(dp));

    dp[0][0] = 1;

    forn(i, n) {

        // forn(j, m+1) {

        //     cerr << i << ' ' << j << ' ' << dp[i][j] << nl;

        // }

        forn(j, m) {

            dp[i][j+1] += dp[i][j];

        }

        forn(j, m) {

            Mint cur = dp[i][j];

            for(int k = i; k < n; k++) {

                if(!allowed[k][j]) break;

                int sz = k + 1 - i;

                dp[k+1][j+1] += cur * calc(sz + sizes[j] - 1, sz);

            }

        }

    }

    Mint ans = 0;

    forn(i, m+1) ans += dp[n][i];

    cout << ans/divide << nl;

}

int main() {

    ios::sync_with_stdio(0);

    cin.tie(0);

    cout.tie(0);

    #ifdef yangster

    freopen("input.txt", "r", stdin);

    freopen("output.txt", "w", stdout);

    // #else

    // freopen("cowpatibility.in", "r", stdin);

    // freopen("cowpatibility.out", "w", stdout);

    #endif

    cout << fixed << setprecision(14);

    int t = 1;

    if (multiTest) cin >> t;

    for (int ii = 0; ii < t; ii++) {

        solve(ii + 1);

    }

}


C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab.  During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab.  During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab.  During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba.  During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8
bacabcab
OutputCopy4
InputCopy4
bcda
OutputCopy3
InputCopy6
abbbbb
OutputCopy5
NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows.  During the first move, remove the third character s3=s3= d, ss becomes bca.  During the second move, remove the second character s2=s2= c, ss becomes ba.  And during the third move, remove the first character s1=s1= b, ss becomes a.

// konakarthik12
// cpp20
#include <bits/stdc++.h>

using namespace std;

const int MOD = 1e9 + 7;
const int INF = (int)1e9;
using ll = long long;
using pii = pair<int, int>;
using pdd = pair<double, double>;
template <class T>
using pqueue = priority_queue<T>;
#define all(x) begin(x), end(x)
#define filla(x, v) memset(x, v, sizeof x);
template <class... Args>
void read(Args&... args) {
	(..., (cin >> args));
}
template <typename T>
void readN(int n, T c) {
	for (int i = 0; i < n; i++) {
		cin >> c[i];
	}
}

template <class... Args>
void print(Args... args) {
	string delim = "";
	(..., (cout << delim << args, delim = " "));
}

template <class... Args>
void println(Args... args) {
	print(args...);
	cout << "\n";
}
template <class T>
#define f first
#define s second

const auto rng = std::default_random_engine{};

template <int MOD = MOD>
struct Modular {
	int value;
	static const int MOD_value = MOD;

	Modular(long long v = 0) {
		value = v % MOD;
		if (value < 0) {
			value += MOD;
		}
	}
	Modular(long long a, long long b)
		: value(0) {
		*this += a;
		*this /= b;
	}

	Modular& operator+=(Modular const& b) {
		value += b.value;
		if (value >= MOD) {
			value -= MOD;
		}
		return *this;
	}
	Modular& operator-=(Modular const& b) {
		value -= b.value;
		if (value < 0) {
			value += MOD;
		}
		return *this;
	}
	Modular& operator*=(Modular const& b) {
		value = (long long)value * b.value % MOD;
		return *this;
	}

	friend Modular mexp(Modular a, long long e) {
		Modular res = 1;
		while (e) {
			if (e & 1) {
				res *= a;
			}
			a *= a;
			e >>= 1;
		}
		return res;
	}
	friend Modular inverse(Modular a) {
		return mexp(a, MOD - 2);
	}

	Modular& operator/=(Modular const& b) {
		return *this *= inverse(b);
	}
	friend Modular operator+(Modular a, Modular const b) {
		return a += b;
	}
	friend Modular operator-(Modular a, Modular const b) {
		return a -= b;
	}
	friend Modular operator-(Modular const a) {
		return 0 - a;
	}
	friend Modular operator*(Modular a, Modular const b) {
		return a *= b;
	}
	friend Modular operator/(Modular a, Modular const b) {
		return a /= b;
	}
	friend std::ostream& operator<<(std::ostream& os, Modular const& a) {
		return os << a.value;
	}

	friend bool operator==(Modular const& a, Modular const& b) {
		return a.value == b.value;
	}
	friend bool operator!=(Modular const& a, Modular const& b) {
		return a.value != b.value;
	}
};
template <typename T>
int sgn(T val) {
	return (T(0) < val) - (val < T(0));
}
#ifndef ONLINE_JUDGE
#define deb(...) logger(__LINE__, #__VA_ARGS__, __VA_ARGS__)

template <typename T>
struct iterable {
	enum { value = false };
};
template <typename T>
struct iterable<vector<T>> {
	enum { value = true };
};

template <typename T, typename = typename enable_if<iterable<T>::value>::type>
ostream& operator<<(ostream& out, T const& c) {
	out << '[';
	bool first = true;
	for (auto& elem : c) {
		if (!first) {
			out << ", ";
		}
		out << elem;
		first = false;
	}
	out << ']';
	return out;
};
template <typename T, typename V>
ostream& operator<<(ostream& out, pair<T, V> const& p) {
	out << '(' << p.first << ", " << p.second << ')';
	return out;
}
double to_rad(double degrees) {
	return degrees * (M_PI / 180);
}

template <typename... Args>
void logger(int line, string vars, Args&&... values) {
	cerr << "\e[30;1m" << line << ": ";
	cerr << vars << " = ";
	string delim = "";
	(..., (cerr << delim << values, delim = ", "));
	cerr << "\e[0m\n";
}
#else
#define deb(...) 0
#endif
void solve();

int main() {
	cin.tie(0)->sync_with_stdio(false);
	cout << fixed << setprecision(15);

	solve();
	cout.flush();
	return 0;
}

void solve() {
	int n;
	string s;
	read(n, s);
	s = '3' + s + '3';
	int ans = 0;
	for (char c = 'z'; c >= 'a'; c--) {
		int index = 1;
		while (index < (int) s.length() - 1) {
			if (s[index] == c && (s[index - 1] == c - 1 || s[index + 1] == c - 1)) {
        deb(s, index);
				s.erase(s.begin() + index);
				ans++;
        if (index > 1) index--;
			} else {
				index++;
			}
		}
	}

	print(ans);
}


B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer kk (0≤k≤1090≤k≤109) and replaces all missing elements in the array aa with kk.Let mm be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai−ai+1||ai−ai+1| for all 1≤i≤n−11≤i≤n−1) in the array aa after Dark replaces all missing elements with kk.Dark should choose an integer kk so that mm is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1041≤t≤104)  — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer nn (2≤n≤1052≤n≤105) — the size of the array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−1≤ai≤109−1≤ai≤109). If ai=−1ai=−1, then the ii-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of nn for all test cases does not exceed 4⋅1054⋅105.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of mm and an integer kk (0≤k≤1090≤k≤109) that makes the maximum absolute difference between adjacent elements in the array aa equal to mm.Make sure that after replacing all the missing elements with kk, the maximum absolute difference between adjacent elements becomes mm.If there is more than one possible kk, you can print any of them.ExampleInputCopy7
5
-1 10 -1 12 -1
5
-1 40 35 -1 35
6
-1 -1 9 -1 3 -1
2
-1 -1
2
0 -1
4
1 -1 3 -1
7
1 -1 7 5 2 -1 5
OutputCopy1 11
5 35
3 6
0 42
0 0
1 2
3 4
NoteIn the first test case after replacing all missing elements with 1111 the array becomes [11,10,11,12,11][11,10,11,12,11]. The absolute difference between any adjacent elements is 11. It is impossible to choose a value of kk, such that the absolute difference between any adjacent element will be ≤0≤0. So, the answer is 11.In the third test case after replacing all missing elements with 66 the array becomes [6,6,9,6,3,6][6,6,9,6,3,6].  |a1−a2|=|6−6|=0|a1−a2|=|6−6|=0;  |a2−a3|=|6−9|=3|a2−a3|=|6−9|=3;  |a3−a4|=|9−6|=3|a3−a4|=|9−6|=3;  |a4−a5|=|6−3|=3|a4−a5|=|6−3|=3;  |a5−a6|=|3−6|=3|a5−a6|=|3−6|=3. So, the maximum difference between any adjacent elements is 33.

#include <bits/stdc++.h>

#define ll long long

#define vi vector<int>

#define vl vector<ll>

#define vp vector<pair<int,int>>

#define ff first

#define ss second

#define forw(i,a,b) for(int i=a;i<b;i++)

#define backw(i,a,b) for(int i=a;i>=b;i--)

using namespace std;

const int M=998244353;

void solve(){

  int n;

  cin>>n;

  vi a(n);

  set<int> v;

  ll sum=0;

  forw(i,0,n){

    cin>>a[i];

  }

  int mx=INT_MIN,mn=INT_MAX;

  int ans=0;

  forw(i,0,n-1){

    if(a[i]==-1 && a[i+1]!=-1){

      mx=max(mx,a[i+1]);

      mn=min(mn,a[i+1]);

    }else if(a[i]!=-1 && a[i+1]==-1){

      mx=max(mx,a[i]);

      mn=min(mn,a[i]);

    }else{

      ans=max(ans,abs(a[i]-a[i+1]));

    }

  }

  int avg=(mx+mn)/2;

  if(a[0]==-1)a[0]=avg;

  forw(i,1,n){

    if(a[i]==-1) a[i]=avg;

    ans=max(ans,abs(a[i]-a[i-1]));

  }

  cout<<ans<<" "<<avg<<endl;

}

int main(){

  int t;

  cin>>t;

  while(t--){

    // cout<<"test "<<t<<endl;

    solve();

  }

}


F. Attack on Red Kingdomtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe Red Kingdom is attacked by the White King and the Black King!The Kingdom is guarded by nn castles, the ii-th castle is defended by aiai soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders. Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.Each attack must target a castle with at least one alive defender in it. There are three types of attacks:  a mixed attack decreases the number of defenders in the targeted castle by xx (or sets it to 00 if there are already less than xx defenders);  an infantry attack decreases the number of defenders in the targeted castle by yy (or sets it to 00 if there are already less than yy defenders);  a cavalry attack decreases the number of defenders in the targeted castle by zz (or sets it to 00 if there are already less than zz defenders). The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.Then, the test cases follow. Each test case is represented by two lines. The first line contains four integers nn, xx, yy and zz (1≤n≤3⋅1051≤n≤3⋅105, 1≤x,y,z≤51≤x,y,z≤5). The second line contains nn integers a1a1, a2a2, ..., anan (1≤ai≤10181≤ai≤1018).It is guaranteed that the sum of values of nn over all test cases in the input does not exceed 3⋅1053⋅105.OutputFor each test case, print the answer to it: the number of possible options for the first attack of the White King (or 00, if the Black King can launch the last attack no matter how the White King acts).ExamplesInputCopy3
2 1 3 4
7 6
1 1 2 3
1
1 1 2 2
3
OutputCopy2
3
0
InputCopy10
6 5 4 5
2 3 2 3 1 3
1 5 2 3
10
4 4 2 3
8 10 8 5
2 2 1 4
8 5
3 5 3 5
9 2 10
4 5 5 5
2 10 4 2
2 3 1 4
1 10
3 1 5 3
9 8 7
2 5 4 5
8 8
3 5 1 4
5 5 10
OutputCopy0
2
1
2
5
12
5
0
0
2

/*************************************

*    author: marvinthang             *

*    created: 10.01.2023 09:36:50    *

*************************************/

#include <bits/stdc++.h>

using namespace std;

#define                  fi  first

#define                  se  second

#define                left  ___left

#define               right  ___right

#define                TIME  (1.0 * clock() / CLOCKS_PER_SEC)

#define             MASK(i)  (1LL << (i))

#define             FULL(i)  (MASK(i) - 1)

#define           BIT(x, i)  ((x) >> (i) & 1)

#define  __builtin_popcount  __builtin_popcountll

#define              ALL(v)  (v).begin(), (v).end()

#define           REP(i, n)  for (int i = 0, _n = (n); i < _n; ++i)

#define        FOR(i, a, b)  for (int i = (a), _b = (b); i <= _b; ++i)

#define       FORD(i, b, a)  for (int i = (b), _a = (a); i >= _a; --i)

#define        scan_op(...)  istream & operator >> (istream &in, __VA_ARGS__ &u)

#define       print_op(...)  ostream & operator << (ostream &out, const __VA_ARGS__ &u)

#ifdef LOCAL

    #include "debug.h"

#else

    #define file(name) if (fopen(name".inp", "r")) { freopen(name".inp", "r", stdin); freopen(name".out", "w", stdout); }

    #define DB(...) 23

    #define db(...) 23

    #define debug(...) 23

#endif

template <class T> scan_op(vector <T>)  { for (size_t i = 0; i < u.size(); ++i) in >> u[i]; return in; }

template <class U, class V> scan_op(pair <U, V>)  { return in >> u.fi >> u.se; }

template <class U, class V> print_op(pair <U, V>)  { return out << '(' << u.first << ", " << u.second << ')'; }

template <class Con, class = decltype(begin(declval<Con>()))> typename enable_if <!is_same<Con, string>::value, ostream&>::type operator << (ostream &out, const Con &con) { out << '{'; for (__typeof(con.begin()) it = con.begin(); it != con.end(); ++it) out << (it == con.begin() ? "" : ", ") << *it; return out << '}'; }

template <size_t i, class T> ostream & print_tuple_utils(ostream &out, const T &tup) { if constexpr(i == tuple_size<T>::value) return out << ")";  else return print_tuple_utils<i + 1, T>(out << (i ? ", " : "(") << get<i>(tup), tup); }

template <class ...U> print_op(tuple<U...>) { return print_tuple_utils<0, tuple<U...>>(out, u); }

// end of template

const double PI = 3.1415926535897932384626433832795; // acos(-1.0); atan(-1.0);

const int dir[] = {1, 0, -1, 0, 1, 1, -1, -1, 1}; // {2, 1, -2, -1, -2, 1, 2, -1, 2};

void process(void) {

    int n, x, y, z; cin >> n >> x >> y >> z;

    vector <long long> a(n); cin >> a;

    vector <vector <int>> dp(37, vector<int>(3, 0));

    int ma = max({x, y, z});

    map <vector <vector <int>>, int> states;

    int cycle = -1, first = -1;

    FOR(i, 1, 36) {

        REP(j, 3) {

            vector <int> List;

            List.push_back(dp[max(0, i - x)][0]);

            if (j != 1) List.push_back(dp[max(0, i - y)][1]);

            if (j != 2) List.push_back(dp[max(0, i - z)][2]);

            sort(ALL(List));

            for (int x: List) if (dp[i][j] == x) ++dp[i][j];

        }

        if (i >= ma - 1) {

            vector <vector <int>> v(dp.begin() + i - ma + 1, dp.begin() + i + 1);

            if (!states.count(v)) states[v] = i;

            else {

                first = states[v];

                cycle = i - first;

                break;

            }

        }

    }

    auto get_dp = [&] (long long i, int j) {

        if (i < first) return dp[max(0LL, i)][j];

        return dp[(i - first) % cycle + first][j];

    };

    int xor_all = 0;

    for (long long a: a) xor_all ^= get_dp(a, 0);

    int res = 0;

    for (long long a: a) {

        int cur_xor = xor_all ^ get_dp(a, 0);

        if (!(cur_xor ^ get_dp(a - x, 0))) ++res;

        if (!(cur_xor ^ get_dp(a - y, 1))) ++res;

        if (!(cur_xor ^ get_dp(a - z, 2))) ++res;

    }

    cout << res << '\n';

}

int main(void) {

    ios_base::sync_with_stdio(false); cin.tie(nullptr); // cout.tie(nullptr);

    file("test");

    int t; cin >> t; while (t--)

        process();

    cerr << "Time elapsed: " << TIME << " s.\n";

    return (0^0);

}


G. Seollaltime limit per test3 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputIt is only a few days until Seollal (Korean Lunar New Year); and Jaehyun has invited his family to his garden. There are kids among the guests. To make the gathering more fun for the kids, Jaehyun is going to run a game of hide-and-seek.The garden can be represented by a n×mn×m grid of unit cells. Some (possibly zero) cells are blocked by rocks, and the remaining cells are free. Two cells are neighbors if they share an edge. Each cell has up to 4 neighbors: two in the horizontal direction and two in the vertical direction. Since the garden is represented as a grid, we can classify the cells in the garden as either "black" or "white". The top-left cell is black, and two cells which are neighbors must be different colors. Cell indices are 1-based, so the top-left corner of the garden is cell (1,1)(1,1).Jaehyun wants to turn his garden into a maze by placing some walls between two cells. Walls can only be placed between neighboring cells. If the wall is placed between two neighboring cells aa and bb, then the two cells aa and bb are not neighboring from that point. One can walk directly between two neighboring cells if and only if there is no wall directly between them. A maze must have the following property. For each pair of free cells in the maze, there must be exactly one simple path between them. A simple path between cells aa and bb is a sequence of free cells in which the first cell is aa, the last cell is bb, all cells are distinct, and any two consecutive cells are neighbors which are not directly blocked by a wall.At first, kids will gather in cell (1,1)(1,1), and start the hide-and-seek game. A kid can hide in a cell if and only if that cell is free, it is not (1,1)(1,1), and has exactly one free neighbor. Jaehyun planted roses in the black cells, so it's dangerous if the kids hide there. So Jaehyun wants to create a maze where the kids can only hide in white cells.You are given the map of the garden as input. Your task is to help Jaehyun create a maze.InputYour program will be judged in multiple test cases.The first line contains the number of test cases tt. (1≤t≤1001≤t≤100). Afterward, tt test cases with the described format will be given.The first line of a test contains two integers n,mn,m (2≤n,m≤202≤n,m≤20), the size of the grid.In the next nn line of a test contains a string of length mm, consisting of the following characters (without any whitespace):   O: A free cell.  X: A rock. It is guaranteed that the first cell (cell (1,1)(1,1)) is free, and every free cell is reachable from (1,1)(1,1). If t≥2t≥2 is satisfied, then the size of the grid will satisfy n≤10,m≤10n≤10,m≤10. In other words, if any grid with size n>10n>10 or m>10m>10 is given as an input, then it will be the only input on the test case (t=1t=1).OutputFor each test case, print the following:If there are no possible mazes, print a single line NO.Otherwise, print a single line YES, followed by a grid of size (2n−1)×(2m−1)(2n−1)×(2m−1) denoting the found maze. The rules for displaying the maze follows. All cells are indexed in 1-base.  For all 1≤i≤n,1≤j≤m1≤i≤n,1≤j≤m, if the cell (i,j)(i,j) is free cell, print 'O' in the cell (2i−1,2j−1)(2i−1,2j−1). Otherwise, print 'X' in the cell (2i−1,2j−1)(2i−1,2j−1).  For all 1≤i≤n,1≤j≤m−11≤i≤n,1≤j≤m−1, if the neighboring cell (i,j),(i,j+1)(i,j),(i,j+1) have wall blocking it, print ' ' in the cell (2i−1,2j)(2i−1,2j). Otherwise, print any printable character except spaces in the cell (2i−1,2j)(2i−1,2j). A printable character has an ASCII code in range [32,126][32,126]: This includes spaces and alphanumeric characters.  For all 1≤i≤n−1,1≤j≤m1≤i≤n−1,1≤j≤m, if the neighboring cell (i,j),(i+1,j)(i,j),(i+1,j) have wall blocking it, print ' ' in the cell (2i,2j−1)(2i,2j−1). Otherwise, print any printable character except spaces in the cell (2i,2j−1)(2i,2j−1)  For all 1≤i≤n−1,1≤j≤m−11≤i≤n−1,1≤j≤m−1, print any printable character in the cell (2i,2j)(2i,2j). Please, be careful about trailing newline characters or spaces. Each row of the grid should contain exactly 2m−12m−1 characters, and rows should be separated by a newline character. Trailing spaces must not be omitted in a row.ExampleInputCopy4
2 2
OO
OO
3 3
OOO
XOO
OOO
4 4
OOOX
XOOX
OOXO
OOOO
5 6
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OOOOOO
OutputCopyYES
OOO
  O
OOO
NO
YES
OOOOO X
  O O
X O O X
  O
OOO X O
O O   O
O OOOOO
YES
OOOOOOOOOOO
  O   O   O
OOO OOO OOO
O   O   O
OOO OOO OOO
  O   O   O
OOO OOO OOO
O   O   O
OOO OOO OOO

/*+Rainybunny+*/

#include <bits/stdc++.h>

#define rep(i, l, r) for (int i = l, rep##i = r; i <= rep##i; ++i)
#define per(i, r, l) for (int i = r, per##i = l; i >= per##i; --i)

typedef std::pair<int, int> PII;
#define fi first
#define se second

const int MAXN = 20, IINF = 0x3f3f3f3f;
const int MOVE[4][2] = { { -1, 0 }, { 0, -1 }, { 1, 0 }, { 0, 1 } };
int n, m, deg[MAXN * MAXN + 5];
char maz[MAXN + 5][MAXN + 5], str[MAXN * 2 + 5][MAXN * 2 + 5];

inline bool inside(const int i, const int j) {
    return 1 <= i && i <= n && 1 <= j && j <= m;
}

inline int id(const int i, const int j) {
    return (i - 1) * m + j;
}

struct DSU {
    int fa[MAXN * MAXN + 5], siz[MAXN * MAXN + 5];
    inline void init() { rep (i, 1, n * m) siz[fa[i] = i] = 1; }
    inline int find(const int x) {
        return x == fa[x] ? x : fa[x] = find(fa[x]);
    }
    inline bool unite(int x, int y) {
        if ((x = find(x)) == (y = find(y))) return false;
        if (siz[x] < siz[y]) x ^= y ^= x ^= y;
        return siz[fa[y] = x] += siz[y], true;
    }
};

namespace MI { // Matroid Intersection.

std::vector<PII> U;
std::vector<int> ans, dis, L, R, T;
std::queue<int> que;
DSU dsu;

inline void initInd() {
    dsu.init();
    rep (i, 1, n) rep (j, 1, m) deg[id(i, j)] = (i + j) & 1 ? -IINF : 0;
    deg[1] = -IINF;
    rep (i, 0, int(U.size()) - 1) if (ans[i]) {
        dsu.unite(U[i].fi, U[i].se), ++deg[U[i].fi], ++deg[U[i].se];
    }
}

inline void build() {
    initInd();
    L.clear(), R.clear();
    T.clear(), T.resize(U.size());
    dis.clear(), dis.resize(U.size(), IINF);
    rep (i, 0, int(U.size()) - 1) {
        if (ans[i]) L.push_back(i);
        else {
            R.push_back(i);
            if (deg[U[i].fi] < 2 && deg[U[i].se] < 2) T[i] = true;
            if (dsu.find(U[i].fi) != dsu.find(U[i].se)) {
                que.push(i), dis[i] = 0;
            }
        }
    }
}

inline std::vector<int> augment() {
    int fin = -1;
    std::vector<int> pre(U.size(), -1);
    while (!que.empty()) {
        int u = que.front(); que.pop();
        if (T[u]) { fin = u; break; }
        if (ans[u]) {
            dsu.init();
            for (int x: L) if (x != u) dsu.unite(U[x].fi, U[x].se);
            for (int v: R) {
                if (dis[v] == IINF && dsu.find(U[v].fi) != dsu.find(U[v].se)) {
                    dis[v] = dis[u] + 1, pre[v] = u, que.push(v);
                }
            }
        } else {
            for (int v: L) if (dis[v] == IINF) {
                ++deg[U[u].fi], ++deg[U[u].se];
                --deg[U[v].fi], --deg[U[v].se];
                if (deg[U[u].fi] <= 2 && deg[U[u].se] <= 2
                  && deg[U[v].fi] <= 2 && deg[U[v].se] <= 2) {
                    dis[v] = dis[u] + 1, pre[v] = u, que.push(v);
                }
                --deg[U[u].fi], --deg[U[u].se];
                ++deg[U[v].fi], ++deg[U[v].se];
            }
        }
    }
    if (!~fin) return {};
    while (!que.empty()) que.pop();
    std::vector<int> ret;
    ret.push_back(fin);
    while (~pre[fin]) ret.push_back(fin = pre[fin]);
    return ret;
}

inline void solve() {
    ans.clear(), ans.resize(U.size());
    while (true) {
        build();
        auto&& res(augment());
        if (res.empty()) break;
        for (int id: res) ans[id] ^= 1;
    }
}

} // namespace MI.

int main() {
    int T; scanf("%d", &T);
    while (T--) {
        scanf("%d %d", &n, &m);
        rep (i, 1, n) scanf("%s", maz[i] + 1);

        MI::U.clear();
        rep (i, 1, n) rep (j, 1, m) {
            if (~(i + j) & 1 && id(i, j) != 1 && maz[i][j] == 'O') {
                rep (k, 0, 3) {
                    int x = i + MOVE[k][0], y = j + MOVE[k][1];
                    if (inside(x, y) && maz[x][y] == 'O') {
                        MI::U.emplace_back(id(i, j), id(x, y));
                    }
                }
            }
        }

        MI::solve();
        MI::initInd();
        rep (i, 1, n) rep (j, 1, m) {
            if (~(i + j) & 1 && id(i, j) != 1
              && maz[i][j] == 'O' && deg[id(i, j)] != 2) {
                puts("NO"); goto FIN;
            }
        }
        rep (i, 1, 2 * n - 1) {
            rep (j, 1, 2 * m - 1) {
                str[i][j] = i & 1 && j & 1 ? maz[i + 1 >> 1][j + 1 >> 1] : ' ';
            }
            str[i][2 * m] = '\0';
        }

        if (maz[1][2] == 'O') {
            MI::U.emplace_back(id(1, 1), id(1, 2)), MI::ans.push_back(0);
        }
        if (maz[2][1] == 'O') {
            MI::U.emplace_back(id(1, 1), id(2, 1)), MI::ans.push_back(0);
        }
        rep (i, 0, int(MI::U.size()) - 1) {
            if (MI::dsu.find(MI::U[i].fi) != MI::dsu.find(MI::U[i].se)) {
                MI::dsu.unite(MI::U[i].fi, MI::U[i].se);
                MI::ans[i] = true;
            }
        }
        rep (i, 1, n) rep (j, 1, m) {
            if (maz[i][j] == 'O' && MI::dsu.find(id(i, j))
              != MI::dsu.find(id(1, 1))) {
                puts("NO"); goto FIN;
            }
        }

        rep (i, 0, int(MI::U.size()) - 1) if (MI::ans[i]) {
            int b = (MI::U[i].fi - 1) % m + 1, a = (MI::U[i].fi - b) / m + 1;
            int d = (MI::U[i].se - 1) % m + 1, c = (MI::U[i].se - d) / m + 1;
            str[a + c - 1][b + d - 1] = 'O';
        }
        puts("YES");
        rep (i, 1, 2 * n - 1) puts(str[i] + 1);
        FIN: ;
    }
    return 0;
}


B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1
OutputCopy1.000000000000
InputCopy2
OutputCopy1.500000000000
NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars.

#include <bits/stdc++.h>

using namespace std;

//-------------------------------------------------------

void fast(){ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);}

//-------------------------------------------------------

#define endl '\n'

#define pb push_back

#define all(x) (x).begin(),(x).end()

#define fi first

#define se second

#define sz(s) (int)(s.size())

#define inf 0x3f3f3f3f3f3f3f3fLL

#define watch(x) cout<<(#x)<<" = "<<x<<endl

#define clr(arr, val) memset(arr, val, sizeof(arr))

string ABC = "abcdefghijklmnopqrstuvwxyz";

//const int dr[] {-1, -1, 0, 1, 1, 1, 0, -1};

//const int dc[] {0, 1, 1, 1, 0, -1, -1, -1};

typedef long long ll;

const int OO = 0x3f3f3f3f;

///-------------- may need them -----------------//

//int n;cin>>n;vector<int>ar(n);for(int &i:ar){cin>>i;}

//int dx[] = {2,-2,2,-2,1,1,-1,-1}, dy[] = {1,1,-1,-1,2,-2,2,-2}; // knight moves

//int dx[] = {0,0,1,1,1,-1,-1,-1}, dy[] = {-1,1,-1,0,1,-1,0,1}; // 8 adjacent neighbours

//int dx[] = {0, 0, 1, -1}, dy[] = {-1, 1, 0, 0}; //4 adjacent neighbours

int const N = 2e5+5;

int const M = 2*N;

///---------------------------//

void main1()

{

  int n;cin>>n;

  double ans=(double)(1.0/n);

  if(n==1){

    cout<<"1.0000";

    return;

  }

  while(1){

    double fr=pow(n-1,-1);

//    watch(fr);

    ans+=fr;

    --n;

    if(n==1)

        break;

  }

  cout<<fixed<<ans<<setprecision(6);

}

int main()

{

    fast();

    int T=1;//cin>>T;

    //freopen("input.txt" ,"r" ,stdin);

    //freopen("output.txt" ,"w" ,stdout);

    while(T--) //cin.ignore();

    {

        main1();

        if(T)cout<<endl;

    }

    return 0;

}


E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6
-100 -200 -300 125 77 -4
OutputCopy9
InputCopy1000000000000 5
-1 0 0 0 0
OutputCopy4999999999996
InputCopy10 4
-3 -6 5 4
OutputCopy-1

#include <bits/stdc++.h>

#define nl  << "\n"

#define spc << " " <<

#define pt cout <<

using namespace std;

typedef long long ll;

#define int long long

#define pii pair<int, int>

int mod = 1e9 + 7;

int MAX = 1e9 + 1;

int MIN = -1e9;

double eps = 1e-7;

int dieTime(int req,vector<int> &arr,int n){

    for(int i=0;i<n;i++){

        req += arr[i];

        if(req <= 0)

            return i+1;

    }

    return n;

}

signed main(){

    ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);

    int h,n,netDam = 0,minDam = MAX; cin >> h >> n;

    vector<int> arr(n);

    for(int i=0;i<n;i++){

        cin >> arr[i];

        netDam += arr[i];

        minDam = min(minDam,netDam);

    }

    minDam = abs(minDam);

    if(h <= minDam)

        pt dieTime(h, arr, n) nl;

    else if(netDam >= 0)

        pt -1 nl;

    else{

        netDam = abs(netDam);

//        pt minDam spc h spc netDam nl;

        int num = ceil((double)(h-minDam)/netDam);

//        pt num nl;

        h = h-num*netDam;

        int ans = num*n;

//        pt ans nl;

        ans += dieTime(h, arr, n);

        pt ans nl;

    }

}


#include <bits/stdc++.h>
#include <algorithm>
#include <iostream>

using namespace std;
int main()
{
  int n,sum,ans,s;
  cin>>n;
  ans =0;
  for(int i=2 ; i<n ; i++)
  {
      s=n;
      sum=0;
      while(s)
      {
        sum+=(s%i);
        s/=i;
      }
      ans+=sum;
  }
  int g=__gcd(ans,n-2);
  cout<<ans/g<<"/"<<(n-2)/g;
}


#include <bits/stdc++.h>

using namespace std;

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;

#define ordered_set tree<int, null_type,less_equal<int>, rb_tree_tag,tree_order_statistics_node_update>

#define IOS ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);

int binexp(int a,int b,int m=1e9+7)

{

   if(b==0) return 1;

   int x=binexp(a,b/2,m)%m;

   if(b%2) x=((a%m)*(x*1LL*x)%m)%m;

   else x=(x*1LL*x)%m;

   return x%m;

}

void ram()

{

   int n;

   cin>>n;

   string s;

   cin>>s;

   for(char ch='z';ch>='b';ch--)

   {

      string t="";

      if(s.find(ch)==string :: npos) continue;

      for(int i=0;i<s.size();i++)

      {

         char ch1=(char)(ch-1);

         int j=i;

         int p=0,q=0;

         while(i<s.size() and (s[i]==ch or s[i]==ch1))

         {

            if(s[i]==ch) p=1;

            else q=1;

            i++;

         }

         if(p and q)

         {

            for(int k=j;k<i;k++) if(s[k]==ch) s[k]='@';

         }

      }

      for(auto it:s) if(it!='@') t+=it;

      s=t;

   }

   //cout<<s<<endl;

   cout<<n-s.size()<<endl;

}

int main()

{

   IOS

   int t=1;

   //cin>>t;

   while (t--) ram();

}


A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5
5 2 3
1 2 3
4 3 3
4 1 2
10 2 6
1 2 3 4 5 7
2 1 1
2
100 76 8
76 75 36 67 41 74 10 77
OutputCopy2
0
4
0
2
NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor.

#include <bits/stdc++.h>

using namespace std;

using ll = long long;

using ld = long double;

#define pb push_back

#define ff first

#define ss second

#define oo 100000000000000L

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

void solve(){

    int n,s,k,cur,ans1=oo,ans2=oo; cin >> n >> s >> k;

    map<int,int> mp;

    for(int i=0;i<k;++i) {

        int cur; cin >> cur;

        mp[cur]++;

    }

    cur=s;

    while(mp[cur]>0&&cur<=n){

        ++cur;

    }

    if(cur<=n) {

        ans1=cur-s;

    }

    cur=s-1;

    while(cur>0&&mp[cur]){

        --cur;

    }

    if(cur>0){

        ans2=s-cur;

    }

    cout << min(ans1,ans2);

}

int main(){

    ios::sync_with_stdio(false); cin.tie(0);

    int t; cin >> t;

    while(t--) {

        solve();

        cout << "\n";

    }

    return 0;

}


D. Around the Worldtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are planning 144144 trips around the world.You are given a simple weighted undirected connected graph with nn vertexes and mm edges with the following restriction: there isn't any simple cycle (i. e. a cycle which doesn't pass through any vertex more than once) of length greater than 33 which passes through the vertex 11. The cost of a path (not necessarily simple) in this graph is defined as the XOR of weights of all edges in that path with each edge being counted as many times as the path passes through it.But the trips with cost 00 aren't exciting. You may choose any subset of edges incident to the vertex 11 and remove them. How many are there such subsets, that, when removed, there is not any nontrivial cycle with the cost equal to 00 which passes through the vertex 11 in the resulting graph? A cycle is called nontrivial if it passes through some edge odd number of times. As the answer can be very big, output it modulo 109+7109+7.InputThe first line contains two integers nn and mm (1≤n,m≤1051≤n,m≤105) — the number of vertexes and edges in the graph. The ii-th of the next mm lines contains three integers aiai, bibi and wiwi (1≤ai,bi≤n,ai≠bi,0≤wi<321≤ai,bi≤n,ai≠bi,0≤wi<32) — the endpoints of the ii-th edge and its weight. It's guaranteed there aren't any multiple edges, the graph is connected and there isn't any simple cycle of length greater than 33 which passes through the vertex 11.OutputOutput the answer modulo 109+7109+7.ExamplesInputCopy6 8
1 2 0
2 3 1
2 4 3
2 6 2
3 4 8
3 5 4
5 4 5
5 6 6
OutputCopy2
InputCopy7 9
1 2 0
1 3 1
2 3 9
2 4 3
2 5 4
4 5 7
3 6 6
3 7 7
6 7 8
OutputCopy1
InputCopy4 4
1 2 27
1 3 1
1 4 1
3 4 0
OutputCopy6NoteThe pictures below represent the graphs from examples.  In the first example; there aren't any nontrivial cycles with cost 00, so we can either remove or keep the only edge incident to the vertex 11.  In the second example, if we don't remove the edge 1−21−2, then there is a cycle 1−2−4−5−2−11−2−4−5−2−1 with cost 00; also if we don't remove the edge 1−31−3, then there is a cycle 1−3−2−4−5−2−3−11−3−2−4−5−2−3−1 of cost 00. The only valid subset consists of both edges.  In the third example, all subsets are valid except for those two in which both edges 1−31−3 and 1−41−4 are kept.

// LUOGU_RID: 101124005
#include<bits/stdc++.h>

#define For(i,a,b) for(int i=(a);i<=(b);++i)

#define Rof(i,a,b) for(int i=(a);i>=(b);--i)

using namespace std;

const int Maxn=1e5,Maxk=374,Mod=1e9+7;

inline int read()

{

    int x=0,f=1;

    char ch=getchar();

    while(ch<'0' || ch>'9')

    {

        if(ch=='-') f=-1;

        ch=getchar();

    }

    while(ch>='0' && ch<='9')

    {

        x=x*10+ch-'0';

        ch=getchar();

    }

    return x*f;

}

struct Node{int frm,to,nxt,w;} Edge[Maxn*2+5];

int tot=1,Head[Maxn+5];

map<pair<int,int>,int> mp;

inline void Addedge(int x,int y,int z)

{

    Edge[++tot]=(Node){x,y,Head[x],z};

    Head[x]=tot,mp[make_pair(x,y)]=z;

}

int n,m,fa[Maxn+5],val[Maxn+5][5];

int num[Maxn+5][5],sum[Maxn+5],vis[Maxn+5];

int dfn[Maxn+5],chk[Maxn+5],cnt[Maxn+5],ID,cur;

int id[2][4][8][16][32],st[Maxk+5][5],tyw;

int g[Maxk+5][Maxk+5],f[2][Maxk+5];

vector<int> v,w[Maxn+5];

inline int Find(int x) {return fa[x]==x?x:fa[x]=Find(fa[x]);}

int hzh[5];

inline void add(int &x,int y) {x=(x+y)%Mod;}

inline void Reset(int *A)

{

    Rof(i,4,0) if(A[i]) For(j,i+1,4)

        if(A[j]&(1<<i)) A[j]^=A[i];

}

inline void dfs(int i)

{

    if(i>4)

    {

        id[hzh[0]][hzh[1]][hzh[2]][hzh[3]][hzh[4]]=++tyw;

        memcpy(st[tyw],hzh,sizeof(hzh)); return;

    }

    hzh[i]=0; dfs(i+1);

    For(j,1<<i,(1<<i+1)-1)

    {

        int flag=0; hzh[i]=j;

        For(k,0,i-1) if(hzh[k] && j&(1<<k)) {flag=1; break;}

        if(!flag) dfs(i+1);

    }

}

inline void Merge(int a,int b)

{

    For(i,0,4) hzh[i]=st[a][i];

    For(i,0,4) if(st[b][i])

    {

        int x=st[b][i];

        Rof(j,4,0) if(x&(1<<j))

        {

            if(!hzh[j]) {hzh[j]=x; break;}

            x^=hzh[j];

        }

        if(!x) {g[a][b]=-1; return;}

    }

    Reset(hzh);

    int idx=id[hzh[0]][hzh[1]][hzh[2]][hzh[3]][hzh[4]];

    if(!idx) g[a][b]=-1;

    else g[a][b]=idx;

}

inline void Build()

{

    dfs(0);

    For(i,1,tyw) For(j,1,tyw) Merge(i,j);

}

inline void Insert(int x,int y)

{

    Rof(i,4,0) if(y&(1<<i))

    {

        if(!val[x][i]) {val[x][i]=y; return;}

        y^=val[x][i];

    }

    if(!y) chk[x]=1;

}

inline void dfs(int x,int fa)

{

    dfn[x]=++cur;

    for(int i=Head[x];i;i=Edge[i].nxt)

    {

        int y=Edge[i].to,z=Edge[i].w;

        if(y==fa || y==1) continue;

        if(!dfn[y]) sum[y]=sum[x]^z,dfs(y,x);

        else if(dfn[y]<dfn[x]) Insert(ID,sum[x]^sum[y]^z);

    }

}

int main()

{

    n=read(),m=read();

    For(i,1,n) fa[i]=i;

    For(i,1,m)

    {

        int a=read(),b=read(),c=read();

        Addedge(a,b,c),Addedge(b,a,c);

        if(a!=1 && b!=1 && Find(a)!=Find(b)) fa[Find(a)]=Find(b);

    }

    For(i,2,n) if(Find(i)==i) v.push_back(ID=i),dfs(i,0);

    For(i,2,n) w[Find(i)].push_back(i);

    for(int i=Head[1];i;i=Edge[i].nxt) cnt[Find(Edge[i].to)]++;

    for(auto i:v) if(cnt[i]==2)

    {

        int a=0,b=0;

        for(auto j:w[i]) if(mp.find(make_pair(1,j))!=mp.end()) (!a?a:b)=j;

        int res=mp[make_pair(1,a)]^mp[make_pair(1,b)]^mp[make_pair(a,b)];

        memcpy(num[i],val[i],sizeof(val[i])),vis[i]=chk[i];

        Rof(j,4,0) if(res&(1<<j))

        {

            if(!num[i][j]) {num[i][j]=res; break;}

            res^=num[i][j];

        }

        if(!res) vis[i]=1;

    }

    for(auto i:v) Reset(val[i]),Reset(num[i]);

    Build();

    int o=0,p=1; f[0][1]=1;

    for(auto i:v)

    {

        o^=1,p^=1,memset(f[o],0,sizeof(f[o]));

        memcpy(f[o],f[p],sizeof(f[p]));

        if(cnt[i]==1 && !chk[i])

        {

            int idx=id[val[i][0]][val[i][1]][val[i][2]][val[i][3]][val[i][4]];

            For(j,1,tyw) if(f[p][j] && g[j][idx]>0) add(f[o][g[j][idx]],f[p][j]);

        }

        if(cnt[i]==2 && !chk[i])

        {

            int idx=id[val[i][0]][val[i][1]][val[i][2]][val[i][3]][val[i][4]];

            For(j,1,tyw) if(f[p][j] && g[j][idx]>0) add(f[o][g[j][idx]],f[p][j]*2%Mod);

        }

        if(cnt[i]==2 && !vis[i])

        {

            int idx=id[num[i][0]][num[i][1]][num[i][2]][num[i][3]][num[i][4]];

            For(j,1,tyw) if(f[p][j] && g[j][idx]>0) add(f[o][g[j][idx]],f[p][j]);

        }

    }

    int ans=0;

    For(i,1,tyw) add(ans,f[o][i]);

    printf("%d\n",ans);

    return 0;

}


B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions:  If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss;  If we write the strings t1,t2,…,tkt1,t2,…,tk in order, the resulting string will be equal to tt;  For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= "gamegame". Then the string t=t= "megamage" is a reducible anagram of ss, we may choose for example s1=s1= "game", s2=s2= "gam", s3=s3= "e" and t1=t1= "mega", t2=t2= "mag", t3=t3= "e":  On the other hand, we can prove that t=t= "memegaga" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105)  — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.ExamplesInputCopyaaaaa
3
1 1
2 4
5 5
OutputCopyYes
No
Yes
InputCopyaabbbbbbc
6
1 2
2 4
2 2
1 9
5 7
3 5
OutputCopyNo
Yes
Yes
Yes
No
No
NoteIn the first sample; in the first and third queries; the substring is "a"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand; in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= "a", s2=s2= "aa", t1=t1= "a", t2=t2= "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram.

#include "bits/stdc++.h"

#include<ext/pb_ds/assoc_container.hpp>

#include<ext/pb_ds/tree_policy.hpp>

#define ll long long

#define NFS ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)

#define all(x) (x).begin(), (x).end() //Forward traversal

#define ff first

#define ss second

#define nl "\n"

#define lb lower_bound

#define ub upper_bound

#define pb push_back

using namespace std;

using namespace __gnu_pbds;

template<class T>

using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update> ;

// find_by_order, order_of_key

#ifndef youknowwhoiam1

#define debug(x) cerr << #x<<" "; _print(x); cerr << endl;

#else

#define debug(x);

#endif

void _print(int t) {cerr << t;}

void _print(ll t) {cerr << t;}

void _print(double t) {cerr << t;}

void _print(string t) {cerr << t;}

void _print(char t) {cerr << t;}

template <class T, class V> void _print(pair <T, V> p);

template <class T> void _print(vector <T> v);

template <class T> void _print(set <T> v);

template <class T, class V> void _print(map <T, V> v);

template <class T> void _print(multiset <T> v);

template <class T, class V> void _print(pair <T, V> p) {cerr << "{"; _print(p.ff); cerr << ","; _print(p.ss); cerr << "}";}

template <class T> void _print(vector <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}

template <class T> void _print(set <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}

template <class T> void _print(multiset <T> v) {cerr << "[ "; for (T i : v) {_print(i); cerr << " ";} cerr << "]";}

template <class T, class V> void _print(map <T, V> v) {cerr << "[ "; for (auto i : v) {_print(i); cerr << " ";} cerr << "]";}

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

//-----------------------------------------------------------------------------------------------------------------------------//

const ll MOD = LLONG_MAX;

const ll inf = LLONG_MAX;

ll add(ll x, ll y) {x += y; while (x >= MOD) x -= MOD; while (x < 0) x += MOD; return x;}

ll sub(ll x, ll y) {return add(x, -y);}

ll mul(ll x, ll y) {return (x * 1ll * y) % MOD;}

ll binpow(ll x, ll y) {ll z = 1; while (y) {if (y & 1) z = mul(z, x); x = mul(x, x); y >>= 1;} return z;}

ll inv(ll i) {if (i == 1) return 1; return (MOD - ((MOD / i) * inv(MOD % i)) % MOD) % MOD;}

ll gcd(ll a, ll b) { if (b == 0) return a; return gcd(b, a % b);}

//-----------------------------------------------------------------------------------------------------------------------------//

/*

*/

void solve() {

	ll i, j;

	string s;

	cin >> s;

	ll n = s.length();

	vector<vector<ll>> dp(n + 1, vector<ll>(26));

	for (i = 0; i < n; i++) {

		for (j = 0; j < 26; j++) {

			dp[i + 1][j] = dp[i][j] + (s[i] == char(j + 97));

		}

	}

	ll q;

	cin >> q;

	for (i = 0; i < q; i++) {

		ll l, r;

		cin >> l >> r;

		if (r - l == 0) {cout << "Yes" << nl; continue;}

		ll id = s[r - 1] - 'a';

		if (s[l - 1] == s[r - 1]) {

			ll ctr = 0;

			for (j = 0; j < 26; j++) {

				if (dp[r][j] - dp[l - 1][j] > 0) {

					ctr++;

				}

			}

			if (ctr > 2) {cout << "Yes" << nl;}

			else {

				cout << "No" << nl;

			}

		} else {

			cout << "Yes" << nl;

		}

	}

}

int main() {

	NFS;

#ifndef youknowwhoiam1

	freopen("error.txt", "w", stderr);

#endif

	using namespace std::chrono;

	high_resolution_clock::time_point t1 = high_resolution_clock::now();

	ll tc = 1;

	// cin >> tc;

	while (tc--) {

		solve();

	}

	high_resolution_clock::time_point t2 = high_resolution_clock::now();

	duration<double> time_span = duration_cast<duration<double>>(t2 - t1);

	std::cerr << setprecision(10) << fixed;

	std::cerr << "Time: " << time_span.count() << " seconds.";

	std::cerr << std::endl;

	return 0;

}


A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤30001≤n≤3000)  — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4
4
1227
1
0
6
177013
24
222373204424185217171912
OutputCopy1227
-1
17703
2237344218521717191
NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit).

#include <iostream>

#include <iterator>

#include <algorithm>

#include <bits/stdc++.h>

using namespace std;

typedef long long int ll;

typedef long double ld;

typedef string s;

typedef vector<int> vi;

typedef vector<ll> vll;

typedef vector<ld> vld;

typedef vector<vector<ll>> vvll;

typedef vector<vector<ld>> vvld;

typedef vector<vector<vector<ll>>> vvvll;

typedef vector<string> vstr;

typedef vector<pair<ll, ll>> vpll;

typedef pair<ll, ll> pll;

#include <ext/pb_ds/assoc_container.hpp>

#include <ext/pb_ds/tree_policy.hpp>

using namespace __gnu_pbds;

#define ordered_set tree<ll, null_type, less<ll>, rb_tree_tag, tree_order_statistics_node_update>

#define fast  ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);

#define textfile    freopen("input.txt" , "r" , stdin); freopen("output.txt" , "w" , stdout);

#define pb push_back

#define nl "\n"

#define all(c) (c).begin(), (c).end()

#define iotam1 cout << -1 << nl

#define cty cout << "YES" << nl

#define ctn cout << "NO" << nl

#define lma LLONG_MAX

#define lmi LLONG_MIN

#define sz(v) (v).size()

#define prec(n) fixed << setprecision(n)

#define c(x) cout << (x)

#define csp(x) cout << (x) << " ";

#define c1(x) cout << (x) << nl;

#define c2(x, y) cout << (x) << " " << (y) << nl;

#define c3(x, y, z) cout << (x) << " " << (y) << " " << (z) << nl;

#define c4(a, b, c, d) cout << (a) << " " << (b) << " " << (c) << " " << (d) << nl;

#define c5(a, b, c, d, e) cout << (a) << " " << (b) << " " << (c) << " " << (d) << " " << (e) << nl;

#define c6(a, b, c, d, e, f) cout << (a) << " " << (b) << " " << (c) << " " << (d) << " " << (e) << " " << (f) << nl;

#define f(i, a, n) for (ll i = a; i < n; i++)

#define rf(i, n, a) for (ll i = n; i > a; i--)

#define fi first

#define se second

#define print(vec, a, b) for (ll i = a; i < b; i++) cout << vec[i] << " "; cout << nl;

#define input(vec, a, b)  for (ll i = a; i < b; i++) cin >> vec[i];

#define ms(a, val) memset(a, val, sizeof(a))

const ll mod = 1000000007;

const long double pi = 3.14159265358979323846264338327950288419716939937510582097494459230;

ll pct(ll x) { return __builtin_popcount(x); } // #of set bits

ll modI(ll a, ll m = mod)

{

    ll m0 = m, y = 0, x = 1;

    if (m == 1)

        return 0;

    while (a > 1)

    {

        ll q = a / m;

        ll t = m;

        m = a % m;

        a = t;

        t = y;

        y = x - q * y;

        x = t;

    }

    if (x < 0)

        x += m0;

    return x;

}

ll powm(ll a, ll b, ll m = mod)

{

    ll res = 1;

    while (b)

    {

        if (b & 1)

            res = (res * a) % m;

        a = (a * a) % m;

        b >>= 1;

    }

    return res;

}

ll __lcm(ll a, ll b) { return (a * b) / __gcd(a, b); }

ll __lcm(vector<ll> &arr) { ll res = arr[0]; for (ll i = 1; i < arr.size(); i++) res = __lcm(res, arr[i]); return res; }

ll __gcd(ll a, ll b) { if (b == 0) return a; return __gcd(b, a % b); }

ll __gcd(vector<ll> &arr) { ll res = arr[0]; for (ll i = 1; i < arr.size(); i++) res = __gcd(res, arr[i]); return res; }

ll __gcd(ll a, ll b, ll c) { return __gcd(__gcd(a, b), c); }

ll __lcm(ll a, ll b, ll c) { return __lcm(__lcm(a, b), c); }

ll pow(ll a, ll b) { ll res = 1; while (b) { if (b & 1) res = (res * a); a = (a * a); b >>= 1; } return res; }

ll pow(ll a, ll b, ll m) { ll res = 1; while (b) { if (b & 1) res = (res * a) % m; a = (a * a) % m; b >>= 1; } return res; }

ll modInv(ll a, ll m = mod) { return pow(a, m - 2, m); }

ll fact(ll n) { ll res = 1; for (ll i = 1; i <= n; i++) res = (res * i) % mod; return res; }

vector<ll> sieve(ll n) { bool prime[n + 1]; memset(prime, true, sizeof(prime)); for (ll p = 2; p * p <= n; p++) { if (prime[p] == true) { for (ll i = p * p; i <= n; i += p) prime[i] = false; } } vector<ll> v; for (ll i = 2; i <= n; i++) { if (prime[i]) v.pb(i); } return v; }

ll dijkstra(vector<vector<pair<ll, ll>>> &adj, ll src, ll dest) { vector<ll> dist(adj.size(), 1e18); dist[src] = 0; priority_queue<pair<ll, ll>, vector<pair<ll, ll>>, greater<pair<ll, ll>>> pq; pq.push({0, src}); while (!pq.empty()) { ll u = pq.top().se; ll d = pq.top().fi; pq.pop(); if (d > dist[u]) continue; for (auto v : adj[u]) { if (dist[u] + v.se < dist[v.fi]) { dist[v.fi] = dist[u] + v.se; pq.push({dist[v.fi], v.fi}); } } } return dist[dest]; }

ll nCr(ll n, ll r) { if (r > n) return 0; if (r > n - r) r = n - r; ll ans = 1; for (ll i = 0; i < r; i++) { ans *= (n - i); ans /= (i + 1); } return ans; }

void func()

{

   s s1;

   ll res=1,t1,oc=0,ec=0,n;

   cin >> n;

   cin >> s1;

   ll a[n];

   f(i,0,n) {

       t1=(int(s1[i])-'0');

       if (t1%2==0) {

           a[i]=0;

           ec++;

       } else {

           a[i]=1;

           oc++;

       }

   }

   if (oc==0 || oc==1 || (oc==1 && a[0]==1)) {

       c1(-1);

   } else {

       ll count=0;

       f(i,0,n) {

           if (count==2) {

               break;

           }

           if (a[i]==1) {

               c(s1[i]);

               count++;

           }

       } c(nl);

   }

}

int main(){

fast;

    ll t;

    cin >> t;

    while (t--)

    {

        func();

    }

    return 0;

}