A renowned abstract artist Sasha, drawing inspiration from nowhere, decided to paint a picture entitled "Special Olympics". He justly thought that, if the regular Olympic games have five rings, then the Special ones will do with exactly two rings just fine.Let us remind you that a ring is a region located between two concentric circles with radii r and R (r < R). These radii are called internal and external, respectively. Concentric circles are circles with centers located at the same point.Soon a white canvas, which can be considered as an infinite Cartesian plane, had two perfect rings, painted with solid black paint. As Sasha is very impulsive, the rings could have different radii and sizes, they intersect and overlap with each other in any way. We know only one thing for sure: the centers of the pair of rings are not the same.When Sasha got tired and fell into a deep sleep, a girl called Ilona came into the room and wanted to cut a circle for the sake of good memories. To make the circle beautiful, she decided to cut along the contour.We'll consider a contour to be a continuous closed line through which there is transition from one color to another (see notes for clarification). If the contour takes the form of a circle, then the result will be cutting out a circle, which Iona wants.But the girl's inquisitive mathematical mind does not rest: how many ways are there to cut a circle out of the canvas?

The input contains two lines.  Each line has four space-separated integers xi, yi, ri, Ri, that describe the i-th ring; xi and yi are coordinates of the ring's center, ri and Ri are the internal and external radii of the ring correspondingly ( - 100 ≤ xi, yi ≤ 100; 1 ≤ ri < Ri ≤ 100).  It is guaranteed that the centers of the rings do not coinside.

A single integer — the number of ways to cut out a circle from the canvas.

NoteFigures for test samples are given below. The possible cuts are marked with red dotted line.

#include <iostream>
#include <cmath>
#include <bits/stdc++.h>
#include "vector"

// getline(cin, string);
//memset(memo, -1, sizeof memo); // initialize DP memoization table with -1
//memset(arr, 0, sizeof arr); // to clear array of integers
using namespace std;
#define F first
#define S second
#define ll long long
#define PB push_back
#define MP make_pair
#define all(v) v.begin(), v.end()
#define sz(v) ((int)((v).size()))
#define f(i, n) for(ll i=0; i < n; i++)
#define oo 1e17+5
typedef vector<int> vi;
typedef set<string> ss;
typedef set<int> si;
typedef set<ll> sll;
typedef vector<long long> vll;
typedef long double   	  ld;
typedef vector<double>    vd;
typedef vector<vi>      vvi;
typedef vector< vd >      vvd;
typedef vector<string>    vs;
typedef pair<int, int> ii;
typedef pair<ll, ll> lll;

const ll M = 998244353;
const ll MAX = 1e18;
const ld EPS {1e-19};
const ld PI {3.14159265358979323846};
ll pow(ll x, ll y) {
    ll ans{1};
    while(y) {
        if(y&1) ans *= x;
        x *= x;
        y /= 2;
    }
    return ans;
}
ll big_pow(ll x, ll y) {
    ll ans{1};
    while(y) {
        if(y&1) ans = ((ans%M)*(x%M)) % M;
        x = ((x%M) * (x%M)) %M;
        y/=2;
    }
    return ans;
}
bool is_int(ld num) {
    return num == (ll)num;
}
int cmp_d(ld a, ld b) {
    if(fabs(a-b) <= EPS) return -1;
    return a>b? 1:0;
}
ll mod(ll x, ll m){
    return (x%m +m) % m;
}

void printVec(const vi& v, string t =""){
    cout << t;
    for(auto i = v.begin(); i!= v.end(); i++) {
        cout << *i <<" ";
//        if(i != v.end() -1) cout << " ";
    }
    cout <<"\n";
}

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

ll mod_pow(ll b, ll p, ll m) {
    if(!p) return 1;

    ll ans = mod_pow(b,p/2,m);
    ans = mod(ans*ans,m);

    if(p&1) ans = mod(ans*b,m);
    return ans;
}
// M is a prime number > N
ll inv(ll a) {     // Fermat's little theorem
    return mod_pow(a,M-2,M); // O(log p)
}

unsigned ll C(unsigned ll n, unsigned ll k, unsigned ll fact[]){
    return ( ((fact[n] * inv(fact[k]))%M) * inv(fact[n-k]) ) % M;
}
struct comp {
    template <typename T>
    bool operator()(const T& p1, const T& p2) const
    {
        if(p1.second != p2.second) return p1.second < p2.second;
        else return p1.first < p1.first;
    }
};

double dist(ld x, ld y, ii p2){
    return sqrt(pow((x - p2.F), 2) + pow((y- p2.S), 2));
}

struct P {
    ll x, y, z;
    bool operator<(const P &p) const {
        if(x != p.x) return x <  p.x;
        else return y <  p.y;
    }
};

const ll N = 1e2+2;
bool vis[N];
vector<vi> v(N);

void dfs(double p,ll i ,ll l){
    vis[i] = 1;
    ll nnv= 0;
    for(auto x: v[i]){
        if(!vis[x]) nnv++;
    }
    if(nnv) p /= (double) (nnv);
    for(auto x: v[i]){
        if(!vis[x]) {
            dfs(p, x, l+1);
        }
    }
}

ll mem[N][N][3];
ll k1, k2;
ll dp(ll n1, ll n2, int f){
    if(n1 == 0 && n2 == 0) return 1;
    else if (n1 < 0 || n2 < 0) return 0;
    if(mem[n1][n2][f] != -1) return mem[n1][n2][f];

    ll nways = 0;
    if(f != 1){
        for(int i = 1; i <= k1; i++){
            if(n1 - i < 0) break;
            nways += dp(n1 - i, n2, 1);
        }
    }

    if(f != 0){
        for(int i = 1; i <= k2; i++){
            if(n2 - i < 0) break;
            nways += dp(n1, n2- i, 0);
        }
    }

    mem[n1][n2][f] = nways % 100000000;
    return mem[n1][n2][f];

}

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    ll x1, y1, r1, R1, x2, y2, r2, R2;
    cin>> x1 >> y1 >> r1 >> R1;
    cin>> x2 >> y2 >> r2 >> R2;
    ll cnt =0;
    ld c1c2 = dist(x1, y1, MP(x2, y2));

    bool ch11 =0, ch1 = 0, ch22 = 0, ch2 = 0;
    if(abs(r2 - r1) >= c1c2) ch11 = 1;
    else if(c1c2 >= r2 + r1) ch1 = 1;
    if(abs(R2 - r1) >= c1c2) ch22 = 1;
    else if(c1c2 >= R2 + r1) ch2 = 1;
    if((ch1 || ch11) && (ch2 || ch22)){
        if(ch11 && ch22){ if((r2 - r1) * (R2 - r1) > 0) cnt++;}
        else if(ch1 && ch2) cnt++;
    }
//    cout << cnt<<"\n";

    ch11 =0, ch1 = 0, ch22 = 0, ch2 = 0;
    if(abs(r2 - R1) >= c1c2) ch11 = 1;
    else if(c1c2 >= r2 + R1) ch1 = 1;
    if(abs(R2 - R1) >= c1c2) ch22 = 1;
    else if(c1c2 >= R2 + R1) ch2 = 1;
    if((ch1 || ch11) && (ch2 || ch22)){
        if(ch11 && ch22) {if(((r2 - R1) * (R2 - R1) > 0)) cnt++; }
        else if(ch1 && ch2) cnt++;
    }
//    cout << cnt<<"\n";

    ch11 =0, ch1 = 0, ch22 = 0, ch2 = 0;
    if(abs(r2 - r1) >= c1c2) ch11 = 1;
    else if(c1c2 >= r1 + r2) ch1 = 1;
    if(abs(r2 - R1) >= c1c2) ch22 = 1;
    else if(c1c2 >= R1 + r2) ch2 = 1;
    if((ch1 || ch11) && (ch2 || ch22)){
        if(ch11 && ch22) { if((r1 - r2) * (R1 - r2) > 0) cnt++; }
        else if(ch1 && ch2) cnt++;
    }
//    cout << cnt<<"\n";

    ch11 =0, ch1 = 0, ch22 = 0, ch2 = 0;
    if(abs(R2 - r1) >= c1c2) ch11 = 1;
    else if(c1c2 >= r1 + R2) ch1 = 1;
    if(abs(R2 - R1) >= c1c2) ch22 = 1;
    else if(c1c2 >= R1 + R2) ch2 = 1;
    if((ch1 || ch11) && (ch2 || ch22)){
        if(ch11 && ch22) { if((r1 - R2) * (R1 - R2) > 0) cnt++; }
        else if(ch1 && ch2) cnt++;
    }
    cout << cnt;
}


Consider some square matrix A with side n consisting of zeros and ones. There are n rows numbered from 1 to n from top to bottom and n columns numbered from 1 to n from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the i-row and the j-th column as Ai, j.Let's call matrix A clear if no two cells containing ones have a common side.Let's call matrix A symmetrical if it matches the matrices formed from it by a horizontal and/or a vertical reflection. Formally, for each pair (i, j) (1 ≤ i, j ≤ n) both of the following conditions must be met: Ai, j = An - i + 1, j and Ai, j = Ai, n - j + 1.Let's define the sharpness of matrix A as the number of ones in it.Given integer x, your task is to find the smallest positive integer n such that there exists a clear symmetrical matrix A with side n and sharpness x.

The only line contains a single integer x (1 ≤ x ≤ 100) — the required sharpness of the matrix.

Print a single number — the sought value of n.

NoteThe figure below shows the matrices that correspond to the samples:

/*
    Jai shankar

             _.Y-'''''`..
            ,'          `.
           /             `\
          |'              `\
          |  .,-------..   '|
          |  `.......--'   \'
          |   /--+--+--\    '
          |   "..|\,:-''    |
      ____|  ,-''''''''b    |----.._
 .,--i,.--|   '"------''    |''''--:`----..._
'|,--'    |                 |       `.--::--.:;_
||                                  ,YY'''''`- .`.
| `-...__                        ,-'   '`       \|
 \,_`--..:::--....____  ___...-''    ,-''-b     ||
   ':--....                  ,,.,--''      ``.. ||
     `-.   ``-------....,--'',/                `|
         \.                  /|
         ||                  \|
         ||                   `b
       ,b'                     ``=
   ,-'''                         '``.
   |                                 |
   |                      :dg:       |
   `---'''''`-------------'''''''''''

                                                    */

#include <bits/stdc++.h>
#include <climits>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

#define ll long long
#define pii pair<int, int>
#define pll pair<long long, long long>
#define vi vector<int>
#define vll vector<long long>
#define mii map<int, int>
#define si set<int>
#define ff first
#define ss second
// #define sc set<char>

/* FUNCTION */
#define f(i, s, e) for (long long i = s; i < e; i++)
#define fe(i, s, e) for (long long i = s; i <= e; i++)
#define rf(i, e, s) for (long long i = e - 1; i >= s; i--)
#define pb push_back
#define eb emplace_back

/* PRINTS */
template <class T>
void print_v(vector<T> &v)
{
    cout << "{";
    for (auto x : v)
        cout << x << ",";
    cout << "\b";
}

/* UTILS */
#define MOD 1000000007
#define debug(x) cout << #x << " " << x << endl;
#define pi 3.14159
ll min(ll a, int b)
{
    if (a < b)
        return a;
    return b;
}
ll min(int a, ll b)
{
    if (a < b)
        return a;
    return b;
}
ll max(ll a, int b)
{
    if (a > b)
        return a;
    return b;
}
ll max(int a, ll b)
{
    if (a > b)
        return a;
    return b;
}
ll gcd(ll a, ll b)
{
    if (b == 0)
        return a;
    return gcd(b, a % b);
}
ll lcm(ll a, ll b) { return a / gcd(a, b) * b; }
string to_upper(string a)
{
    for (int i = 0; i < (int)a.size(); ++i)
        if (a[i] >= 'a' && a[i] <= 'z')
            a[i] -= 'a' - 'A';
    return a;
}
string to_lower(string a)
{
    for (int i = 0; i < (int)a.size(); ++i)
        if (a[i] >= 'A' && a[i] <= 'Z')
            a[i] += 'a' - 'A';
    return a;
}
bool prime(ll a)
{
    if (a == 1)
        return 0;
    for (int i = 2; i <= round(sqrt(a)); ++i)
        if (a % i == 0)
            return 0;
    return 1;
}

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

void yes() { cout << "YES\n"; }
void no() { cout << "NO\n"; }

typedef long int int32;
typedef unsigned long int uint32;
typedef long long int int64;
typedef unsigned long long int uint64;
typedef vector<ll> vl;
typedef vector<char> vc;
typedef vector<string> vs;

template <typename T>
void add(T &a, T b, T M)
{
    a = ((a % M) + (b % M)) % M;
}

template <typename T>
void mul(T &a, T b, T M)
{
    a = ((a % M) * (b % M)) % M;
}

template <typename T>
void sub(T &a, T b, T M)
{
    a = (a - b + M) % M;
}
typedef vector<pair<ll,ll>>vpl;
#define all(v) (v).begin(),(v).end()

class dsu{
        ll n;
    vector<ll> par, sz;
public:
    dsu(int s){
        n=s;
        for(int i=0; i<n; i++){
            par.push_back(i);
            sz.push_back(1);
        }
    }

    ll findPar(int a){
        if(par[a]==a) return a;

        return par[a]=findPar(par[a]);
    }

    void Union(int a, int b){
        if(findPar(par[a])==findPar(par[b])) return;

        if(sz[par[a]]<sz[par[b]]){
            par[findPar(a)]=par[findPar(b)];
            sz[par[b]]+=sz[par[a]];
        }
        else{
            par[findPar(b)]=par[findPar(a)];
            sz[par[a]]+=sz[par[b]];
        }
    }

};

int maxi=0;

// void Dijkstra(ll s, ll n, vector<ll> &dist,vector<int> &parent vector<pair<ll, ll>> *adj) {
//     dist.assign(n, 1e18);
//     parent.assign(n, -1);
//     dist[s] = 0;
//     priority_queue <pair<ll, ll>, vector<pair<ll, ll>>, greater<pair<ll, ll>>> q;
//     q.push({0, s});
//     while (!q.empty()) {
//         pair<ll, ll> here = q.top();
//         q.pop();
//         ll v = here.ss;
//         ll d_v = here.ff;
//         if (d_v != dist[v])
//             continue;
//         for (auto edge : adj[v]) {
//             if (dist[v] + edge.ss < dist[edge.ff]) {
//                 dist[edge.ff] = dist[v] + edge.ss;
//                 maxi=max(maxi, edge.ss);
//                 parent[edge.ff] = v;
//                 q.push({dist[edge.ff], edge.ff});
//             }
//         }
//     }
// }

/* ------------------------------------------ OM GAN GANPATYAY NAMAH -------------------------------------------------*/
void dijkstra(ll src, vector<ll> *adj, vector<ll> & dis){
    set<pair<ll, ll> > st;

    st.insert({0, src});
    while(!st.empty()){
        auto it=*st.begin();
        st.erase(st.begin());
        ll node=it.ss;
        ll d= it.ff;

        for(int it:adj[node]){
            if(d+1<dis[it]){
                st.erase({dis[it], it});
                dis[it]=d+1;

                st.insert({dis[it], it});
            }
        }
    }
}

bool valid(int i, int j, int n, int m){
    if(i<0 || i>=n || j<0 || j>=m) return 0;
    return 1;
}

int main(){

    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);   // file input.txt is opened in reading mode i.e "r"
    freopen("output.txt", "w", stdout); // file output.txt is opened in writing mode i.e "w"
    #endif
    // ncr();
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    // const int M = 998244353;
    // ll t;
    // cin >> t;
    // while (t--) {

//     /*======================= KYA RE BHIKH-MANGEYA AA GYA CODE PADHNE =======================*/
        // int n,k;

        int n;
        cin>>n;
        int sum=0;
        int i=1;
        while((i*i+1)/2<n) i+=2;
        cout<<(n==3?5:i);
        // cout<<i<<'\n';

// }

return 0;

}

/*
    The worse Day of my coding history is 13 June 2023.
    I will remember you and show you who is OJAS GUPTA.

    XXXXXX (13 JUNE 2023) XXXXXXX
*/


Polycarpus plays with red and blue marbles. He put n marbles from the left to the right in a row. As it turned out, the marbles form a zebroid.A non-empty sequence of red and blue marbles is a zebroid, if the colors of the marbles in this sequence alternate. For example, sequences (red; blue; red) and (blue) are zebroids and sequence (red; red) is not a zebroid.Now Polycarpus wonders, how many ways there are to pick a zebroid subsequence from this sequence. Help him solve the problem, find the number of ways modulo 1000000007 (109 + 7).

The first line contains a single integer n (1 ≤ n ≤ 106) — the number of marbles in Polycarpus's sequence.

Print a single number — the answer to the problem modulo 1000000007 (109 + 7).

NoteLet's consider the first test sample. Let's assume that Polycarpus initially had sequence (red; blue; red), so there are six ways to pick a zebroid:   pick the first marble;  pick the second marble;  pick the third marble;  pick the first and second marbles;  pick the second and third marbles;  pick the first, second and third marbles. It can be proven that if Polycarpus picks (blue; red; blue) as the initial sequence, the number of ways won't change.

#include <iostream>
using namespace std;

const int MOD = 1000000007;

int N;

int main(){
    cin >> N;
    int red = 0, blue = 0;
    for (int i = 0; i < N; i++){
        if (i % 2 == 0){
            red += blue + 1;
            red %= MOD;
        }
        else{
            blue += red + 1;
            blue %= MOD;
        }
    }
    cout << (red + blue) % MOD << endl;
    return 0;
}


A bracket sequence is a string, containing only characters "(", ")", "[" and "]".A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([])" are correct (the resulting expressions are: "(1)+[1]", "([1+1]+1)"), and "](" and "[" are not. The empty string is a correct bracket sequence by definition.A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (where |s| is the length of string s) is the string slsl + 1... sr. The empty string is a substring of any string by definition.You are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets «[» as possible.

The first and the only line contains the bracket sequence as a string, consisting only of characters "(", ")", "[" and "]". It is guaranteed that the string is non-empty and its length doesn't exceed 105 characters.

In the first line print a single integer — the number of brackets «[» in the required bracket sequence. In the second line print the optimal sequence. If there are more than one optimal solutions print any of them.

#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>

using namespace std;

void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}

template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif

#define INF 1e9+7
#define all(x) x.begin(),x.end()
#define endl '\n'
typedef long long ll;
using pii=pair<int,int>;

using namespace __gnu_pbds;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;

string text;
int cnt[100010];
int n;
int ans;
int ansL,ansR;

int solve(int l,int r) {
    if(!l) return cnt[r];
    return cnt[r]-cnt[l-1];
}
vector<pii> seg;

int main () {
    ios::sync_with_stdio(false); cin.tie(0);
    cin>>text; n=text.size();
    for(int i=0;i<n;i++) {
        if(i) cnt[i]+=cnt[i-1];
        if(text[i]=='[') {
            cnt[i]++;
        }
    }
    stack<int> s;
    for(int i=0;i<n;i++) {
        if(text[i]=='(' or text[i]=='[') s.push(i);
        else {
            if(text[i]==')') {
                if(!s.empty() and text[s.top()]=='(') {

                    if(!s.empty()) {

                        seg.emplace_back(s.top(),i);
                    }
                    s.pop();

                }
                else if(!s.empty() and s.top()!='(') {
                    while(!s.empty()) s.pop();

                }
            }
            else {
                if(!s.empty() and text[s.top()]=='[') {

                    if(!s.empty()) {
                        seg.emplace_back(s.top(),i);
                    }
                    s.pop();

                }
                else {
                    while(!s.empty()) s.pop();
                }
            }
        }
    }
    if(seg.empty()) {
        cout<<"0"<<endl; return 0;
    }
    sort(all(seg));
    int len=seg.size(); int l=seg[0].first; int r=seg[0].second;
    for(int i=1;i<len;i++) {
        if(seg[i].second<=r) continue;
        if(seg[i].first<=r+1) {
            r=seg[i].second;
        }
        else {
            int res=solve(l,r);
            if(res>ans) {
                ansL=l; ansR=r; ans=res;
            }
            l=seg[i].first; r=seg[i].second;
        }
    }

    int res=solve(l,r);
    if(res>ans) {
        ansL=l; ansR=r; ans=res;
    }
    //debug(seg);
    cout<<ans<<endl;
    if(ans) {
            for(int i=ansL;i<=ansR;i++) cout<<text[i];
    }
}


Once upon a time an old man and his wife lived by the great blue sea. One day the old man went fishing and caught a real live gold fish. The fish said: "Oh ye, old fisherman! Pray set me free to the ocean and I will grant you with n gifts, any gifts you wish!". Then the fish gave the old man a list of gifts and their prices. Some gifts on the list can have the same names but distinct prices. However, there can't be two gifts with the same names and the same prices. Also, there can be gifts with distinct names and the same prices. The old man can ask for n names of items from the list. If the fish's list has p occurrences of the given name, then the old man can't ask for this name of item more than p times.The old man knows that if he asks for s gifts of the same name, the fish will randomly (i.e. uniformly amongst all possible choices) choose s gifts of distinct prices with such name from the list. The old man wants to please his greedy wife, so he will choose the n names in such a way that he can get n gifts with the maximum price. Besides, he isn't the brightest of fishermen, so if there are several such ways, he chooses one of them uniformly.The old man wondered, what is the probability that he can get n most expensive gifts. As the old man isn't good at probability theory, he asks you to help him.

The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 1000) — the number of the old man's wishes and the number of distinct names in the goldfish's list, correspondingly. Then m lines follow: the i-th line first contains integer ki (ki > 0) — the number of distinct prices of gifts with the i-th name, then ki distinct space-separated integers cij (1 ≤ cij ≤ 109), the gifts' prices.  It is guaranteed that the sum of all ki doesn't exceed 1000. It is guaranteed that n is not greater than the total number of the gifts.

On a single line print one real number — the probability of getting n most valuable gifts. The answer will be considered correct if its absolute or relative error does not exceed 10 - 9.


Not long ago Billy came across such a problem, where there were given three natural numbers A, B and C from the range [1, N], and it was asked to check whether the equation AB = C is correct. Recently Billy studied the concept of a digital root of a number. We should remind you that a digital root d(x) of the number x is the sum s(x) of all the digits of this number, if s(x) ≤ 9, otherwise it is d(s(x)). For example, a digital root of the number 6543 is calculated as follows: d(6543) = d(6 + 5 + 4 + 3) = d(18) = 9. Billy has counted that the digital root of a product of numbers is equal to the digital root of the product of the factors' digital roots, i.e. d(xy) = d(d(x)d(y)). And the following solution to the problem came to his mind: to calculate the digital roots and check if this condition is met. However, Billy has doubts that this condition is sufficient. That's why he asks you to find out the amount of test examples for the given problem such that the algorithm proposed by Billy makes mistakes.

The first line contains the only number N (1 ≤ N ≤ 106).

Output one number — the amount of required A, B and C from the range [1, N].

NoteFor the first sample the required triples are (3, 4, 3) and (4, 3, 3).

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn=1000010;
long long c[10];
int f[maxn];
int prime[maxn];
int vis[maxn];
int d(int x)
{
	int tmp=0;
	while(x)
	{
		tmp+=x%10;
		x/=10;
	}
	return tmp<10?tmp:d(tmp);
}
void init()
{
	memset(vis,0,sizeof(vis));
	f[1]=1;
	int tot=0;
	for(int i=2;i<=1000000;i++)
	{
		if(!vis[i])
		{
			f[i]=2;
			prime[tot++]=i;
		}
		for(int j=0;j<tot;j++)
		{
			if(i*prime[j]>1000000) break;
			vis[i*prime[j]]=1;
			if(i%prime[j]==0)
			{
				int tmp=i;
				while(tmp%prime[j]==0) tmp/=prime[j];
				f[i*prime[j]]=(f[i/tmp]+1)*f[tmp];
				break;
			}
			else f[i*prime[j]]=f[i]*f[prime[j]];
		}
	}
}
int main()
{
	init();
	int n;
	scanf("%d",&n);
	long long res=0;
	for(int i=1;i<=n;i++)
	{
		c[d(i)]++;
		res+=f[i];
	//	cout<<f[i]<<endl;
	}
	long long ans=0;
	for(int i=0;i<10;i++)
		for(int j=0;j<10;j++)
		{
			long long k=d(i*j),tmp;
			if(i==j) tmp=c[i]*c[i];
			else tmp=c[i]*c[j];
			ans+=tmp*c[k];
		}
	//cout<<res<<" "<<ans<<endl;
	cout<<ans-res<<endl;
	return 0;
}


Nick is attracted by everything unconventional. He doesn't like decimal number system any more, and he decided to study other number systems. A number system with base b caught his attention. Before he starts studying it, he wants to write in his notepad all the numbers of length n without leading zeros in this number system. Each page in Nick's notepad has enough space for c numbers exactly. Nick writes every suitable number only once, starting with the first clean page and leaving no clean spaces. Nick never writes number 0 as he has unpleasant memories about zero divide.Would you help Nick find out how many numbers will be written on the last page.

The only input line contains three space-separated integers b, n and c (2 ≤ b < 10106, 1 ≤ n < 10106, 1 ≤ c ≤ 109). You may consider that Nick has infinite patience, endless amount of paper and representations of digits as characters. The numbers doesn't contain leading zeros.

In the only line output the amount of numbers written on the same page as the last number.

NoteIn both samples there are exactly 4 numbers of length 3 in binary number system. In the first sample Nick writes 3 numbers on the first page and 1 on the second page. In the second sample all the 4 numbers can be written on the first page.

#include<bits/stdc++.h>
#define LL long long
using namespace std;
vector<int>ve;
LL M;
void qfind(int n)
{
	for (int i = 2; i*i <= n; ++i)
		if (n%i == 0)
		{
			n /= i; ve.push_back(i);
			while (n%i == 0) n /= i;
			qfind(n);
			return;
		}
	if(ve.size()==0||n>*ve.rbegin())ve.push_back(n);
}
LL power(LL x, LL n)
{
	LL ans = 1;
	while (n)
	{
		if (n & 1)ans = ans*x%M;
		x = x*x%M;
		n >>= 1;
	}
	return ans;
}
int main()
{
	string b, n; LL c;
	cin >> b >> n;
	scanf("%lld", &c);
	LL nn = 0, bb = 0;
	M = c;
	for (int i = 0; i< b.length(); ++i)
		bb = (bb * 10 % c + b[i] - '0') % M;
	if (n.length() <= 11)
	{
		for (int i = 0; i<n.length(); ++i)
			nn = nn * 10 + n[i] - '0';
	}

	else
	{
		LL temp = c;
		qfind(c);
		for (int i = 0; i < ve.size(); ++i)
		{
			temp = (temp*(ve[i] - 1)*1.0) / ((ve[i]) * 1.0);
		}
		nn = 0;
		for (int i = 0; i<n.length(); ++i)
			nn = (nn * 10 % temp + n[i] - '0') % temp;
		nn += temp;
	}
	LL ans1 = (power(bb, nn) - power(bb, nn - 1) + M) % M;
	if (ans1 == 0) ans1 = c;
	 printf("%lld\n", ans1);
	return 0;
}


There is a new TV game on BerTV. In this game two players get a number A consisting of 2n digits. Before each turn players determine who will make the next move. Each player should make exactly n moves. On it's turn i-th player takes the leftmost digit of A and appends it to his or her number Si. After that this leftmost digit is erased from A. Initially the numbers of both players (S1 and S2) are «empty». Leading zeroes in numbers A, S1, S2 are allowed. In the end of the game the first player gets S1 dollars, and the second gets S2 dollars.One day Homer and Marge came to play the game. They managed to know the number A beforehand. They want to find such sequence of their moves that both of them makes exactly n moves and which maximizes their total prize. Help them.

The first line contains integer n (1 ≤ n ≤ 18). The second line contains integer A consisting of exactly 2n digits. This number can have leading zeroes.

Output the line of 2n characters «H» and «M» — the sequence of moves of Homer and Marge, which gives them maximum possible total prize. Each player must make exactly n moves. If there are several solutions, output any of them.

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
#define PI acos(-1)
#define LSB(i) ((i) & -(i))
#define ll long long
#define pb push_back
#define mp make_pair
#define mt make_tuple
#define fi first
#define sc second
#define th third
#define fo fourth
#define pii pair<int,int>
#define pll pair<ll,ll>
#define ldb double
#define INF 1e15
#define MOD 1000000007
#define endl "\n"

#define all(data)       data.begin(),data.end()
#define TYPEMAX(type)   std::numeric_limits<type>::max()
#define TYPEMIN(type)   std::numeric_limits<type>::min()
#define MAXN 20
ll a[2*MAXN];
ll dp[MAXN][MAXN],pow10[MAXN];
int main()
{
    ios::sync_with_stdio(false); cin.tie(0);
    pow10[0]=1;
    for(int i=1;i<18;i++) pow10[i]=10*pow10[i-1];
    ll n; cin>>n; char c;
    for(int i=1;i<=2*n;i++) {cin>>c; a[i]=c-'0';}
    for(int i=1;i<=n;i++) swap(a[i],a[2*n-i+1]);
    for(int i=0;i<=n;i++)
    {
        for(int j=0;j<=n;j++)
        {
            dp[i][j]=0;
            if(i) dp[i][j]=max(dp[i][j],dp[i-1][j]+pow10[i-1]*a[i+j]);
            if(j) dp[i][j]=max(dp[i][j],dp[i][j-1]+pow10[j-1]*a[i+j]);
        }
    }
    vector<char> v;
    ll i=n,j=n;
    while(i || j)
    {
        if(i && j)
        {
            if(dp[i][j]==dp[i-1][j]+pow10[i-1]*a[i+j]) {v.pb('H'); i--;}
            else {v.pb('M'); j--;}
        }
        else if(i) {v.pb('H'); i--;}
        else {v.pb('M'); j--;}
    }
    //reverse(all(v));
    for(auto x:v) cout<<x;
    return 0;
}


A schoolboy Petya studies square equations. The equations that are included in the school curriculum, usually look simple: x2 + 2bx + c = 0 where b, c are natural numbers.Petya noticed that some equations have two real roots, some of them have only one root and some equations don't have real roots at all. Moreover it turned out that several different square equations can have a common root.Petya is interested in how many different real roots have all the equations of the type described above for all the possible pairs of numbers b and c such that 1 ≤ b ≤ n, 1 ≤ c ≤ m. Help Petya find that number.

The single line contains two integers n and m. (1 ≤ n, m ≤ 5000000).

Print a single number which is the number of real roots of the described set of equations.

NoteIn the second test from the statement the following equations are analysed: b = 1, c = 1: x2 + 2x + 1 = 0; The root is x =  - 1 b = 1, c = 2: x2 + 2x + 2 = 0; No roots Overall there's one rootIn the second test the following equations are analysed: b = 1, c = 1: x2 + 2x + 1 = 0; The root is x =  - 1 b = 1, c = 2: x2 + 2x + 2 = 0; No roots b = 1, c = 3: x2 + 2x + 3 = 0; No roots b = 2, c = 1: x2 + 4x + 1 = 0; The roots are  b = 2, c = 2: x2 + 4x + 2 = 0; The roots are  b = 2, c = 3: x2 + 4x + 3 = 0; The roots are x1 =  - 3, x2 =  - 1 b = 3, c = 1: x2 + 6x + 1 = 0; The roots are  b = 3, c = 2: x2 + 6x + 2 = 0; The roots are  b = 3, c = 3: x2 + 6x + 3 = 0; The roots are  Overall there are 13 roots and as the root  - 1 is repeated twice, that means there are 12 different roots.

#define _USE_MATH_DEFINES
#define _CRT_SECURE_NO_DEPRECATE

#include <algorithm>
#include <bitset>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>

using namespace std;

#pragma comment(linker, "/STACK:64000000")

#define problem "Khaustov"

typedef long long int64;
typedef unsigned char byte;
typedef pair<int, int> pii;
typedef pair<int, pii> piii;
typedef pair<int64, int64> pii64;
typedef pair<pii64, int> piii64;
typedef pair<double, int64> pdi;
typedef pair<double, double> pdd;
typedef pair<pdi, int> pdii;
typedef pair<int, string> pis;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<vvi> vvvi;
typedef vector<pii> vpii;
typedef vector<vpii> vvpii;
typedef vector<string> vs;
typedef vector<vs> vvs;
typedef list<int> li;
typedef stringstream ss;

#define y1 _dsfdsfkn
#define left _dsfdsf
#define right _dfjdsj
#define link _tsu_sux
#define prime 1103
#define eps 1e-8
#define inf 123456789
#define toMod 1000000007LL

inline double sqr(double x)
{
    return x * x;
}

int n, m;
pii PREV, CUR;

int64 res;
int k;
pii a[15000000];

inline pii make(int x, int y)
{
    if (x > y) swap(x, y);
    return pii(x, y);
}

int main()
{
    //freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);

    k = 0;
    scanf("%d%d", &n, &m);
    res = 0;
    for (int b = 1; b <= n; ++b)
    {
        int MAX = b - 1;
        int MIN = 1;

        int64 sb = b;
        sb *= (int64)b;

        if (sb > m)
        {
            double T = sqrt((double)(sb - m));
            if (T > 1e-9) T -= 1e-9;
            MIN = (int)ceil(T);
        } else a[k++] = make(-b, -b);

        if (MIN > MAX)
        {
            int64 lim = min((int64)m, sb - 1);
            res += 2 * lim;
            continue;
        }

        int64 lim = min((int64)m, sb - 1);
        lim -= (MAX - MIN + 1);
        res += 2 * lim;

        a[k++] = make(MAX - b, MIN - b);
        a[k++] = make(-MAX - b, -MIN - b);
    }

    sort(a, a + k);
    if (k) res += (a[0].second - a[0].first + 1);
    for (int i = 1; i < k; ++i)
    {
        a[i].first = max(a[i].first, a[i - 1].second + 1);
        if (a[i].second >= a[i].first)
            res += (a[i].second - a[i].first + 1);
        a[i].second = max(a[i].second, a[i - 1].second);
    }

    printf("%lld\n", res);

    return 0;
}


Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry.

The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp.

If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO".

#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>

using namespace std;

double cartesian_distance(const vector<double>& a,
      const vector<double>& b) {
   double square_sum = 0;

   for(int i = 0; i < 3; ++i) {
      square_sum += (b[i] - a[i]) * (b[i] - a[i]);
   }

   return sqrt(square_sum);
}

inline void read_point(vector<double>& dest) {
   for(int j = 0; j < 3; ++j) {
      int a;
      cin >> a;
      dest[j] = a;
   }
}

int main() {
   ios_base::sync_with_stdio(false);

   cout.setf(ios_base::fixed, ios_base::floatfield);
   cout.precision(10);

   int n;
   cin >> n;

   vector<vector<double> > lines(n + 1, vector<double>(3));

   for(int i = 0; i <= n; ++i) {
      read_point(lines[i]);
   }

   int v_potter, v_snitch;
   cin >> v_potter >> v_snitch;

   vector<double> potter_start(3);
   read_point(potter_start);

   // General idea: Do a binary search on the time Harry will catch
   // the snitch.
   // Let t_left and t_right be the range of times where
   // you are searching in, and t_middle = (t_left + t_right) / 2.
   // If Harry can reach the ball at t_middle (i.e, if the time it takes
   // Harry to reach the point where the snitch is at t_middle is <=
   // t_middle), then we'll search in [t_left, t_middle], otherwise
   // we'll search in [t_middle, t_right]. Notice that, because
   // v_potter >= v_snitch, if Harry can catch the snitch at time
   // t_a, then he will be able to catch it at time t_b > t_a. So the
   // algorithm will always find the correct answer if it exists.
   // Also, if Harry can't reach the last point fast enough (i.e before
   // the snitch), then there is no answer.
   //
   // We'll need to compute the time it takes reach each particular
   // line so we know the point where the snitch is at a particular time t

   vector<double> times(n + 1);

   for(int i = 1; i <= n; ++i) {
      times[i] = times[i - 1] +
         cartesian_distance(lines[i], lines[i - 1]) / v_snitch;
   }

   const double eps = 1e-12;

   if (times[n] + eps < cartesian_distance(potter_start, lines[n]) /
         v_potter) {
      cout << "NO\n";
   } else {
      // Possible, start binary search
      double t_left = 0,
             t_right = times[n],
             t_middle;

      vector<double> point(3);

      for(int i = 0; i < 150; ++i) {
        t_middle = (t_left + t_right) / 2;

        // Find the line where t_middle belongs
        // index is the second point of the line
        int index = upper_bound(times.begin(), times.end(), t_middle) -
           times.begin();

        index = min(index, n);

        double segment_time = t_middle - times[index - 1];
        double factor = segment_time / (times[index] - times[index - 1]);

        // Compute point
        for(int i = 0; i < 3; ++i) {
           point[i] = lines[index - 1][i] +
              factor * (lines[index][i] - lines[index - 1][i]);
        }

        double potter_distance = cartesian_distance(point, potter_start);
        double potter_time = potter_distance / v_potter;

        if (abs(potter_time - t_middle) <= eps) {
           break;
        } else if (potter_time > t_middle) {
           // Search right
           t_left = t_middle;
        } else {
           t_right = t_middle;
        }
      }

      cout << "YES\n";
      cout << t_middle << '\n';
      cout << point[0] << ' ' << point[1] << ' ' << point[2] << '\n';
   }
}


Today you are to solve the problem even the famous Hercule Poirot can't cope with! That's why this crime has not yet been solved and this story was never included in Agatha Christie's detective story books. You are not informed on what crime was committed, when and where the corpse was found and other details. We only know that the crime was committed in a house that has n rooms and m doors between the pairs of rooms. The house residents are very suspicious, that's why all the doors can be locked with keys and all the keys are different. According to the provided evidence on Thursday night all the doors in the house were locked, and it is known in what rooms were the residents, and what kind of keys had any one of them. The same is known for the Friday night, when all the doors were also locked. On Friday it was raining heavily, that's why nobody left the house and nobody entered it. During the day the house residents could  open and close doors to the neighboring rooms using the keys at their disposal (every door can be opened and closed from each side);  move freely from a room to a room if a corresponding door is open;  give keys to one another, being in one room.  "Little grey matter" of Hercule Poirot are not capable of coping with such amount of information. Find out if the positions of people and keys on the Thursday night could result in the positions on Friday night, otherwise somebody among the witnesses is surely lying.

The first line contains three preset integers n, m и k (1 ≤ n, m, k ≤ 1000) — the number of rooms, the number of doors and the number of house residents respectively. The next m lines contain pairs of room numbers which join the doors. The rooms are numbered with integers from 1 to n. There cannot be more that one door between the pair of rooms. No door connects a room with itself. The next k lines describe the residents' position on the first night. Every line contains a resident's name (a non-empty line consisting of no more than 10 Latin letters), then after a space follows the room number, then, after a space — the number of keys the resident has. Then follow written space-separated numbers of the doors that can be unlocked by these keys. The doors are numbered with integers from 1 to m in the order in which they are described in the input data. All the residents have different names, uppercase and lowercase letters considered to be different. Every m keys occurs exactly once in the description. Multiple people may be present in one room, some rooms may be empty. The next k lines describe the position of the residents on the second night in the very same format. It is guaranteed that in the second night's description the residents' names remain the same and every m keys occurs exactly once.

Print "YES" (without quotes) if the second arrangement can result from the first one, otherwise, print "NO".

2 1 2
1 2
Dmitry 1 1 1
Natalia 2 0
Natalia 1 1 1
Dmitry 2 0

4 4 3
1 3
1 2
2 3
3 4
Artem 1 1 4
Dmitry 1 1 2
Edvard 4 2 1 3
Artem 2 0
Dmitry 1 0
Edvard 4 4 1 2 3 4

#pragma comment(linker, "/STACK:10000000")

#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <bitset>
#include <sstream>

#include <algorithm>
#include <functional>
#include <numeric>
#include <iostream>

#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <cassert>

using namespace std;

#define forn(i, n) for(int i = 0; i < int(n); ++i)
#define for1(i, n) for(int i = 1; i <= int(n); ++i)
#define ford(i, n) for(int i = int(n) - 1; i >= 0; --i)
#define fore(i, l, r) for(int i = int(l); i < int(r); ++i)
#define sz(v) int((v).size())
#define all(v) (v).begin(), (v).end()
#define pb push_back
#define X first
#define Y second
#define mp make_pair
#define debug(x) {cerr << #x << " = " << x << endl;}
template<typename T> inline T abs(T a){ return ((a < 0) ? -a : a); }
template<typename T> inline T sqr(T a){ return a * a; }

typedef long long li;
typedef long double ld;
typedef pair<int, int> pt;

const int INF = (int)1E9 + 7;
const ld EPS = 1E-9;
const ld PI = 3.1415926535897932384626433832795;

const int NMAX = 2000;
int n, m, k;

vector<int> g[NMAX];
vector<pt> e;

map<string, int> idx;

int pos1[NMAX], pos2[NMAX];
vector<int> key1[NMAX];
vector<int> key2[NMAX];

int c[NMAX];
void init(){
    forn(i, n)
        c[i] = i;
}

int root(int v){
    return c[v] == v ? v : c[v] = root(c[v]);
}

bool join(int a, int b){
    a = root(a), b = root(b);
    if(a == b) return false;
    if(rand() & 1) swap(a, b);
    c[a] = b;
    return true;
}

vector<int> getKeyPos(int* pos, vector<int>* key){
    vector<int> key_pos(m, 0);
    forn(i, k)
        forn(j, sz(key[i]))
            key_pos[key[i][j]] = pos[i];
    return key_pos;
}

vector<int> getColor(int* pos, vector<int>* key){
    vector<int> key_pos = getKeyPos(pos, key);

    init();

    bool was = true;
    while(was){
        was = false;
        forn(i, m){
            int u = e[i].X, v = e[i].Y;
            if(root(u) == root(key_pos[i]) || root(v) == root(key_pos[i])){
                if(join(u, v))
                    was = true;
            }
        }
    }

    vector<int> ans(n);
    map<int, int> clr;
    forn(i, n){
        int cur = root(i);
        if(!clr.count(cur)){
            int val = sz(clr);
            clr[cur] = val;
        }
        ans[i] = clr[cur];
    }
    return ans;
}

int main() {
    //freopen("input.txt", "rt", stdin);
    //freopen("output.txt", "wt", stdout);

    scanf("%d%d%d", &n, &m, &k);
    forn(i, m){
        int u, v;
        scanf("%d%d", &u, &v);
        --u, --v;
        e.pb(pt(u, v));
        g[u].pb(v);
        g[v].pb(u);
    }

    forn(i, k){
        string name;
        cin >> name;
        if(!idx.count(name)){
            int val = sz(idx);
            idx[name] = val;
        }

        scanf("%d", &pos1[idx[name]]);
        pos1[idx[name]]--;
        int cnt;
        scanf("%d", &cnt);
        key1[idx[name]].resize(cnt);
        forn(j, cnt){
            scanf("%d", &key1[idx[name]][j]);
            key1[idx[name]][j]--;
        }
    }

    forn(i, k){
        string name;
        cin >> name;
        if(!idx.count(name)){
            int val = sz(idx);
            idx[name] = val;
        }

        scanf("%d", &pos2[idx[name]]);
        pos2[idx[name]]--;
        int cnt;
        scanf("%d", &cnt);
        key2[idx[name]].resize(cnt);
        forn(j, cnt){
            scanf("%d", &key2[idx[name]][j]);
            key2[idx[name]][j]--;
        }
    }

    vector<int> c1 = getColor(pos1, key1), c2 = getColor(pos2, key2);

    if(c1 != c2){
        puts("NO");
        exit(0);
    }

    forn(i, k){
        if(c1[pos1[i]] != c2[pos2[i]]){
            puts("NO");
            exit(0);
        }
    }

    vector<int> k1 = getKeyPos(pos1, key1), k2 = getKeyPos(pos2, key2);

    forn(i, m)
        if(c1[k1[i]] != c2[k2[i]]){
            puts("NO");
            exit(0);
        }

    puts("YES");
    return 0;
}


Once a walrus professor Plato asked his programming students to perform the following practical task. The students had to implement such a data structure that would support a convex hull on some set of points S. The input to the program had q queries of two types: 1. Add a point with coordinates (x, y) into the set S. Note that in this case the convex hull of S could have changed, and could have remained the same. 2. Say whether a point with coordinates (x, y) belongs to an area limited by the convex hull, including the border. All the students coped with the task. What about you?

The first line contains an integer q (4 ≤ q ≤ 105).  Then follow q lines in the following way: "t x y", where t is the query type (1 or 2), and (x, y) are the coordinates of the point ( - 106 ≤ x, y ≤ 106, x and y are integers).  There is at least one query of type 2. It is guaranteed that the three queries of the first type follow first and the points given in the queries form a non-degenerative triangle. Also all the points added in S are distinct.

For each query of the second type print one string containing "YES", if the point lies inside the convex hull or on its border. Otherwise, print "NO".

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <algorithm>
#include <queue>
#include <assert.h>
#include <cmath>
using namespace std;

#define inf 1000000000
#define eps 1e-9

inline int sgn(double a) {if (a > eps) return 1; else if (a < -eps) return -1; return 0;}

struct point {
    double x, y;
    double ang, l;
    point(double x, double y) : x(x), y(y) {l = len(); if (sgn(x) && sgn(y)) ang = angle();}
    point() {}
    inline void read() {int a, b; scanf("%d%d", &a, &b); x = a, y = b; *this = point(x, y);}
    inline double len() const {return sqrt(x * x + y * y);}
    inline double len2() const {return x * x + y * y;}
    inline double angle() {return atan2(y, x);}
    inline double slope() {return y / x;}
    inline int part() {
        return (int)(y > 0 || (sgn(y) == 0 && x > 0));
    }
    inline void normalize() {
        double r = 1.0 / len();
        x *= r; y *= r;
    }
    inline point getNormal() {
        point ret = *this;
        ret.normalize();
        return ret;
    }
};

inline point operator -(const point &a, const point &b) {return point(a.x - b.x, a.y - b.y);}
inline point operator +(const point &a, const point &b) {return point(a.x + b.x, a.y + b.y);}
inline point operator *(const point &a, double b) {return point(b * a.x, b * a.y);}
inline point operator *(double b, const point &a) {return point(b * a.x, b * a.y);}
inline double operator *(const point &a, const point &b) {return a.x * b.x + a.y * b.y;}
inline double operator %(const point &a, const point &b) {return a.x * b.y - a.y * b.x;}
inline bool operator ==(const point &a, const point &b) {return sgn(a.x - b.x) == 0 && sgn(a.y - b.y) == 0;}
inline bool operator !=(const point &a, const point &b) {return !(a == b);}
inline double dist(const point &a, const point &b) {return (a - b).len();}

bool operator <(point a, point b) {
    if (a.part() != b.part()) return b.part();
    int tmp = sgn(a % b);
    if (tmp) return tmp == 1;
    return a.len() + eps < b.len();
}

int n;

set<point> S;

typedef set<point>::iterator it;

void print() {
    for (it i = S.begin(); i != S.end(); i++) printf("%lf %lf %lf\n", i->x, i->y, i->ang);
}

it getPrev(it p) {
    if (p == S.begin()) p = S.end();
    p--;
    return p;
}

it getNext(it p) {
    p++;
    if (p == S.end()) p = S.begin();
    return p;
}

bool Inside(point p) {
//  print();
    it t1 = S.upper_bound(p);
    if (t1 == S.end()) t1 = S.begin();
    it t0 = getPrev(t1);
//  printf("%lf %lf\n", t0->x, t0->y);
//  printf("%lf %lf\n", t1->x, t1->y);
    return sgn((p - *t0) % (*t1 - *t0)) <= 0;
}

void Insert(point p) {
    if (Inside(p)) return;
    S.insert(p);
    it tmp = S.lower_bound(p);
    if (tmp != S.begin()) {
        tmp--;
        if (sgn(tmp->ang == p.ang)) S.erase(tmp);
    }
    while (true && S.size() > 3) {
        it t0 = getPrev(S.lower_bound(p)), t1 = getPrev(t0);
        if (sgn((*t0 - p) % (*t1 - p)) >= 0) S.erase(t0);
        else break;
    }
    while (true && S.size() > 3) {
        it t0 = getNext(S.lower_bound(p)), t1 = getNext(t0);
        if (sgn((*t0 - p) % (*t1 - p)) <= 0) S.erase(t0);
        else break;
    }
}

int main() {
//  freopen("data.in", "r", stdin);
    scanf("%d", &n);
    point S[3];
    for (int i = 0; i < 3; i++) scanf("%*d"), S[i].read();
    point O = (S[0] + S[1] + S[2]) * (1.0 / 3.0);
    ::S.insert(S[0] - O); ::S.insert(S[1] - O); ::S.insert(S[2] - O);
    n -= 3;
    for (int i = 0; i < n; i++) {
        int ctrl; scanf("%d", &ctrl);
        point p; p.read(); p = p - O;
        if (ctrl == 2) printf("%s\n", Inside(p) ? "YES" : "NO");
        else Insert(p);
    }
    return 0;
}


You are given an array $$$a$$$ consisting of $$$n$$$ integer numbers.You have to color this array in $$$k$$$ colors in such a way that:   Each element of the array should be colored in some color;  For each $$$i$$$ from $$$1$$$ to $$$k$$$ there should be at least one element colored in the $$$i$$$-th color in the array;  For each $$$i$$$ from $$$1$$$ to $$$k$$$ all elements colored in the $$$i$$$-th color should be distinct. Obviously, such coloring might be impossible. In this case, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions above. If there are multiple answers, you can print any.

The first line of the input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 5000$$$) — the length of the array $$$a$$$ and the number of colors, respectively. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 5000$$$) — elements of the array $$$a$$$.

If there is no answer, print "NO". Otherwise print "YES" and any coloring (i.e. numbers $$$c_1, c_2, \dots c_n$$$, where $$$1 \le c_i \le k$$$ and $$$c_i$$$ is the color of the $$$i$$$-th element of the given array) satisfying the conditions described in the problem statement. If there are multiple answers, you can print any.

NoteIn the first example the answer $$$2~ 1~ 2~ 1$$$ is also acceptable.In the second example the answer $$$1~ 1~ 1~ 2~ 2$$$ is also acceptable.There exist other acceptable answers for both examples.

import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 *
 * @author caoash
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        FastScanner in = new FastScanner(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        BArrayKColoring solver = new BArrayKColoring();
        solver.solve(1, in, out);
        out.close();
    }

    static class BArrayKColoring {
        public void solve(int testNumber, FastScanner br, PrintWriter pw) {
            int n = br.nextInt();
            int k = br.nextInt();
            Pair[] data = new Pair[n];
            for (int i = 0; i < data.length; i++) {
                data[i] = new Pair(br.nextInt(), i);
            }
            Arrays.sort(data);
            int[] fin = new int[n];
            int curr = 1;
            for (int i = 0; i < n; i++) {
                fin[i] = curr++;
                if (curr == k + 1) {
                    curr = 1;
                }
            }
            int[] ret = new int[n];
            boolean[][] used = new boolean[5001][5001];
            for (int i = 0; i < n; i++) {
                ret[data[i].s] = fin[i];
            }
//        for(int i = 0; i < n; i++){
//            pw.print(ret[i] + " ");
//        }
//        pw.println();
            for (int i = 0; i < n; i++) {
                if (used[data[i].f][fin[i]]) {
                    pw.println("NO");
                    pw.close();
                    return;
                } else {
                    used[data[i].f][fin[i]] = true;
                }
            }
            pw.println("YES");
            for (int i = 0; i < n; i++) {
                pw.print(ret[i] + " ");
            }
            pw.close();
        }

    }

    static class Pair implements Comparable<Pair> {
        public int f;
        public int s;

        public Pair(int f, int s) {
            this.f = f;
            this.s = s;
        }

        public int compareTo(Pair p) {
            return this.f == p.f ? this.s - p.s : this.f - p.f;
        }

        public String toString() {
            return "(" + f + "," + s + ")";
        }

    }

    static class FastScanner {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private FastScanner.SpaceCharFilter filter;

        public FastScanner(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1) {
                throw new InputMismatchException();
            }
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0) {
                    return -1;
                }
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c)) {
                c = read();
            }
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9') {
                    throw new InputMismatchException();
                }
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c) {
            if (filter != null) {
                return filter.isSpaceChar(c);
            }
            return isWhitespace(c);
        }

        public static boolean isWhitespace(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public interface SpaceCharFilter {
            public boolean isSpaceChar(int ch);

        }

    }
}


The only difference between easy and hard versions is constraints.The BerTV channel every day broadcasts one episode of one of the $$$k$$$ TV shows. You know the schedule for the next $$$n$$$ days: a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the show, the episode of which will be shown in $$$i$$$-th day.The subscription to the show is bought for the entire show (i.e. for all its episodes), for each show the subscription is bought separately.How many minimum subscriptions do you need to buy in order to have the opportunity to watch episodes of purchased shows $$$d$$$ ($$$1 \le d \le n$$$) days in a row? In other words, you want to buy the minimum number of TV shows so that there is some segment of $$$d$$$ consecutive days in which all episodes belong to the purchased shows.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ test case descriptions follow. The first line of each test case contains three integers $$$n, k$$$ and $$$d$$$ ($$$1 \le n \le 100$$$, $$$1 \le k \le 100$$$, $$$1 \le d \le n$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the show that is broadcasted on the $$$i$$$-th day. It is guaranteed that the sum of the values of $$$n$$$ for all test cases in the input does not exceed $$$100$$$.

Print $$$t$$$ integers — the answers to the test cases in the input in the order they follow. The answer to a test case is the minimum number of TV shows for which you need to purchase a subscription so that you can watch episodes of the purchased TV shows on BerTV for $$$d$$$ consecutive days. Please note that it is permissible that you will be able to watch more than $$$d$$$ days in a row.

NoteIn the first test case to have an opportunity to watch shows for two consecutive days, you need to buy a subscription on show $$$1$$$ and on show $$$2$$$. So the answer is two.In the second test case, you can buy a subscription to any show because for each show you can find a segment of three consecutive days, consisting only of episodes of this show.In the third test case in the unique segment of four days, you have four different shows, so you need to buy a subscription to all these four shows.In the fourth test case, you can buy subscriptions to shows $$$3,5,7,8,9$$$, and you will be able to watch shows for the last eight days.

import java.util.*;
import java.io.*;

public class Main {

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

        public long nextLong() {
            return Long.parseLong(next());
        }

        public char nextChar() {
            return next().charAt(0);
        }

        public float nextFloat() {
            return Float.parseFloat(next());
        }

        public double nextDouble() {
            return Double.parseDouble(next());
        }

        public int[] nextIntArray(int n) {
            int[] intArray = new int[n];
            for (int i = 0; i < n; i++) {
                intArray[i] = nextInt();
            }
            return intArray;
        }
    }

    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        Task solver = new Task();
        solver.solve(1, in, out);
        out.close();
    }

    static class Task {

        public static int q, n, k, d;
        public static int[] N = new int[200005];
        public static int[] check = new int[1000005];

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int q = in.nextInt();
            while (q-- > 0) {
                n = in.nextInt();
                k = in.nextInt();
                d = in.nextInt();
                int count = 0;
                int mi = Integer.MAX_VALUE;
                for (int i = 0; i < d - 1; i++) {
                    N[i] = in.nextInt() - 1;
                    if (check[N[i]] == 0) {
                        count++;
                    }
                    check[N[i]]++;
                }
                for (int i = d - 1; i < n; i++) {
                    N[i] = in.nextInt() - 1;
                    if (check[N[i]] == 0) {
                        count++;
                    }
                    check[N[i]]++;
                    if (count < mi) {
                        mi = count;
                    }
                    if (check[N[i - d + 1]] == 1) {
                        count--;
                    }
                    check[N[i - d + 1]]--;
                }
                out.println(mi);
                for (int i = n - d + 1; i < n; i++) {
                    check[N[i]]--;
                }
            }
        }
    }
}


Dawid has four bags of candies. The $$$i$$$-th of them contains $$$a_i$$$ candies. Also, Dawid has two friends. He wants to give each bag to one of his two friends. Is it possible to distribute the bags in such a way that each friend receives the same amount of candies in total?Note, that you can't keep bags for yourself or throw them away, each bag should be given to one of the friends.

The only line contains four integers $$$a_1$$$, $$$a_2$$$, $$$a_3$$$ and $$$a_4$$$ ($$$1 \leq a_i \leq 100$$$) — the numbers of candies in each bag.

Output YES if it's possible to give the bags to Dawid's friends so that both friends receive the same amount of candies, or NO otherwise. Each character can be printed in any case (either uppercase or lowercase).

NoteIn the first sample test, Dawid can give the first and the third bag to the first friend, and the second and the fourth bag to the second friend. This way, each friend will receive $$$12$$$ candies.In the second sample test, it's impossible to distribute the bags.

import java.util.*;
import java.io.*;
public class Main
{
    public static void main(String args[])throws IOException
    {
        BufferedReader obj=new BufferedReader(new InputStreamReader(System.in));
        String temp[]=obj.readLine().split(" ");
        int arr[]=new int[temp.length];
        long total=0;
        for(int i=0;i<temp.length;i++)
        {
            arr[i]=Integer.parseInt(temp[i]);
            total+=arr[i];
        }
        if(total%2!=0)
        {System.out.println("NO");
        return;
        }
        if(possible(arr,total))
        System.out.println("YES");
        else
        System.out.println("NO");
    }
    public static boolean possible(int[] arr,long total)throws IOException
    {
        int n = arr.length;

        // Run a loop for printing all 2^n
        // subsets one by obe
        for (int i = 0; i < (1<<n); i++)
        {
            long sum=0;
            // Print current subset
            for (int j = 0; j < n; j++)
                {
                if ((i & (1 << j)) > 0)
                    sum+=arr[j];
                 }
            if(total==2*sum)
            return true;
    }
    return false;
    }
}


A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, the strings "kek", "abacaba", "r" and "papicipap" are palindromes, while the strings "abb" and "iq" are not.A substring $$$s[l \ldots r]$$$ ($$$1 \leq l \leq r \leq |s|$$$) of a string $$$s = s_{1}s_{2} \ldots s_{|s|}$$$ is the string $$$s_{l}s_{l + 1} \ldots s_{r}$$$.Anna does not like palindromes, so she makes her friends call her Ann. She also changes all the words she reads in a similar way. Namely, each word $$$s$$$ is changed into its longest substring that is not a palindrome. If all the substrings of $$$s$$$ are palindromes, she skips the word at all.Some time ago Ann read the word $$$s$$$. What is the word she changed it into?

The first line contains a non-empty string $$$s$$$ with length at most $$$50$$$ characters, containing lowercase English letters only.

If there is such a substring in $$$s$$$ that is not a palindrome, print the maximum length of such a substring. Otherwise print $$$0$$$. Note that there can be multiple longest substrings that are not palindromes, but their length is unique.

Note"mew" is not a palindrome, so the longest substring of it that is not a palindrome, is the string "mew" itself. Thus, the answer for the first example is $$$3$$$.The string "uffuw" is one of the longest non-palindrome substrings (of length $$$5$$$) of the string "wuffuw", so the answer for the second example is $$$5$$$.All substrings of the string "qqqqqqqq" consist of equal characters so they are palindromes. This way, there are no non-palindrome substrings. Thus, the answer for the third example is $$$0$$$.

import java.util.HashSet;
import java.util.Scanner;

public class Nafis {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        int sz = str.length();
        HashSet<Character> freq = new HashSet<>();
        for (int i = 0; i <= sz / 2; i++) {
            if (str.charAt(i) == str.charAt(sz - i - 1)) {
                freq.add(str.charAt(i));
                continue;
            } else {
                System.out.println(sz);
                return;
            }
        }

        System.out.println(freq.size() == 1 ? 0 : sz - 1);

    }
}

[{'input': 'mew\r\n', 'output': ['3']}, {'input': 'wuffuw\r\n', 'output': ['5']}, {'input': 'qqqqqqqq\r\n', 'output': ['0']}, {'input': 'ijvji\r\n', 'output': ['4']}, {'input': 'iiiiiii\r\n', 'output': ['0']}, {'input': 'wobervhvvkihcuyjtmqhaaigvvgiaahqmtjyuchikvvhvrebow\r\n', 'output': ['49']}, {'input': 'wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww\r\n', 'output': ['0']}, {'input': 'wobervhvvkihcuyjtmqhaaigvahheoqleromusrartldojsjvy\r\n', 'output': ['50']}, {'input': 'ijvxljt\r\n', 'output': ['7']}, {'input': 'fyhcncnchyf\r\n', 'output': ['10']}, {'input': 'ffffffffffff\r\n', 'output': ['0']}, {'input': 'fyhcncfsepqj\r\n', 'output': ['12']}, {'input': 'ybejrrlbcinttnicblrrjeby\r\n', 'output': ['23']}, {'input': 'yyyyyyyyyyyyyyyyyyyyyyyyy\r\n', 'output': ['0']}, {'input': 'ybejrrlbcintahovgjddrqatv\r\n', 'output': ['25']}, {'input': 'oftmhcmclgyqaojljoaqyglcmchmtfo\r\n', 'output': ['30']}, {'input': 'oooooooooooooooooooooooooooooooo\r\n', 'output': ['0']}, {'input': 'oftmhcmclgyqaojllbotztajglsmcilv\r\n', 'output': ['32']}, {'input': 'gxandbtgpbknxvnkjaajknvxnkbpgtbdnaxg\r\n', 'output': ['35']}, {'input': 'gggggggggggggggggggggggggggggggggggg\r\n', 'output': ['0']}, {'input': 'gxandbtgpbknxvnkjaygommzqitqzjfalfkk\r\n', 'output': ['36']}, {'input': 'fcliblymyqckxvieotjooojtoeivxkcqymylbilcf\r\n', 'output': ['40']}, {'input': 'fffffffffffffffffffffffffffffffffffffffffff\r\n', 'output': ['0']}, {'input': 'fcliblymyqckxvieotjootiqwtyznhhvuhbaixwqnsy\r\n', 'output': ['43']}, {'input': 'rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr\r\n', 'output': ['0']}, {'input': 'rajccqwqnqmshmerpvjyfepxwpxyldzpzhctqjnstxyfmlhiy\r\n', 'output': ['49']}, {'input': 'a\r\n', 'output': ['0']}, {'input': 'abca\r\n', 'output': ['4']}, {'input': 'aaaaabaaaaa\r\n', 'output': ['10']}, {'input': 'aba\r\n', 'output': ['2']}, {'input': 'asaa\r\n', 'output': ['4']}, {'input': 'aabaa\r\n', 'output': ['4']}, {'input': 'aabbaa\r\n', 'output': ['5']}, {'input': 'abcdaaa\r\n', 'output': ['7']}, {'input': 'aaholaa\r\n', 'output': ['7']}, {'input': 'abcdefghijka\r\n', 'output': ['12']}, {'input': 'aaadcba\r\n', 'output': ['7']}, {'input': 'aaaabaaaa\r\n', 'output': ['8']}, {'input': 'abaa\r\n', 'output': ['4']}, {'input': 'abcbaa\r\n', 'output': ['6']}, {'input': 'ab\r\n', 'output': ['2']}, {'input': 'l\r\n', 'output': ['0']}, {'input': 'aaaabcaaaa\r\n', 'output': ['10']}, {'input': 'abbaaaaaabba\r\n', 'output': ['11']}, {'input': 'abaaa\r\n', 'output': ['5']}, {'input': 'baa\r\n', 'output': ['3']}, {'input': 'aaaaaaabbba\r\n', 'output': ['11']}, {'input': 'ccbcc\r\n', 'output': ['4']}, {'input': 'bbbaaab\r\n', 'output': ['7']}, {'input': 'abaaaaaaaa\r\n', 'output': ['10']}, {'input': 'abaaba\r\n', 'output': ['5']}, {'input': 'aabsdfaaaa\r\n', 'output': ['10']}, {'input': 'aaaba\r\n', 'output': ['5']}, {'input': 'aaabaaa\r\n', 'output': ['6']}, {'input': 'baaabbb\r\n', 'output': ['7']}, {'input': 'ccbbabbcc\r\n', 'output': ['8']}, {'input': 'cabc\r\n', 'output': ['4']}, {'input': 'aabcd\r\n', 'output': ['5']}, {'input': 'abcdea\r\n', 'output': ['6']}, {'input': 'bbabb\r\n', 'output': ['4']}, {'input': 'aaaaabababaaaaa\r\n', 'output': ['14']}, {'input': 'bbabbb\r\n', 'output': ['6']}, {'input': 'aababd\r\n', 'output': ['6']}, {'input': 'abaaaa\r\n', 'output': ['6']}, {'input': 'aaaaaaaabbba\r\n', 'output': ['12']}, {'input': 'aabca\r\n', 'output': ['5']}, {'input': 'aaabccbaaa\r\n', 'output': ['9']}, {'input': 'aaaaaaaaaaaaaaaaaaaab\r\n', 'output': ['21']}, {'input': 'babb\r\n', 'output': ['4']}, {'input': 'abcaa\r\n', 'output': ['5']}, {'input': 'qwqq\r\n', 'output': ['4']}, {'input': 'aaaaaaaaaaabbbbbbbbbbbbbbbaaaaaaaaaaaaaaaaaaaaaa\r\n', 'output': ['48']}, {'input': 'aaab\r\n', 'output': ['4']}, {'input': 'aaaaaabaaaaa\r\n', 'output': ['12']}, {'input': 'wwuww\r\n', 'output': ['4']}, {'input': 'aaaaabcbaaaaa\r\n', 'output': ['12']}, {'input': 'aaabbbaaa\r\n', 'output': ['8']}, {'input': 'aabcbaa\r\n', 'output': ['6']}, {'input': 'abccdefccba\r\n', 'output': ['11']}, {'input': 'aabbcbbaa\r\n', 'output': ['8']}, {'input': 'aaaabbaaaa\r\n', 'output': ['9']}, {'input': 'aabcda\r\n', 'output': ['6']}, {'input': 'abbca\r\n', 'output': ['5']}, {'input': 'aaaaaabbaaa\r\n', 'output': ['11']}, {'input': 'sssssspssssss\r\n', 'output': ['12']}, {'input': 'sdnmsdcs\r\n', 'output': ['8']}, {'input': 'aaabbbccbbbaaa\r\n', 'output': ['13']}, {'input': 'cbdbdc\r\n', 'output': ['6']}, {'input': 'abb\r\n', 'output': ['3']}, {'input': 'abcdefaaaa\r\n', 'output': ['10']}, {'input': 'abbbaaa\r\n', 'output': ['7']}, {'input': 'v\r\n', 'output': ['0']}, {'input': 'abccbba\r\n', 'output': ['7']}, {'input': 'axyza\r\n', 'output': ['5']}, {'input': 'abcdefgaaaa\r\n', 'output': ['11']}, {'input': 'aaabcdaaa\r\n', 'output': ['9']}, {'input': 'aaaacaaaa\r\n', 'output': ['8']}, {'input': 'aaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaa\r\n', 'output': ['42']}, {'input': 'abbbaa\r\n', 'output': ['6']}, {'input': 'abcdee\r\n', 'output': ['6']}, {'input': 'oom\r\n', 'output': ['3']}, {'input': 'aabcaa\r\n', 'output': ['6']}, {'input': 'abba\r\n', 'output': ['3']}, {'input': 'aaca\r\n', 'output': ['4']}, {'input': 'aacbca\r\n', 'output': ['6']}, {'input': 'ababa\r\n', 'output': ['4']}, {'input': 'abcda\r\n', 'output': ['5']}, {'input': 'cccaaccc\r\n', 'output': ['7']}, {'input': 'aaabcda\r\n', 'output': ['7']}, {'input': 'aa\r\n', 'output': ['0']}, {'input': 'aabaaaa\r\n', 'output': ['7']}, {'input': 'abbaaaa\r\n', 'output': ['7']}, {'input': 'aaabcbaaa\r\n', 'output': ['8']}, {'input': 'aabba\r\n', 'output': ['5']}, {'input': 'xyxx\r\n', 'output': ['4']}, {'input': 'aaaaaaaaaaaabc\r\n', 'output': ['14']}, {'input': 'bbaaaabb\r\n', 'output': ['7']}, {'input': 'aaabaa\r\n', 'output': ['6']}, {'input': 'sssssabsssss\r\n', 'output': ['12']}, {'input': 'bbbaaaabbb\r\n', 'output': ['9']}, {'input': 'abbbbaaaa\r\n', 'output': ['9']}, {'input': 'wwufuww\r\n', 'output': ['6']}, {'input': 'oowoo\r\n', 'output': ['4']}, {'input': 'cccaccc\r\n', 'output': ['6']}, {'input': 'aaa\r\n', 'output': ['0']}, {'input': 'bbbcc\r\n', 'output': ['5']}, {'input': 'abcdef\r\n', 'output': ['6']}, {'input': 'abbba\r\n', 'output': ['4']}, {'input': 'aab\r\n', 'output': ['3']}, {'input': 'aaba\r\n', 'output': ['4']}, {'input': 'azbyaaa\r\n', 'output': ['7']}, {'input': 'oooooiooooo\r\n', 'output': ['10']}, {'input': 'aabbbbbaaaaaa\r\n', 'output': ['13']}]


Kirill plays a new computer game. He came to the potion store where he can buy any potion. Each potion is characterized by two integers — amount of experience and cost. The efficiency of a potion is the ratio of the amount of experience to the cost. Efficiency may be a non-integer number.For each two integer numbers a and b such that l ≤ a ≤ r and x ≤ b ≤ y there is a potion with experience a and cost b in the store (that is, there are (r - l + 1)·(y - x + 1) potions).Kirill wants to buy a potion which has efficiency k. Will he be able to do this?

First string contains five integer numbers l, r, x, y, k (1 ≤ l ≤ r ≤ 107, 1 ≤ x ≤ y ≤ 107, 1 ≤ k ≤ 107).

Print "YES" without quotes if a potion with efficiency exactly k can be bought in the store and "NO" without quotes otherwise. You can output each of the letters in any register.

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
public class Ideone
{
	public static void main (String[] args) throws java.lang.Exception
	{
		// your code goes here
		Scanner scan=new Scanner(System.in);
		int l=scan.nextInt();
		int r=scan.nextInt();
		int x=scan.nextInt();
		int y=scan.nextInt();
		long k=scan.nextInt();
        for(int i=x;i<=y;i++)
            if(k*i>=l&&k*i<=r){System.out.println("YES");return;}

        System.out.println("NO");

	}
}


Calculate the minimum number of characters you need to change in the string s, so that it contains at least k different letters, or print that it is impossible.String s consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.

First line of input contains string s, consisting only of lowercase Latin letters (1 ≤ |s| ≤ 1000, |s| denotes the length of s). Second line of input contains integer k (1 ≤ k ≤ 26).

Print single line with a minimum number of necessary changes, or the word «impossible» (without quotes) if it is impossible.

NoteIn the first test case string contains 6 different letters, so we don't need to change anything.In the second test case string contains 4 different letters: {'a', 'h', 'o', 'y'}. To get 5 different letters it is necessary to change one occurrence of 'o' to some letter, which doesn't occur in the string, for example, {'b'}.In the third test case, it is impossible to make 7 different letters because the length of the string is 6.

import java.util.*;
import java.io.*;

public class Solution {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);

        String str = scan.next();
        int n = str.length();
        int k = scan.nextInt();
        if(k == 1)
        	System.out.println(0);
        else{
	        HashSet<Character> set = new HashSet<Character>();
		    for(int i = 0; i < n; i++)
		    	set.add(str.charAt(i));
		    int res = (k-set.size());
		    if(k > n)
		    	System.out.println("impossible");
		    else if(res >= 0)
		    	System.out.println(res);
		    else
		    	System.out.println(0);
	  	}
		scan.close();
	}
}

[{'input': 'yandex\r\n6\r\n', 'output': ['0\r\n']}, {'input': 'yahoo\r\n5\r\n', 'output': ['1\r\n']}, {'input': 'google\r\n7\r\n', 'output': ['impossible\r\n']}, {'input': 'a\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'z\r\n2\r\n', 'output': ['impossible\r\n']}, {'input': 'fwgfrwgkuwghfiruhewgirueguhergiqrbvgrgf\r\n26\r\n', 'output': ['14\r\n']}, {'input': 'nfevghreuoghrueighoqghbnebvnejbvnbgneluqe\r\n26\r\n', 'output': ['12\r\n']}, {'input': 'a\r\n3\r\n', 'output': ['impossible\r\n']}, {'input': 'smaxpqplaqqbxuqxalqmbmmgubbpspxhawbxsuqhhegpmmpebqmqpbbeplwaepxmsahuepuhuhwxeqmmlgqubuaxehwuwasgxpqmugbmuawuhwqlswllssueglbxepbmwgs\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'cuguccgcugcugucgggggcgcgucgucugcuuuccccuugccg\r\n4\r\n', 'output': ['1\r\n']}, {'input': 'fcfccfcfccfcfcffcffffffcfccfccfcffccccfcffffccfccfcffcfcccccffcfffcccffcfccfffffcccfccffffffccfccccf\r\n20\r\n', 'output': ['18\r\n']}, {'input': 'swmkwaruyv\r\n5\r\n', 'output': ['0\r\n']}, {'input': 'tnbqpsuhkczmejirvyfdolxwga\r\n22\r\n', 'output': ['0\r\n']}, {'input': 'abcde\r\n3\r\n', 'output': ['0\r\n']}, {'input': 'abb\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'aaaa\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'abcde\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'yandex\r\n4\r\n', 'output': ['0\r\n']}, {'input': 'aaabbbccc\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'abcd\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'asdfgh\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'aab\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'mynameissako\r\n5\r\n', 'output': ['0\r\n']}, {'input': 'abcde\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'abcd\r\n3\r\n', 'output': ['0\r\n']}, {'input': 'abcdef\r\n2\r\n', 'output': ['0\r\n']}, {'input': 'abcdefg\r\n4\r\n', 'output': ['0\r\n']}, {'input': 'abc\r\n1\r\n', 'output': ['0\r\n']}, {'input': 'asdafjsgljdllgjdgkl\r\n5\r\n', 'output': ['0\r\n']}, {'input': 'yaay\r\n3\r\n', 'output': ['1\r\n']}, {'input': 'yaay\r\n4\r\n', 'output': ['2\r\n']}, {'input': 'zzzzzz\r\n2\r\n', 'output': ['1\r\n']}]


Your friend recently gave you some slimes for your birthday. You have n slimes all initially with value 1.You are going to play a game with these slimes. Initially, you put a single slime by itself in a row. Then, you will add the other n - 1 slimes one by one. When you add a slime, you place it at the right of all already placed slimes. Then, while the last two slimes in the row have the same value v, you combine them together to create a slime with value v + 1.You would like to see what the final state of the row is after you've added all n slimes. Please print the values of the slimes in the row from left to right.

The first line of the input will contain a single integer, n (1 ≤ n ≤ 100 000).

Output a single line with k integers, where k is the number of slimes in the row after you've finished the procedure described in the problem statement. The i-th of these numbers should be the value of the i-th slime from the left.

NoteIn the first sample, we only have a single slime with value 1. The final state of the board is just a single slime with value 1.In the second sample, we perform the following steps:Initially we place a single slime in a row by itself. Thus, row is initially 1.Then, we will add another slime. The row is now 1 1. Since two rightmost slimes have the same values, we should replace these slimes with one with value 2. Thus, the final state of the board is 2.In the third sample, after adding the first two slimes, our row is 2. After adding one more slime, the row becomes 2 1.In the last sample, the steps look as follows:   1  2  2 1  3  3 1  3 2  3 2 1  4

import java.lang.*;
import java.util.*;
import java.io.*;
public class test
{

  Scanner sc=new Scanner(System.in);
  PrintWriter pr=new PrintWriter(System.out,true);
  public static void main(String... args)
  {
       test c=new test();
       c.prop();
  }
  public void prop()
  {
    int n,count=1 ;
    Stack<Integer> s=new Stack<Integer>();
     s.push(0);
      n=sc.nextInt();
        for (int i=1; ;++i) {
            if(n%2==0)
            {
              ++count ;
              n=n/2 ;
            }else
              {
                s.push(count);
                n=n-1 ;
              }
            if(n==0)
             break ;
        }
       for (; ; ) {
          n=s.pop();
            if(n==0)
              break ;
            else
              pr.print(n+" ");
       }
      pr.println("");

  }
}


Little Chris knows there's no fun in playing dominoes, he thinks it's too random and doesn't require skill. Instead, he decided to play with the dominoes and make a "domino show".Chris arranges n dominoes in a line, placing each piece vertically upright. In the beginning, he simultaneously pushes some of the dominoes either to the left or to the right. However, somewhere between every two dominoes pushed in the same direction there is at least one domino pushed in the opposite direction.After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. The figure shows one possible example of the process.  Given the initial directions Chris has pushed the dominoes, find the number of the dominoes left standing vertically at the end of the process!

The first line contains a single integer n (1 ≤ n ≤ 3000), the number of the dominoes in the line. The next line contains a character string s of length n. The i-th character of the string si is equal to    "L", if the i-th domino has been pushed to the left;  "R", if the i-th domino has been pushed to the right;  ".", if the i-th domino has not been pushed.  It is guaranteed that if si = sj = "L" and i < j, then there exists such k that i < k < j and sk = "R"; if si = sj = "R" and i < j, then there exists such k that i < k < j and sk = "L".

Output a single integer, the number of the dominoes that remain vertical at the end of the process.

NoteThe first example case is shown on the figure. The four pieces that remain standing vertically are highlighted with orange.In the second example case, all pieces fall down since the first piece topples all the other pieces.In the last example case, a single piece has not been pushed in either direction.

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int size = Integer.parseInt(scanner.nextLine());
        String input = scanner.nextLine();

        boolean lastLeft = true;
        int numStanding = 0;
        int counter = 0;

        for (int i = 0; i < input.length(); i++) {
            switch (input.charAt(i)) {
                case 'L':
                    // Special case cause starts with left
                    if (!lastLeft) {
                        numStanding += (counter%2); // Add one if odd
                    }
                    counter = 0;
                    lastLeft = true;
                    break;
                case 'R':
                    numStanding += counter;
                    counter = 0;
                    lastLeft = false;
                    break;
                case '.':
                    counter++;
                    break;
                default:
            }
        }

        if (lastLeft) {
            numStanding += counter;
        }

        System.out.println(numStanding);
    }
}


"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.You are given an arbitrary sequence a1, a2, ..., an containing n integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).

The first line of the input data contains an integer n (1 ≤ n ≤ 5000) which represents how many numbers are in the sequence. The second line contains a sequence of integers ai (1 ≤ ai ≤ 5000, 1 ≤ i ≤ n).

Print the only number — the minimum number of changes needed to get the permutation.

NoteThe first sample contains the permutation, which is why no replacements are required.In the second sample it is enough to replace the first element with the number 1 and that will make the sequence the needed permutation.In the third sample we can replace the second element with number 4 and the fourth element with number 2.

import java.io.IOException;
import java.io.InputStream;
import java.util.InputMismatchException;

public class Task4 {
    static class FastScanner{
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;

        public FastScanner()
        {
            stream = System.in;
        }

        int read()
        {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars){
                curChar = 0;
                try{
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        boolean isSpaceChar(int c)
        {
            return c==' '||c=='\n'||c=='\r'||c=='\t'||c==-1;
        }

        boolean isEndline(int c)
        {
            return c=='\n'||c=='\r'||c==-1;
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String next(){
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do{
                res.appendCodePoint(c);
                c = read();
            }while(!isSpaceChar(c));
            return res.toString();
        }

        String nextLine(){
            int c = read();
            while (isEndline(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do{
                res.appendCodePoint(c);
                c = read();
            }while(!isEndline(c));
            return res.toString();
        }
    }

    public static void main(String[] args) {
        FastScanner in = new FastScanner();
        byte vis[] =new byte[5005];
            int n = in.nextInt();

            int ans = 0;
            int t;
            for(int i=0;i<n;i++)
            {
                t= in.nextInt();
                if(t > n || vis[t]!=0)
                    ans++;
                else
                    vis[t] = 1;
            }
          System.out.println(ans);

    }

}


«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine.However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and she was fighting them off. Every k-th dragon got punched in the face with a frying pan. Every l-th dragon got his tail shut into the balcony door. Every m-th dragon got his paws trampled with sharp heels. Finally, she threatened every n-th dragon to call her mom, and he withdrew in panic.How many imaginary dragons suffered moral or physical damage tonight, if the princess counted a total of d dragons?

Input data contains integer numbers k, l, m, n and d, each number in a separate line (1 ≤ k, l, m, n ≤ 10, 1 ≤ d ≤ 105).

NoteIn the first case every first dragon got punched with a frying pan. Some of the dragons suffered from other reasons as well, but the pan alone would be enough.In the second case dragons 1, 7, 11, 13, 17, 19 and 23 escaped unharmed.

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner scn=new Scanner(System.in);
        int k=scn.nextInt();
        int l=scn.nextInt();
        int m=scn.nextInt();
        int n=scn.nextInt();
        int d=scn.nextInt();
        int arr[]=new int[d+1];
        for(int i=k;i<arr.length;i+=k) {
            arr[i]=1;
        }
        for(int i=l;i<arr.length;i+=l) {
            arr[i]=1;
        }
        for(int i=m;i<arr.length;i+=m) {
            arr[i]=1;
        }
        for(int i=n;i<arr.length;i+=n) {
            arr[i]=1;
        }
        int ans=0;
        for(int i=1;i<arr.length;i++) {
            if(arr[i]==1)
                ans++;
        }
        System.out.println(ans);
    }
}


One day little Vasya found mom's pocket book. The book had n names of her friends and unusually enough, each name was exactly m letters long. Let's number the names from 1 to n in the order in which they are written.As mom wasn't home, Vasya decided to play with names: he chose three integers i, j, k (1 ≤ i < j ≤ n, 1 ≤ k ≤ m), then he took names number i and j and swapped their prefixes of length k. For example, if we take names "CBDAD" and "AABRD" and swap their prefixes with the length of 3, the result will be names "AABAD" and "CBDRD".You wonder how many different names Vasya can write instead of name number 1, if Vasya is allowed to perform any number of the described actions. As Vasya performs each action, he chooses numbers i, j, k independently from the previous moves and his choice is based entirely on his will. The sought number can be very large, so you should only find it modulo 1000000007 (109 + 7).

The first input line contains two integers n and m (1 ≤ n, m ≤ 100) — the number of names and the length of each name, correspondingly. Then n lines contain names, each name consists of exactly m uppercase Latin letters.

Print the single number — the number of different names that could end up in position number 1 in the pocket book after the applying the procedures described above. Print the number modulo 1000000007 (109 + 7).

NoteIn the first sample Vasya can get the following names in the position number 1: "AAB", "AAA", "BAA" and "BAB".

import java.io.*;
import java.util.*;

public class C
{

	public static void main(String[] args)throws IOException
	{
		BufferedReader ob = new BufferedReader(new InputStreamReader(System.in));
		StringBuffer sb = new StringBuffer();

		String s[]=ob.readLine().split(" ");
		int n=Integer.parseInt(s[0]);
		long mod = 1000000007L;
		int m=Integer.parseInt(s[1]);
		long ans = 1;
		HashSet<Character> set[] = new HashSet[m];
		for(int i = 0;i < m;i++)
			set[i] = new HashSet<>();
		for(int i = 0;i < n;i++)
		{
			String str=ob.readLine();
			for(int j = 0;j < m;j++)
				set[j].add(str.charAt(j));
		}
		for(int i = 0;i < m;i++)
		{
//			System.out.println("size = "+set[i].size());
			ans*=set[i].size();
			ans%=mod;
		}
		System.out.println(ans);

	}

}

[{'input': '2 3\r\nAAB\r\nBAA\r\n', 'output': ['4\r\n']}, {'input': '4 5\r\nABABA\r\nBCGDG\r\nAAAAA\r\nYABSA\r\n', 'output': ['216\r\n']}, {'input': '1 1\r\nE\r\n', 'output': ['1\r\n']}, {'input': '2 2\r\nNS\r\nPD\r\n', 'output': ['4\r\n']}, {'input': '3 4\r\nPJKD\r\nNFJX\r\nFGFK\r\n', 'output': ['81\r\n']}, {'input': '4 5\r\nSXFMY\r\nATHLM\r\nKDDQW\r\nZWGDS\r\n', 'output': ['1024\r\n']}, {'input': '20 14\r\nJNFKBBBJYZHWQE\r\nLBOKZCPFNKDBJY\r\nXKNWGHQHIOXUPF\r\nDDNRUKVUGHWMXW\r\nMTIZFNAAFEAPHX\r\nIXBQOOHEULZYHU\r\nMRCSREUEOOMUUN\r\nHJTSQWKUFYZDQU\r\nGMCMUZCOPRVEIQ\r\nXBKKGGJECOBLTH\r\nXXHTLXCNJZJUAF\r\nVLJRKXXXWMTPKZ\r\nPTYMNPTBBCWKAD\r\nQYJGOBUBHMEDYE\r\nGTKUUVVNKAHTUI\r\nZNKXYZPCYLBZFP\r\nQCBLJTRMBDWNNE\r\nTDOKJOBKEOVNLZ\r\nFKZUITYAFJOQIM\r\nUWQNSGLXEEIRWF\r\n', 'output': ['515139391\r\n']}, {'input': '5 14\r\nAQRXUQQNSKZPGC\r\nDTTKSPFGGVCLPT\r\nVLZQWWESCHDTAZ\r\nCOKOWDWDRUOMHP\r\nXDTRBIZTTCIDGS\r\n', 'output': ['124999979\r\n']}, {'input': '9 23\r\nOILBYKHRGMPENVFNHLSIUOW\r\nLPJFHTUQUINAALRDGLSQUXR\r\nLYYJJEBNZATAFQWTDZSPUNZ\r\nHSJPIQKKWWERJZIEMLCZUKI\r\nOJYIEYDGPFWRHCMISJCCUEM\r\nLMGKZVFYIVDRTIHBWPCNUTG\r\nUBGGNCITVHAIPKXCLTSAULQ\r\nOWSAWUOXQDBSXXBHTLSXUVD\r\nUGQTIZQPBGMASRQPVPSFUWK\r\n', 'output': ['454717784\r\n']}, {'input': '25 4\r\nLVKG\r\nMICU\r\nZHKW\r\nLFGG\r\nOWQO\r\nLCQG\r\nLVXU\r\nOUKB\r\nLNQX\r\nZJTO\r\nOOQX\r\nLVQP\r\nMFQB\r\nMRQV\r\nOIQH\r\nOPXX\r\nXFKU\r\nFCQB\r\nZPKH\r\nLVCH\r\nNFCU\r\nOVQW\r\nOZKU\r\nLFHX\r\nLPXO\r\n', 'output': ['5733\r\n']}, {'input': '30 10\r\nUTNTGOKZYJ\r\nQHOUHNYZVW\r\nLTVGHJRZVW\r\nMZHYHOLZYJ\r\nERYEUEPZYE\r\nUZDBFTURYJ\r\nRVSMQTIZGW\r\nWDJQHMIRYY\r\nKCORHQPZYE\r\nRRPLFOZZVY\r\nJTXMFNNNYJ\r\nMVTGGOZZVV\r\nEHAFFNUZVF\r\nLBRNWJZNYE\r\nJVMOHTPZYJ\r\nWTARFJLZVV\r\nLVJCWOURVW\r\nLCLQFJYRVV\r\nQVBVGNJRYF\r\nNTZGHOLRYE\r\nMGQKHOUPYJ\r\nRRSSBXPZYJ\r\nRYCRGTLZYJ\r\nJRDEGNKRVW\r\nRZKFGHYRVG\r\nMDJBFNIZYG\r\nMPLWHXIZYE\r\nSRZMHMURVE\r\nMTEBBMRZYJ\r\nJPJIFOLZYM\r\n', 'output': ['919913906\r\n']}, {'input': '40 7\r\nPNTVVER\r\nPAHTQDR\r\nRXMJVAS\r\nVIQNLYC\r\nILPUSVX\r\nYJOXQDJ\r\nSEFODTO\r\nOTJMREL\r\nLIQRZGD\r\nLBJJPOR\r\nRUTYHQO\r\nRIWEPBD\r\nKQUMFIB\r\nISTRRYH\r\nXBTOTGK\r\nRFQODEY\r\nHDSTZTP\r\nYCXFAGL\r\nAREGRFU\r\nLELZUYU\r\nGVABDKH\r\nFJAMMME\r\nACVULXE\r\nJHVPJAS\r\nAAQNMBX\r\nJJGUCXG\r\nOQATILQ\r\nNEOSHJM\r\nHFLWOFM\r\nICYEQHY\r\nFACGLYP\r\nPLLXJEQ\r\nDCHXYPB\r\nAGDDZJJ\r\nLSQRXTN\r\nHDQZXIY\r\nNAHDDWW\r\nQCMXRQN\r\nFDUDSZO\r\nHKBEVTW\r\n', 'output': ['206575993\r\n']}, {'input': '2 2\r\nAA\r\nBB\r\n', 'output': ['4\r\n']}, {'input': '1 10\r\nAAAAAAAAAA\r\n', 'output': ['1\r\n']}, {'input': '2 8\r\nAAAAAAAA\r\nBBBBBBBB\r\n', 'output': ['256\r\n']}, {'input': '10 10\r\nAAAAAAAAAA\r\nBBBBBBBBBB\r\nCCCCCCCCCC\r\nDDDDDDDDDD\r\nAAAAAAAAAA\r\nBBBBBBBBBB\r\nCCCCCCCCCC\r\nDDDDDDDDDD\r\nAAAAAAAAAA\r\nBBBBBBBBBB\r\n', 'output': ['1048576\r\n']}, {'input': '1 20\r\nAAAAAAAAAAAAAAAAAAAA\r\n', 'output': ['1\r\n']}, {'input': '20 1\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\n', 'output': ['7\r\n']}, {'input': '5 60\r\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\r\nBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\r\nCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC\r\nDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD\r\nEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\r\n', 'output': ['449874206\r\n']}, {'input': '50 4\r\nAAAA\r\nBBBB\r\nCCCC\r\nDDDD\r\nEEEE\r\nFFFF\r\nGGGG\r\nHHHH\r\nIIII\r\nJJJJ\r\nAAAA\r\nBBBB\r\nCCCC\r\nDDDD\r\nEEEE\r\nFFFF\r\nGGGG\r\nHHHH\r\nIIII\r\nJJJJ\r\nAAAA\r\nBBBB\r\nCCCC\r\nDDDD\r\nEEEE\r\nFFFF\r\nGGGG\r\nHHHH\r\nIIII\r\nJJJJ\r\nAAAA\r\nBBBB\r\nCCCC\r\nDDDD\r\nEEEE\r\nFFFF\r\nGGGG\r\nHHHH\r\nIIII\r\nJJJJ\r\nAAAA\r\nBBBB\r\nCCCC\r\nDDDD\r\nEEEE\r\nFFFF\r\nGGGG\r\nHHHH\r\nIIII\r\nJJJJ\r\n', 'output': ['10000\r\n']}, {'input': '1 100\r\nAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\r\n', 'output': ['1\r\n']}, {'input': '100 1\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\nA\r\n', 'output': ['1\r\n']}, {'input': '100 1\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\nA\r\nB\r\n', 'output': ['2\r\n']}, {'input': '100 1\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nA\r\nB\r\n', 'output': ['14\r\n']}, {'input': '100 1\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nO\r\nP\r\nQ\r\nR\r\nS\r\nT\r\nU\r\nV\r\nW\r\nX\r\nY\r\nZ\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nO\r\nP\r\nQ\r\nR\r\nS\r\nT\r\nU\r\nV\r\nW\r\nX\r\nY\r\nZ\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nO\r\nP\r\nQ\r\nR\r\nS\r\nT\r\nU\r\nV\r\nW\r\nX\r\nY\r\nZ\r\nA\r\nB\r\nC\r\nD\r\nE\r\nF\r\nG\r\nH\r\nI\r\nJ\r\nK\r\nL\r\nM\r\nN\r\nO\r\nP\r\nQ\r\nR\r\nS\r\nT\r\nU\r\nV\r\n', 'output': ['26\r\n']}]