import std.stdio, std.string, std.algorithm;
import std.conv, std.array;

uint f(uint k, uint l) {
    uint c = 0;
    while (l % k == 0) {
        l /= k;
        c++;
    }
    if (l == 1) { return c; }
    else { return 0; }
}

void main() {
    uint k, l; readf("%d\n%d", &k, &l);
    uint c = k.f(l);
    if (c == 0) {
        writeln("NO");
    } else {
        writeln("YES");
        writeln(c / 2);
    }
}

When Petya went to school, he got interested in large numbers and what they were called in ancient times. For instance, he learned that the Russian word "tma" (which now means "too much to be counted") used to stand for a thousand and "tma tmyschaya" (which literally means "the tma of tmas") used to stand for a million.Petya wanted to modernize the words we use for numbers and invented a word petricium that represents number k. Moreover, petricium la petricium stands for number k^2, petricium la petricium la petricium stands for k^3 and so on. All numbers of this form are called petriciumus cifera, and the number's importance is the number of articles la in its title.Petya's invention brought on a challenge that needed to be solved quickly: does some number l belong to the set petriciumus cifera? As Petya is a very busy schoolboy he needs to automate the process, he asked you to solve it.

The first input line contains integer number k, the second line contains integer number l (2≤k,l≤2^31-1).

You should print in the first line of the output "YES", if the number belongs to the set petriciumus cifera and otherwise print "NO". If the number belongs to the set, then print on the seconds line the only number — the importance of number l.

import std.stdio, std.string, std.algorithm;
import std.conv, std.array;

uint f(uint k, uint l) {
    uint c = 0;
    while (l % k == 0) {
        l /= k;
        c++;
    }
    if (l == 1) { return c; }
    else { return 0; }
}

void main() {
    uint k, l; readf("%d\n%d", &k, &l);
    uint c = k.f(l);
    if (c == 0) {
        writeln("NO");
    } else {
        writeln("YES");
        writeln(c - 1);
    }
}


module cf_116B;

import std.stdio, std.algorithm;

struct PigPosition {
    int x, y;
    int wolfs;
}

void main() {
    immutable int[] DX = [-1, 1, 0, 0],
                    DY = [0, 0, -1, 1];
    immutable int MAX_SIZE = 10;

    int n, m;
    char[MAX_SIZE][MAX_SIZE] field;
    PigPosition[] wolfsForPig;

    readf("%d %d\n", &n, &m);
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            readf("%c", &field[i][j]);
            writefln("<%c>", field[i][j]);
            if (field[i][j] == 'P') {
                wolfsForPig ~= PigPosition(i, j, 0);
                for (int k = 0; k < DX.length; ++k) {
                    int dx = i + DX[k];
                    int dy = j + DY[k];

                    if (dx >= 0 && dx < n && dy >= 0 && dy < m && field[dx][dy] == 'W') {
                        ++wolfsForPig[$ - 1].wolfs;
                    }
                }
            }
        }

        char temporary; // skip new line character
        readf("%c", &temporary);
    }

    sort!((a, b) { return a.wolfs < b.wolfs; })(wolfsForPig);

    int eatenPigs = 0;
    for (int i = 0; i < wolfsForPig.length; ++i) {
        for (int j = 0; j < DX.length; ++j) {
            int dx = wolfsForPig[i].x + DX[j];
            int dy = wolfsForPig[i].y + DY[j];

            if (dx >= 0 && dx < n && dy >= 0 && dy < m && field[dx][dy] == 'W') {
                field[dx][dy] = '.';

                ++eatenPigs;
                break;
            }
        }
    }

    writeln(eatenPigs);
}

Once upon a time there were several little pigs and several wolves on a two-dimensional grid of size n×m. Each cell in this grid was either empty, containing one little pig, or containing one wolf.A little pig and a wolf are adjacent if the cells that they are located at share a side. The little pigs are afraid of wolves, so there will be at most one wolf adjacent to each little pig. But each wolf may be adjacent to any number of little pigs.They have been living peacefully for several years. But today the wolves got hungry. One by one, each wolf will choose one of the little pigs adjacent to it (if any), and eats the poor little pig. This process is not repeated. That is, each wolf will get to eat at most one little pig. Once a little pig gets eaten, it disappears and cannot be eaten by any other wolf.What is the maximum number of little pigs that may be eaten by the wolves?

The first line contains integers n and m (1≤n,m≤10) which denotes the number of rows and columns in our two-dimensional grid, respectively. Then follow n lines containing m characters each — that is the grid description. "." means that this cell is empty. "P" means that this cell contains a little pig. "W" means that this cell contains a wolf.
It is guaranteed that there will be at most one wolf adjacent to any little pig.

Print a single number — the maximal number of little pigs that may be eaten by the wolves.

In the first example, one possible scenario in which two little pigs get eaten by the wolves is as follows.

module cf_116B;

import std.stdio, std.algorithm;

struct PigPosition {
    int x, y;
    int wolfs;
}

void main() {
    immutable int[] DX = [-1, 1, 0, 0],
                    DY = [0, 0, -1, 1];
    immutable int MAX_SIZE = 10;

    int n, m;
    char[MAX_SIZE][MAX_SIZE] field;
    PigPosition[] wolfsForPig;

    readf("%d %d\n", &n, &m);
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            readf("%c", &field[i][j]);
            if (field[i][j] == 'P') {
                wolfsForPig ~= PigPosition(i, j, 0);
                for (int k = 0; k < DX.length; ++k) {
                    int dx = i + DX[k];
                    int dy = j + DY[k];

                    if (dx >= 0 && dx < n && dy >= 0 && dy < m && field[dx][dy] == 'W') {
                        ++wolfsForPig[$ - 1].wolfs;
                    }
                }
            }
        }

        char temporary; // skip new line character
        readf("%c", &temporary);
    }

    sort!((a, b) { return a.wolfs < b.wolfs; })(wolfsForPig);

    int eatenPigs = 0;
    for (int i = 0; i < wolfsForPig.length; ++i) {
        for (int j = 0; j < DX.length; ++j) {
            int dx = wolfsForPig[i].x + DX[j];
            int dy = wolfsForPig[i].y + DY[j];

            if (dx >= 0 && dx < n && dy >= 0 && dy < m && field[dx][dy] == 'W') {
                field[dx][dy] = '.';

                ++eatenPigs;
                break;
            }
        }
    }

    writeln(eatenPigs);
}

[{'input': ['2 3\r\nPPW\r\nW.P\r\n'], 'output': ['2\r\n']}, {'input': ['3 3\r\nP.W\r\n.P.\r\nW.P\r\n'], 'output': ['0\r\n']}, {'input': ['1 1\r\nP\r\n'], 'output': ['0\r\n']}, {'input': ['2 6\r\nWW..WW\r\n.PPPP.\r\n'], 'output': ['2\r\n']}, {'input': ['6 2\r\n.W\r\n.W\r\n.P\r\nWP\r\n.P\r\nPW\r\n'], 'output': ['3\r\n']}, {'input': ['2 10\r\nW..WWP.P.P\r\nW..PP.WWP.\r\n'], 'output': ['3\r\n']}, {'input': ['10 2\r\nP.\r\n.W\r\nPW\r\n..\r\nW.\r\nW.\r\n..\r\nP.\r\nWP\r\nPP\r\n'], 'output': ['2\r\n']}, {'input': ['3 4\r\nWPPW\r\n.P..\r\nPWW.\r\n'], 'output': ['3\r\n']}, {'input': ['4 3\r\n.WW\r\n..P\r\nP.P\r\nPWW\r\n'], 'output': ['3\r\n']}, {'input': ['8 4\r\nP.WW\r\nW..P\r\nP..P\r\nP.WW\r\n..P.\r\nW.P.\r\nWP.W\r\nP..P\r\n'], 'output': ['6\r\n']}, {'input': ['1 1\r\nW\r\n'], 'output': ['0\r\n']}, {'input': ['4 10\r\n..P.PW.P.P\r\nP.WP.W..WP\r\nW..P.P..WP\r\nW.PWW.P.P.\r\n'], 'output': ['7\r\n']}, {'input': ['5 1\r\n.\r\nP\r\n.\r\n.\r\nW\r\n'], 'output': ['0\r\n']}, {'input': ['6 5\r\n..WP.\r\nWP..W\r\nW.PP.\r\n.PWW.\r\nP.PPP\r\nWP..W\r\n'], 'output': ['6\r\n']}, {'input': ['10 10\r\nPPPPPPPPPP\r\nPPPPPPPPPP\r\nPPPPPPPPPP\r\nPPPPPPPPPP\r\nPPPPPPPPPP\r\nPPPPPPPPPP\r\nPPPPPPPPPP\r\nPPPPPPPPPP\r\nPPPPPPPPPP\r\nPPPPPPPPPP\r\n'], 'output': ['0\r\n']}, {'input': ['10 1\r\n.\r\nW\r\nW\r\nP\r\nP\r\n.\r\n.\r\n.\r\nW\r\nP\r\n'], 'output': ['2\r\n']}, {'input': ['1 10\r\nP.PW.PW..W\r\n'], 'output': ['2\r\n']}, {'input': ['10 10\r\nPP..PPWPPW\r\nPPPPPPPP..\r\n.PPPPPPP.P\r\nPPPPPPPPPP\r\nPWP.PPP.PP\r\nPW.PP.PPPP\r\nPPPPPP.PPW\r\n..PPWPPP.P\r\nWPPPPPPPPP\r\nWP.WPPPWPP\r\n'], 'output': ['10\r\n']}, {'input': ['10 10\r\nPPPPPPPPPP\r\nPPPPPPPWPP\r\nPPPPPPPPPP\r\nPPPPPPPPPP\r\nPPPPPPPPPP\r\nPPPPPPPPPP\r\nPPPPPPPPPP\r\nPPPPPPPPPP\r\nPPPPPPPPPP\r\nPPPPPPPPPP\r\n'], 'output': ['1\r\n']}, {'input': ['10 10\r\nPPPPPPPPWP\r\nPPPWPPPPPP\r\nPPPPPPPPPP\r\nPWWPPWPPPP\r\nPPPPPPPPPP\r\nPPPPWPPPPP\r\nPPPPPPPPPP\r\nPPPPPPWPPW\r\nPPPPPPPPPP\r\nPPWPPPPPWP\r\n'], 'output': ['10\r\n']}, {'input': ['10 10\r\nWWWWWWWWWW\r\nWWWWWWWWWW\r\nWWWWWWWWWW\r\nWWWWWWWWWW\r\nWWWWWWWWWW\r\nWWWWWWWWWW\r\nWWWWWWWWWW\r\nWWWWWWWWWW\r\nWWWWWWWWWW\r\nWWWWWWWWWW\r\n'], 'output': ['0\r\n']}, {'input': ['1 4\r\nW..P\r\n'], 'output': ['0\r\n']}, {'input': ['10 10\r\nP.W.P.W.P.\r\n.W.P.W.P.W\r\nP.W.P.W.P.\r\n.W.P.W.P.W\r\nP.W.P.W.P.\r\n.W.P.W.P.W\r\nP.W.P.W.P.\r\n.W.P.W.P.W\r\nP.W.P.W.P.\r\n.W.P.W.P.W\r\n'], 'output': ['0\r\n']}, {'input': ['10 10\r\nWPPPWPPPWP\r\nPPPPPPPPPP\r\nPPPPPPPPPP\r\nPPPPPPPPPP\r\nWPPPWPPPWP\r\nPPPPPPPPPP\r\nPPPPPPPPPP\r\nPPPPPPPPPP\r\nWPPPWPPPWP\r\nPPPPPPPPPP\r\n'], 'output': ['9\r\n']}, {'input': ['10 10\r\nPPPPPPPPPP\r\nWWWWWWWWWW\r\nWWWWWWWWWW\r\nPPPPPPPPPP\r\nPPPPPPPPPP\r\nWWWWWWWWWW\r\nWWWWWWWWWW\r\nPPPPPPPPPP\r\nPPPPPPPPPP\r\nWWWWWWWWWW\r\n'], 'output': ['50\r\n']}, {'input': ['4 1\r\n.\r\nW\r\nP\r\n.\r\n'], 'output': ['1\r\n']}, {'input': ['1 10\r\nP..W.PPWW.\r\n'], 'output': ['1\r\n']}, {'input': ['10 1\r\nP\r\nP\r\nW\r\nW\r\n.\r\nP\r\n.\r\n.\r\n.\r\nW\r\n'], 'output': ['1\r\n']}, {'input': ['1 1\r\n.\r\n'], 'output': ['0\r\n']}, {'input': ['10 10\r\nPPPWPPPWPP\r\nPWPPPWPPPP\r\nPPPPPPPPPP\r\nWPPWPPWPPW\r\nPPPPPPPPPP\r\nPWPPWPPWPP\r\nPPPPPPPPPP\r\nPPWPPWPPWP\r\nPPPPPPPPPP\r\nWPPWPPWPPW\r\n'], 'output': ['18\r\n']}, {'input': ['10 10\r\nWPPPPWPPWP\r\nPPPWPPPPPP\r\nPWPPPPWPPP\r\nPPPPWPPPWP\r\nWPPPPPPPPP\r\nPPPWPPWPPP\r\nPWPPPPPPWP\r\nPPPPWPPPPP\r\nWPPPPPWPPP\r\nPPPWPPPPWP\r\n'], 'output': ['18\r\n']}, {'input': ['4 4\r\n.P..\r\n.W..\r\n.P..\r\n..W.\r\n'], 'output': ['1\r\n']}, {'input': ['4 1\r\n.\r\n.\r\nW\r\nP\r\n'], 'output': ['1\r\n']}, {'input': ['10 10\r\nWPPPPWPPWP\r\nPPPWPPPPPP\r\nPWPPPPWPPP\r\nPPPPWPPPWP\r\nWPPPPPPPPP\r\nPPPWPPWPPP\r\nPWPPPPPPWP\r\nPPPPWPPPPP\r\nWPPPPPWPPP\r\nPPPWPPPPWP\r\n'], 'output': ['18\r\n']}, {'input': ['2 3\r\nWWP\r\nPPP\r\n'], 'output': ['2\r\n']}]


/**
 * CodeForces Problem 344.B (1)
 * ACM summer training contest (3b)
 * Noein
 */

import std.stdio;

T mut(T)(in T inval) {
    import std.traits;

    Unqual!T new_val = inval;

    return new_val;
}

T imut(T)(in T inval) {
    immutable new_val = inval;

    return new_val;
}

/*
  T abs(T)(in T inval) { return ((inval < 0) ? -inval : inval); }
  T min(T)(in T l, in T r) { return ((l < r) ? l : r); }
*/

char to_lower(const ref char ch, bool f = true) {
    if(f) {
        if(ch >= 'A' && ch <= 'Z') {
            int dl = ('a' - 'A');
            return cast(char)(ch + dl);
        }
    }
    else if(ch >= 'a' && ch <= 'z') {
        int dl = ('a' - 'A');
        return cast(char)(ch - dl);
    }

    return ch;
}

bool chk_caps_locked(const char[] in_str) {
    bool f = true;
    foreach(c; in_str[1..$]) {
        f &= (c <= 'Z' && c >= 'A');
    }
    return f;
}

void main() {
    string maybe_caps_locked;

    readf("%s ", &maybe_caps_locked);
    string res;
    if(chk_caps_locked(maybe_caps_locked))
    {
        foreach(c; maybe_caps_locked) {
            res ~= c.to_lower();
        }
        res = to_lower(maybe_caps_locked[0], false) ~ res[1..$];
    }

    writeln(res);
}

wHAT DO WE NEED cAPS LOCK FOR?Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentally switched on, if:   either it only contains uppercase letters;  or all letters except for the first one are uppercase. In this case we should automatically change the case of all letters. For example, the case of the letters that form words "hELLO", "HTTP", "z" should be changed.Write a program that applies the rule mentioned above. If the rule cannot be applied, the program should leave the word unchanged.

The first line of the input data contains a word consisting of uppercase and lowercase Latin letters. The word's length is from 1 to 100 characters, inclusive.

Print the result of the given word's processing.

import std;

void main() {
    dstring s;
    readf("%s\n", s);

    auto len = s.length;
    bool need = true;
    foreach (i; 1 .. len) {
        need &= std.uni.isUpper(s[i]);
    }

    dchar[] res = s.dup;
    if (need) {
        foreach (i, x; s) {
            if (std.uni.isUpper(x)) res[i] = std.uni.toLower(x);
            else res[i] = std.uni.toUpper(x);
        }
    }

    res.writeln;
}

[{'input': ['cAPS\r\n'], 'output': ['Caps']}, {'input': ['Lock\r\n'], 'output': ['Lock\r\n']}, {'input': ['cAPSlOCK\r\n'], 'output': ['cAPSlOCK\r\n']}, {'input': ['CAPs\r\n'], 'output': ['CAPs\r\n']}, {'input': ['LoCK\r\n'], 'output': ['LoCK\r\n']}, {'input': ['OOPS\r\n'], 'output': ['oops']}, {'input': ['oops\r\n'], 'output': ['oops\r\n']}, {'input': ['a\r\n'], 'output': ['A']}, {'input': ['A\r\n'], 'output': ['a']}, {'input': ['aA\r\n'], 'output': ['Aa']}, {'input': ['Zz\r\n'], 'output': ['Zz\r\n']}, {'input': ['Az\r\n'], 'output': ['Az\r\n']}, {'input': ['zA\r\n'], 'output': ['Za']}, {'input': ['AAA\r\n'], 'output': ['aaa']}, {'input': ['AAa\r\n'], 'output': ['AAa\r\n']}, {'input': ['AaR\r\n'], 'output': ['AaR\r\n']}, {'input': ['Tdr\r\n'], 'output': ['Tdr\r\n']}, {'input': ['aTF\r\n'], 'output': ['Atf']}, {'input': ['fYd\r\n'], 'output': ['fYd\r\n']}, {'input': ['dsA\r\n'], 'output': ['dsA\r\n']}, {'input': ['fru\r\n'], 'output': ['fru\r\n']}, {'input': ['hYBKF\r\n'], 'output': ['Hybkf']}, {'input': ['XweAR\r\n'], 'output': ['XweAR\r\n']}, {'input': ['mogqx\r\n'], 'output': ['mogqx\r\n']}, {'input': ['eOhEi\r\n'], 'output': ['eOhEi\r\n']}, {'input': ['nkdku\r\n'], 'output': ['nkdku\r\n']}, {'input': ['zcnko\r\n'], 'output': ['zcnko\r\n']}, {'input': ['lcccd\r\n'], 'output': ['lcccd\r\n']}, {'input': ['vwmvg\r\n'], 'output': ['vwmvg\r\n']}, {'input': ['lvchf\r\n'], 'output': ['lvchf\r\n']}, {'input': ['IUNVZCCHEWENCHQQXQYPUJCRDZLUXCLJHXPHBXEUUGNXOOOPBMOBRIBHHMIRILYJGYYGFMTMFSVURGYHUWDRLQVIBRLPEVAMJQYO\r\n'], 'output': ['iunvzcchewenchqqxqypujcrdzluxcljhxphbxeuugnxooopbmobribhhmirilyjgyygfmtmfsvurgyhuwdrlqvibrlpevamjqyo']}, {'input': ['OBHSZCAMDXEJWOZLKXQKIVXUUQJKJLMMFNBPXAEFXGVNSKQLJGXHUXHGCOTESIVKSFMVVXFVMTEKACRIWALAGGMCGFEXQKNYMRTG\r\n'], 'output': ['obhszcamdxejwozlkxqkivxuuqjkjlmmfnbpxaefxgvnskqljgxhuxhgcotesivksfmvvxfvmtekacriwalaggmcgfexqknymrtg']}, {'input': ['IKJYZIKROIYUUCTHSVSKZTETNNOCMAUBLFJCEVANCADASMZRCNLBZPQRXESHEEMOMEPCHROSRTNBIDXYMEPJSIXSZQEBTEKKUHFS\r\n'], 'output': ['ikjyzikroiyuucthsvskztetnnocmaublfjcevancadasmzrcnlbzpqrxesheemomepchrosrtnbidxymepjsixszqebtekkuhfs']}, {'input': ['cTKDZNWVYRTFPQLDAUUNSPKTDJTUPPFPRXRSINTVFVNNQNKXWUZUDHZBUSOKTABUEDQKUIVRTTVUREEOBJTSDKJKVEGFXVHXEYPE\r\n'], 'output': ['Ctkdznwvyrtfpqldauunspktdjtuppfprxrsintvfvnnqnkxwuzudhzbusoktabuedqkuivrttvureeobjtsdkjkvegfxvhxeype']}, {'input': ['uCKJZRGZJCPPLEEYJTUNKOQSWGBMTBQEVPYFPIPEKRVYQNTDPANOIXKMPINNFUSZWCURGBDPYTEKBEKCPMVZPMWAOSHJYMGKOMBQ\r\n'], 'output': ['Uckjzrgzjcppleeyjtunkoqswgbmtbqevpyfpipekrvyqntdpanoixkmpinnfuszwcurgbdpytekbekcpmvzpmwaoshjymgkombq']}, {'input': ['KETAXTSWAAOBKUOKUQREHIOMVMMRSAEWKGXZKRASwTVNSSFSNIWYNPSTMRADOADEEBURRHPOOBIEUIBGYDJCEKPNLEUCANZYJKMR\r\n'], 'output': ['KETAXTSWAAOBKUOKUQREHIOMVMMRSAEWKGXZKRASwTVNSSFSNIWYNPSTMRADOADEEBURRHPOOBIEUIBGYDJCEKPNLEUCANZYJKMR\r\n']}, {'input': ['ZEKGDMWJPVUWFlNXRLUmWKLMMYSLRQQIBRWDPKWITUIMZYYKOEYGREKHHZRZZUFPVTNIHKGTCCTLOKSZITXXZDMPITHNZUIGDZLE\r\n'], 'output': ['ZEKGDMWJPVUWFlNXRLUmWKLMMYSLRQQIBRWDPKWITUIMZYYKOEYGREKHHZRZZUFPVTNIHKGTCCTLOKSZITXXZDMPITHNZUIGDZLE\r\n']}, {'input': ['TcMbVPCFvnNkCEUUCIFLgBJeCOKuJhIGwXFrhAZjuAhBraMSchBfWwIuHAEbgJOFzGtxDLDXzDSaPCFujGGxgxdlHUIQYRrMFCgJ\r\n'], 'output': ['TcMbVPCFvnNkCEUUCIFLgBJeCOKuJhIGwXFrhAZjuAhBraMSchBfWwIuHAEbgJOFzGtxDLDXzDSaPCFujGGxgxdlHUIQYRrMFCgJ\r\n']}, {'input': ['xFGqoLILNvxARKuIntPfeukFtMbvzDezKpPRAKkIoIvwqNXnehRVwkkXYvuRCeoieBaBfTjwsYhDeCLvBwktntyluoxCYVioXGdm\r\n'], 'output': ['xFGqoLILNvxARKuIntPfeukFtMbvzDezKpPRAKkIoIvwqNXnehRVwkkXYvuRCeoieBaBfTjwsYhDeCLvBwktntyluoxCYVioXGdm\r\n']}, {'input': ['udvqolbxdwbkijwvhlyaelhynmnfgszbhgshlcwdkaibceqomzujndixuzivlsjyjqxzxodzbukxxhwwultvekdfntwpzlhhrIjm\r\n'], 'output': ['udvqolbxdwbkijwvhlyaelhynmnfgszbhgshlcwdkaibceqomzujndixuzivlsjyjqxzxodzbukxxhwwultvekdfntwpzlhhrIjm\r\n']}, {'input': ['jgpwhetqqoncighgzbbaLwwwxkxivuwtokehrgprfgewzcwxkavwoflcgsgbhoeamzbefzoonwsyzisetoydrpufktzgbaycgaeg\r\n'], 'output': ['jgpwhetqqoncighgzbbaLwwwxkxivuwtokehrgprfgewzcwxkavwoflcgsgbhoeamzbefzoonwsyzisetoydrpufktzgbaycgaeg\r\n']}, {'input': ['vyujsazdstbnkxeunedfbolicojzjpufgfemhtmdrswvmuhoivjvonacefqenbqudelmdegxqtbwezsbydmanzutvdgkgrjxzlnc\r\n'], 'output': ['vyujsazdstbnkxeunedfbolicojzjpufgfemhtmdrswvmuhoivjvonacefqenbqudelmdegxqtbwezsbydmanzutvdgkgrjxzlnc\r\n']}, {'input': ['pivqnuqkaofcduvbttztjbuavrqwiqrwkfncmvatoxruelyoecnkpqraiahumiaiqeyjapbqyrsxcdgjbihivtqezvasfmzntdfv\r\n'], 'output': ['pivqnuqkaofcduvbttztjbuavrqwiqrwkfncmvatoxruelyoecnkpqraiahumiaiqeyjapbqyrsxcdgjbihivtqezvasfmzntdfv\r\n']}, {'input': ['upvtbsxswbohxshdrbjxcungzquhuomgxwlryvshshsfvqbrxvcikbglietlpqkiwbhiqpmdwuqosbtdvyxekkaqiwrbsibpoect\r\n'], 'output': ['upvtbsxswbohxshdrbjxcungzquhuomgxwlryvshshsfvqbrxvcikbglietlpqkiwbhiqpmdwuqosbtdvyxekkaqiwrbsibpoect\r\n']}, {'input': ['cTKDZNWVYRTFPQLDAUUNSPKTDJTUPPFPRXRSINTVFVNNQNKXWUZUDHZBUSOKTABUEDQKUIVRTTVUREEOBJTSDKJKVEGFXVHXEYPE\r\n'], 'output': ['Ctkdznwvyrtfpqldauunspktdjtuppfprxrsintvfvnnqnkxwuzudhzbusoktabuedqkuivrttvureeobjtsdkjkvegfxvhxeype']}, {'input': ['JEGDOFJOFGJHFROGHOFGMHOFGHORGFHMOu\r\n'], 'output': ['JEGDOFJOFGJHFROGHOFGMHOFGHORGFHMOu\r\n']}, {'input': ['aBACABa\r\n'], 'output': ['aBACABa\r\n']}, {'input': ['AAAAAAAAAAAAAAAAAAAAAAAAaa\r\n'], 'output': ['AAAAAAAAAAAAAAAAAAAAAAAAaa\r\n']}, {'input': ['aaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\r\n'], 'output': ['aaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\r\n']}, {'input': ['dDDDDDDDDDDDDD\r\n'], 'output': ['Dddddddddddddd']}, {'input': ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\n'], 'output': ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\r\n']}, {'input': ['z\r\n'], 'output': ['Z']}, {'input': ['AZ\r\n'], 'output': ['az']}, {'input': ['Z\r\n'], 'output': ['z']}, {'input': ['aAAAA\r\n'], 'output': ['Aaaaa']}, {'input': ['F\r\n'], 'output': ['f']}]


ï»¿import std.stdio;
import std.algorithm;

void main() {
	int n;
	int[] a;
	int temp;

	readf(" %s %s", &n, &temp);

	a ~= temp;
	int max = temp;

	int idx = 0;
	foreach (i; 1 .. n) {
		readf(" %s", &temp);
		a ~= temp;
		if (temp > max) {
			max = temp;
			idx = i;
		}
	}

	(a[idx] == 1) ? a[idx] = 2 : a[idx] = 1;

	writefln("%(%s %)", sort(a));
}

Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 10^9, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that also lies in the range from 1 to 10^9, inclusive. It is not allowed to replace a number with itself or to change no number at all. After the replacement Petya sorted the array by the numbers' non-decreasing. Now he wants to know for each position: what minimum number could occupy it after the replacement and the sorting.

The first line contains a single integer n (1≤n≤10^5), which represents how many numbers the array has. The next line contains n space-separated integers — the array's description. All elements of the array lie in the range from 1 to 10^9, inclusive.

Print n space-separated integers — the minimum possible values of each array element after one replacement and the sorting are performed.

import std.stdio
    , std.typecons
    , std.traits
    , std.algorithm
    , std.range
    , std.container;

void main() {
    const len = {
        uint t;
        readf("%s\n", &t);
        return t;
    }();

    uint[] data = new uint[len];

    auto mymax = tuple(0, 0);
    foreach(idx, ref i; data) {
        readf("%s ", &i);
        if(i > mymax[1]) { mymax[1] = i; mymax[0] = idx; }
    }

    if(mymax[1] != 1) {
        data[mymax[0]] = 1;
    }
    else
    {
        data[mymax[0]] = 2;
    }

    /*data.sort()
    .y!((auto ref arr){
        foreach(ref a; arr) {
            write(a, " ");
        }
    });
    */

    (auto ref arr){
        foreach(ref a; arr) {
            write(a, " ");
        }
    }
    ( data.sort() );
}

alias y(alias clos) = clos;

alias var(alias elem) = std.traits.Unqual!(typeof(elem));

auto mut(T)(auto ref T in_val) {
    std.traits.Unqual!(T) rv = in_val;
    return rv;
}

auto imut(T)(auto ref T in_val) {
    immutable immrv = in_val;
    return immrv;
}


import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

void main() {
    int N; scanf("%d\n", &N);
    auto u = new bool[N];
    int c;
    foreach (i; 0 .. N) {
        int x; scanf("%d", &x);
        x--;
        if (x >= N) c++;
        if (u[x]) c++;
        u[x] = true;
    }
    writeln(c);
}

"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.

The 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.

module cf_137B;

import std.stdio, std.algorithm;

void main() {
	int n;
	int[] numbers;

	readf("%d", &n);
	numbers = new int[n];
	for (auto i = 0; i < n; ++i) {
		readf(" %d", &numbers[i]);
	}

	sort(numbers);

	int skip = 0, index = 0;
	for (auto i = 1; i <= n; ++i) {
		if (index >= n) {
			++skip;
			continue;
		}

		if (numbers[index] == i) {
			while (index < n && numbers[index] == i) {
				++index;
			}
		} else {
			++skip;
		}
	}

	writeln(skip);
}


import std.stdio;
import std.conv;
import std.algorithm;
import std.array;
import std.string;
import std.uni;
import std.math;
import std.container.rbtree;
import std.range;

void main()
{
    auto t = to!long(readln().chomp);
    OUTER: foreach(_; 0..t)
    {
        auto n = readln();
        auto arr = readln().chomp.splitter(" ").map!(to!long).map!(x => pow(x, 2)).array;

        for(int i = 0; i < arr.length; i++)
        {
            for(int j = i+1; j < arr.length; j++)
            {
                double target = arr[i]+arr[j];
                bool found = false;
                for(int z = j+1; z < arr.length; z++)
                {
                    if(arr[z] >= target)
                    {
                        writeln(format("%d %d %d", i, j, z));
                        continue OUTER;
                    }
                }
            }
        }

        writeln("-1");
    }
}

You are given an array $$$a_1, a_2, \dots , a_n$$$, which is sorted in non-decreasing order ($$$a_i \le a_{i + 1})$$$. Find three indices $$$i$$$, $$$j$$$, $$$k$$$ such that $$$1 \le i < j < k \le n$$$ and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to $$$a_i$$$, $$$a_j$$$ and $$$a_k$$$ (for example it is possible to construct a non-degenerate triangle with sides $$$3$$$, $$$4$$$ and $$$5$$$ but impossible with sides $$$3$$$, $$$4$$$ and $$$7$$$). If it is impossible to find such triple, report it.

The first line contains one integer $$$t$$$ ($$$1 \\le t \\le 1000$$$) — the number of test cases.
The first line of each test case contains one integer $$$n$$$ ($$$3 \\le n \\le 5 \\cdot 10^4$$$) — the length of the array $$$a$$$.
The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \\dots , a_n$$$ ($$$1 \\le a_i \\le 10^9$$$; $$$a_{i - 1} \\le a_i$$$) — the array $$$a$$$.
It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case print the answer to it in one line.
If there is a triple of indices $$$i$$$, $$$j$$$, $$$k$$$ ($$$i < j < k$$$) such that it is impossible to construct a non-degenerate triangle having sides equal to $$$a_i$$$, $$$a_j$$$ and $$$a_k$$$, print that three indices in ascending order. If there are multiple answers, print any of them.
Otherwise, print -1.

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		auto n = readln.strip.to !(int);
		auto a = readln.splitter.map !(to !(int)).array;
		auto p = n.iota.array;
		makeIndex (a, p);
		if (a[p[0]] + a[p[1]] <= a[p[$ - 1]])
		{
			auto q = [p[0], p[1], p[$ - 1]];
			sort (q);
			q[] += 1;
			writefln !("%(%s %)") (q);
		}
		else
		{
			writeln (-1);
		}
	}
}


import std.stdio;
import std.algorithm;
import std.range;

void main()
{
    uint[4] nums;
    uint total;
    readf("%s\n%s\n%s\n%s\n%s\n", &nums[0], &nums[1], &nums[2], &nums[3], &total);
    auto sequence = iota(1, total+1).map!(a => any!(b => a%b==0)(nums.dup));
    sequence.save.writeln;
    reduce!((a,b) => a + b)(0, sequence).writeln;
}

«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≤10^5).

In 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 std;

void main() {
    auto k = new int[](4);
    foreach (i; 0 .. 4) readf("%d\n", k[i]);

    int d;
    readf("%d\n", d);

    auto dragons = new bool[](d+1);
    foreach (x; k) {
        int p = x;
        while (p <= d) {
            dragons[p] = true;
            p += x;
        }
    }

    auto res = dragons.count(true);
    res.writeln;
}


import std.stdio;

void main() {
	int[12] array;
	int n;
	readf(" %s", &n);
	for (int i = 0; i < 12; i++)
		readf(" %s", &array[i]);

	array.sort;

	int counter = 0;
	int count = 0;
	foreach_reverse(e; array) {
		if (counter >= n) {
			break;
		}
		counter += e;
		count++;

	}

	writeln(count);
}

What joy! Petya's parents went on a business trip for the whole year and the playful kid is left all by himself. Petya got absolutely happy. He jumped on the bed and threw pillows all day long, until... Today Petya opened the cupboard and found a scary note there. His parents had left him with duties: he should water their favourite flower all year, each day, in the morning, in the afternoon and in the evening. "Wait a second!" — thought Petya. He know for a fact that if he fulfills the parents' task in the i-th (1≤i≤12) month of the year, then the flower will grow by ai centimeters, and if he doesn't water the flower in the i-th month, then the flower won't grow this month. Petya also knows that try as he might, his parents won't believe that he has been watering the flower if it grows strictly less than by k centimeters. Help Petya choose the minimum number of months when he will water the flower, given that the flower should grow no less than by k centimeters.

The first line contains exactly one integer k (0≤k≤100). The next line contains twelve space-separated integers: the i-th (1≤i≤12) number in the line represents ai (0≤ai≤100).

Print the only integer — the minimum number of months when Petya has to water the flower so that the flower grows no less than by k centimeters. If the flower can't grow by k centimeters in a year, print -1.

Let's consider the first sample test. There it is enough to water the flower during the seventh and the ninth month. Then the flower grows by exactly five centimeters.
In the second sample Petya's parents will believe him even if the flower doesn't grow at all (k=0). So, it is possible for Petya not to water the flower at all.

import std;

void main() {
    int k;
    readf("%d\n", k);

    auto a = readln.chomp.split.to!(int[]);

    if (k == 0) {
        writeln(0);
        return;
    }

    a.sort!"a > b";

    foreach (i, x; a) {
        k -= x;
        if (k <= 0) {
            writeln(i+1);
            return;
        }
    }

    writeln(-1);
}


import std.stdio;
import std.array;
import std.algorithm;
import std.conv;

int main() {
    auto s = stdin.byLine;
    s.popFront();
    auto arr = s.front.split(" ").map!(i => to!int(i))();
    int[] arr_sum;
    arr_sum.length = arr.length;
    arr_sum[0] = arr[0];
    for (uint i = 1; i < arr.length; i++) {
        arr_sum[i] = arr[i] + arr_sum[i - 1];
    }
    float max = arr_sum[arr_sum.length - 1];
    int idx = 0;
    for (uint i = arr_sum.length - 1; i >= 0; i--) {
        if (arr_sum[i] < (max/2)) {
            idx = i;
            break;
        }
    }
    writeln(arr_sum.length - idx - 1);
    return 0;
}

Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.Now let's imagine a typical morning in your family. You haven't woken up yet, and Mom is already going to work. She has been so hasty that she has nearly forgotten to leave the two of her darling children some money to buy lunches in the school cafeteria. She fished in the purse and found some number of coins, or to be exact, n coins of arbitrary values a1,a2,...,an. But as Mom was running out of time, she didn't split the coins for you two. So she scribbled a note asking you to split the money equally.As you woke up, you found Mom's coins and read her note. "But why split the money equally?" — you thought. After all, your twin is sleeping and he won't know anything. So you decided to act like that: pick for yourself some subset of coins so that the sum of values of your coins is strictly larger than the sum of values of the remaining coins that your twin will have. However, you correctly thought that if you take too many coins, the twin will suspect the deception. So, you've decided to stick to the following strategy to avoid suspicions: you take the minimum number of coins, whose sum of values is strictly more than the sum of values of the remaining coins. On this basis, determine what minimum number of coins you need to take to divide them in the described manner.

The first line contains integer n (1≤n≤100) — the number of coins. The second line contains a sequence of n integers a1, a2, ..., an (1≤ai≤100) — the coins' values. All numbers are separated with spaces.

In the single line print the single number — the minimum needed number of coins.

In the first sample you will have to take 2 coins (you and your twin have sums equal to 6,0 correspondingly). If you take 1 coin, you get sums 3,3. If you take 0 coins, you get sums 0,6. Those variants do not satisfy you as your sum should be strictly more that your twins' sum.
In the second sample one coin isn't enough for us, too. You can pick coins with values 1,2 or 2,2. In any case, the minimum number of coins equals 2.

import std;

void main() {
    int n;
    readf("%d\n", n);

    auto a = readln.chomp.split.to!(int[]);

    a.sort!"a > b";

    int res, num, rem = a.sum;
    foreach (x; a) {
        if (num > rem) break;

        ++res, num += x, rem -= x;
    }

    res.writeln;
}


import std.stdio;
import std.math;

void main(){
  uint n;
  readf("%s\n",&n);

  solve1(n);
  //solve2(n+1);
}

void solve2(uint size){
  uint mod = 1000000007;
  uint[] m = new uint[size];

  m[0] = 0;
  m[1] = 0;
  m[2] = 3;
  m[3] = 6;
  for(uint i = 4; i < m.length; i++){
    auto sum = 0;
    //writefln("<%s>",i);
    for(uint n = 0; n < i-2; n++){
      sum += pow(2,n)*m[i-n-2];
      //writefln("%s,%s = %s",n,i-n-2,pow(2,n)*m[i-n-2]);
    }
    m[i] = (3*(sum + pow(2,i-2))) % mod;
  }

  writeln(m[size-1]);
}

void solve1(uint n){
  uint k = n;
  if(n < 10){
    n = 10;
  }

  uint mod = 1000000007;
  //uint size = 1000000;
  //uint size = 10;
  uint[] m = new uint[n+1];

  m[0] = 0;
  m[1] = 0;
  m[2] = 3;
  m[3] = 6;
  for(uint i = 4; i < m.length; i++){
    auto x1 = m[i-1] % mod;
    auto x2 = m[i-2] % mod;
    m[i] = (2*x1+3*x2) % mod;
  }

  writeln(m[k]);
}

You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly. An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (10^9+7).

The first line contains the only integer n (1≤n≤10^7) — the required length of the cyclic path.

Print the only integer — the required number of ways modulo 1000000007 (10^9+7).

The required paths in the first sample are:
  D-A-D  D-B-D  D-C-D

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.stdio, std.bitmanip;

void main() {
    immutable int MOD = 10^^9+7;
    auto N = readln.chomp.to!int;

    auto dp = new long[][](2, 4);
    dp[0][0] = 1;
    dp[0][1] = dp[0][2] = dp[0][3] = 0;

    foreach (i; 0..N) {
        auto cur = i % 2;
        auto tar = 1 - cur;
        dp[tar][0] = (dp[cur][1] + dp[cur][2] + dp[cur][3]) % MOD;
        dp[tar][1] = (dp[cur][0] + dp[cur][2] + dp[cur][3]) % MOD;
        dp[tar][2] = (dp[cur][0] + dp[cur][1] + dp[cur][3]) % MOD;
        dp[tar][3] = (dp[cur][0] + dp[cur][1] + dp[cur][2]) % MOD;
    }

    writeln(dp[N%2][0]);
}


module _template;
import std.stdio;
import std.algorithm;
import std.container;
import std.range;
import std.numeric;
import std.conv;
import std.typecons;
import std.format;

struct IO {
        string read_string() {
                while (tokens.empty) {
                tokens = readln.split;
        }
        auto token = tokens.front;
                tokens.popFront;
                return token;
        }

        int read_int() {
                return read_string.to!int;
        }

        string[] tokens;
}

void main() {
        IO cin;
        int t = 1;
        // int t = cin.read_int;
        while (t--) {
                int n = cin.read_int;
                int a = cin.read_int;
                int b = cin.read_int;

                int[] v = new int[n];
                for (int i = 0; i < n; i++) {
                        v[i] = cin.read_int;
                }
                sort(v);
                writeln(v[b] - v[a]);
        }
}

Petya and Vasya are brothers. Today is a special day for them as their parents left them home alone and commissioned them to do n chores. Each chore is characterized by a single parameter — its complexity. The complexity of the i-th chore equals hi.As Petya is older, he wants to take the chores with complexity larger than some value x (hi>x) to leave to Vasya the chores with complexity less than or equal to x (hi≤x). The brothers have already decided that Petya will do exactly a chores and Vasya will do exactly b chores (a+b=n).In how many ways can they choose an integer x so that Petya got exactly a chores and Vasya got exactly b chores?

The first input line contains three integers n,a and b (2≤n≤2000; a,b≥1; a+b=n) — the total number of chores, the number of Petya's chores and the number of Vasya's chores.
The next line contains a sequence of integers h1,h2,...,hn (1≤hi≤10^9), hi is the complexity of the i-th chore. The numbers in the given sequence are not necessarily different.
All numbers on the lines are separated by single spaces.

Print the required number of ways to choose an integer value of x. If there are no such ways, print 0.

In the first sample the possible values of x are 3, 4 or 5.
In the second sample it is impossible to find such x, that Petya got 3 chores and Vasya got 4.

module _template;
import std.stdio;
import std.algorithm;
import std.container;
import std.range;
import std.numeric;
import std.conv;
import std.typecons;
import std.format;

struct IO {
        string read_string() {
                while (tokens.empty) {
                tokens = readln.split;
        }
        auto token = tokens.front;
                tokens.popFront;
                return token;
        }

        int read_int() {
                return read_string.to!int;
        }

        string[] tokens;
}

void main() {
        IO cin;
        int t = 1;
        // int t = cin.read_int;
        while (t--) {
                int n = cin.read_int;
                int a = cin.read_int;
                int b = cin.read_int;

                int[] v = new int[n];
                for (int i = 0; i < n; i++) {
                        v[i] = cin.read_int;
                }
                sort(v);
                writeln(v[b] - v[b - 1]);
        }
}


import std.stdio, std.algorithm, std.string, std.conv, std.range;

void main() {
    int n, a, b, c;
    readf("%d %d %d %d\n", &n, &a, &b, &c);
    dp(n, a, b, c).writeln;
}

int dp(int n, int a, int b, int c) {
    int[] r = new int[n + 1];
    foreach (e; [ a, b, c ]) {
        r[e] = 1;
    }

    foreach (int i, ref e; r) {
        if (e > 0) {
            foreach (cut; [ a, b, c ]) {
                if (i + cut <= n) {
                    r[i + cut] = max(r[i] + 1, r[i + cut]);
                }
            }
        }
    }

    return r[n];
}

Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions:   After the cutting each ribbon piece should have length a, b or c.  After the cutting the number of ribbon pieces should be maximum. Help Polycarpus and find the number of ribbon pieces after the required cutting.

The first line contains four space-separated integers n, a, b and c (1≤n,a,b,c≤4000) — the length of the original ribbon and the acceptable lengths of the ribbon pieces after the cutting, correspondingly. The numbers a, b and c can coincide.

Print a single number — the maximum possible number of ribbon pieces. It is guaranteed that at least one correct ribbon cutting exists.

In the first example Polycarpus can cut the ribbon in such way: the first piece has length 2, the second piece has length 3.
In the second example Polycarpus can cut the ribbon in such way: the first piece has length 5, the second piece has length 2.

import std;

void main() {
    auto a = readln.chomp.split.to!(int[]);

    int n = a.front;
    a.popFront;

    auto cnts = new int[](n+1);
    foreach (x; a) {
        if (x <= n) cnts[x] = 1;
    }

    foreach (i; 0 .. n) {
        if (cnts[i] == 0) continue;

        foreach (x; a) {
            if (i + x > n) continue;

            cnts[i+x] = max(cnts[i+x], cnts[i]+1);
        }
    }

    int res = cnts[n];
    res.writeln;
}


import std.stdio;
import std.string;
import std.conv;

int main() {
    debug stdin = File("in.txt", "r");

    int[44722] tri = void;
    foreach (i; 0 .. 44722) {
        tri[i] = i * (i + 1) / 2;
    }

    int n;
    readf(" %s\n", &n);

    foreach (i; 0 .. 44722) {
        int a = tri[i];
        foreach (j; i .. 44722) {
            int b = tri[j];
            if (a + b >= n) {
                if (a + b > n) break;
                else {
                    writeln("YES");
                    return 0;
                }
            }
        }
    }
    writeln("NO");

    return 0;
}

As you very well know, this year's funkiest numbers are so called triangular numbers (that is, integers that are representable as , where k is some positive integer), and the coolest numbers are those that are representable as a sum of two triangular numbers.A well-known hipster Andrew adores everything funky and cool but unfortunately, he isn't good at maths. Given number n, help him define whether this number can be represented by a sum of two triangular numbers (not necessarily different)!

The first input line contains an integer n (1≤n≤10^9).

Print "YES" (without the quotes), if n can be represented as a sum of two triangular numbers, otherwise print "NO" (without the quotes).

In the first sample number .
In the second sample number 512 can not be represented as a sum of two triangular numbers.

import std.stdio;
import std.range;

int main() {
    debug stdin = File("in.txt", "r");

    int[44722] tri = void;
    foreach (i; 0 .. 44722) {
        tri[i] = i * (i + 1) / 2;
    }

    int n;
    readf(" %s\n", &n);

    int[] triRange = tri;
    auto asr = assumeSorted(triRange);
    foreach (i; 1 .. 44722) {
        int cand = n - tri[i];
        if (cand < 1) break;
        auto er = asr.equalRange(cand);
        if (!er.empty) {
            writeln("YES");
            return 0;
        }
    }
    writeln("NO");

    return 0;
}


import std.stdio;

void main() {
    int n, m, a;
    readf("%s %s %s\n", n, m, a);
    writeln(((n + a - 1) / a) * ((m + a - 1) / a));
}

Theatre Square in the capital city of Berland has a rectangular shape with the size n×m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a×a.What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.

The input contains three positive integer numbers in the first line: n,m and a (1≤n,m,a≤10^9).

import std;

void main() {
    long n, m, a;
    readf("%d %d %d\n", n, m, a);

    long x = (n + a - 1) / a, y = (m + a - 1) / a;

    long res = x * y;
    res.writeln;
}


module cf_203A;

import std.stdio;

void main() {
    int x, t, a, b, da, db;

    readf("%d %d %d %d %d %d", &x, &t, &a, &b, &da, &db);

    bool valeraSaidTrue = false;
    int aa = a;

    dualFor:
    for (int i = 0; i < t; ++i) {
        int bb = b;

        for (int j = 0; j < t; ++j) {
            if (aa + bb == x) {
                valeraSaidTrue = true;
                break dualFor;
            }
            bb -= db;
        }
        aa -= da;
    }

    if (x == a || x == b || x == 0) {
        valeraSaidTrue = true;
    }

    writeln(valeraSaidTrue? "YES": "NO");
}

A boy Valera registered on site Codeforces as Valera, and wrote his first Codeforces Round #300. He boasted to a friend Arkady about winning as much as x points for his first contest. But Arkady did not believe his friend's words and decided to check whether Valera could have shown such a result.He knows that the contest number 300 was unusual because there were only two problems. The contest lasted for t minutes, the minutes are numbered starting from zero. The first problem had the initial cost of a points, and every minute its cost reduced by da points. The second problem had the initial cost of b points, and every minute this cost reduced by db points. Thus, as soon as the zero minute of the contest is over, the first problem will cost a-da points, and the second problem will cost b-db points. It is guaranteed that at any moment of the contest each problem has a non-negative cost.Arkady asks you to find out whether Valera could have got exactly x points for this contest. You should assume that Valera could have solved any number of the offered problems. You should also assume that for each problem Valera made no more than one attempt, besides, he could have submitted both problems at the same minute of the contest, starting with minute 0 and ending with minute number t-1. Please note that Valera can't submit a solution exactly t minutes after the start of the contest or later.

The single line of the input contains six integers x,t,a,b,da,db (0≤x≤600; 1≤t,a,b,da,db≤300) — Valera's result, the contest's duration, the initial cost of the first problem, the initial cost of the second problem, the number of points that the first and the second problem lose per minute, correspondingly.
It is guaranteed that at each minute of the contest each problem has a non-negative cost, that is, a-i·da≥0 and b-i·db≥0 for all 0≤i≤t-1.

If Valera could have earned exactly x points at a contest, print "YES", otherwise print "NO" (without the quotes).

In the first sample Valera could have acted like this: he could have submitted the first problem at minute 0 and the second problem — at minute 2. Then the first problem brings him 20 points and the second problem brings him 10 points, that in total gives the required 30 points.

module cf_203A;

import std.stdio;

void main() {
    int x, t, a, b, da, db;

    readf("%d %d %d %d %d %d", &x, &t, &a, &b, &da, &db);

    bool valeraSaidTrue = false;
    int aa = a;

    dualFor:
    for (int i = 0; i <= t; ++i) {
        int bb = b;

        if (i == t) {
            aa = 0;
        }
        for (int j = 0; j <= t; ++j) {
            if (j == t) {
                bb = 0;
            }
            if (aa + bb == x) {
                valeraSaidTrue = true;
                break dualFor;
            }
            bb -= db;
        }
        aa -= da;
    }

    writeln(valeraSaidTrue? "YES": "NO");
}


import std.stdio;
import std.conv;
import std.string;
import std.typecons;
import std.algorithm;
import std.array;
import std.range;
import std.math;

void main()
{
  auto n = readln().chomp().to!int();
  auto p = new int[][](n, 2);
  auto f = new bool[n];

  foreach (i; iota(n)) {
    p[i] = readln().split().map!(to!int)().array();
  }

  foreach (i; iota(n)) {
    foreach (j; iota(n)) {
      if (i == j) continue;
      if (p[i][0] == p[j][0] || p[i][1] == p[j][1]) {
        f[j] = 1;
      }
    }
  }

  int cnt;
  foreach (i; iota(n)) {
    if (!f[i]) cnt++;
  }

  writeln(cnt ? cnt - 1 : 0);
}

Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.We assume that Bajtek can only heap up snow drifts at integer coordinates.

The first line of input contains a single integer n (1≤n≤100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1≤xi,yi≤1000) — the coordinates of the i-th snow drift.
Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.

Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.

import std.stdio, std.string, std.conv, std.range, std.array, std.algorithm;
import std.uni, std.math, std.container, std.typecons, std.typetuple;
import core.bitop, std.datetime;

immutable int mod = 10^^9 + 7;

void main(){
    int n = readln.chomp.to!int;

    auto x = new int[](n);
    auto y = new int[](n);

    foreach(i ; 0 .. n){
        readVars(x[i], y[i]);
    }

    auto visited = new bool[](n);

    int ans;

    foreach(i ; 0 .. n){
        if(!visited[i]){
            dfs(n, x, y, visited, i);
            ans++;
        }
    }

    writeln(ans - 1);
}

void dfs(int n, int[] x, int[] y, bool[] visited, int i) {
    visited[i] = true;

    foreach(j ; 0 .. n){
        if((x[j] == x[i] || y[j] == y[i]) && !visited[j]){
            dfs(n, x, y, visited, j);
        }
    }
}

void readVars(T...)(auto ref T args){
    auto line = readln.split;
    foreach(ref arg ; args){
        arg = line.front.to!(typeof(arg));
        line.popFront;
    }
    if(!line.empty){
        writeln(line);
        throw new Exception("args num < input num");
    }
}


import std.stdio;
import std.math;
import std.algorithm;

void main() {
	long N, ans =1000000000+42;
	readf(" %d",&N);
	for(int i =0; i < 100; i++) {
		real D =sqrt(1.0*i*i+4.0*N);
		if(fabs(D*D-i*i-4*N) > 1e-9) continue;
		long x =cast(long)(round(D));
		if((x-i)%2 != 0) continue;
		x =(x-i)/2;

		int s =0; long y =x;
		while(y > 0) {
			s +=y%10;
			y /=10;}

		if(s == i) ans =min(ans,x);}

	if(ans > 1000000000) writeln(-1);
	else writeln(ans);}

Let's consider equation:x^2+s(x)·x-n=0, where x,n are positive integers, s(x) is the function, equal to the sum of digits of number x in the decimal number system.You are given an integer n, find the smallest positive integer root of equation x, or else determine that there are no such roots.

A single line contains integer n (1≤n≤10^18) — the equation parameter.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.

Print -1, if the equation doesn't have integer positive roots. Otherwise print such smallest integer x (x>0), that the equation given in the statement holds.

In the first test case x=1 is the minimum root. As s(1)=1 and 1^2+1·1-2=0.
In the second test case x=10 is the minimum root. As s(10)=1+0=1 and 10^2+1·10-110=0.
In the third test case the equation has no roots.

import std.stdio, std.math;

int s(long n) {
	int t = 0;
	while (n > 0) {
		t += n % 10;
		n /= 10;
	}
	return t;
}

int m(long n) {
	int t = 0;
	while (n > 0) { t++; n /= 10; }
	return t * 9;
}

/*
x^2 + tx > n
x^2 + tx + t^2/4 > n + t^2/4
x + t/2 > sqrt(4n^2+t^2)/2
x > sqrt(4n^2+t^2)/2-t/2
*/

long solve(long n) {
	long r = cast(long) sqrt(n * 1.0);
	long t = m(r);
	long l = cast(long) (sqrt(4.0 * n + 1.0 * t * t) / 2 - t / 2);
	if (l == 0) l++;
	while (l <= r) {
		if (n % l == 0) {
			if (l * (l + s(l)) == n) return l;
		}
		l++;
	}
	return -1;
}

void main() {
	long n;
	readf("%d", &n);
	writeln(solve(n));
}


Formula One championship consists of series of races called Grand Prix. After every race drivers receive points according to their final position. Only the top 10 drivers receive points in the following order 25, 18, 15, 12, 10, 8, 6, 4, 2, 1. At the conclusion of the championship the driver with most points is the champion. If there is a tie, champion is the one with most wins (i.e. first places). If a tie still exists, it is chosen the one with most second places, and so on, until there are no more place to use for compare. Last year another scoring system was proposed but rejected. In it the champion is the one with most wins. If there is tie, champion is the one with most points. If a tie still exists it is proceeded the same way as in the original scoring system, that is comparing number of second, third, forth, and so on, places.You are given the result of all races during the season and you are to determine the champion according to both scoring systems. It is guaranteed, that both systems will produce unique champion.

The first line contain integer t (1≤t≤20), where t is the number of races. After that all races are described one by one. Every race description start with an integer n (1≤n≤50) on a line of itself, where n is the number of clasified drivers in the given race. After that n lines follow with the classification for the race, each containing the name of a driver. The names of drivers are given in order from the first to the last place. The name of the driver consists of lowercase and uppercase English letters and has length at most 50 characters. Comparing of names should be case-sensetive.

Your output should contain exactly two line. On the first line is the name of the champion according to the original rule, and on the second line the name of the champion according to the alternative rule.

It is not guaranteed that the same drivers participate in all races. For the championship consider every driver that has participated in at least one race. The total number of drivers during the whole season is not more then 50.

3
3
Hamilton
Vettel
Webber
2
Webber
Vettel
2
Hamilton
Vettel

2
7
Prost
Surtees
Nakajima
Schumacher
Button
DeLaRosa
Buemi
8
Alonso
Prost
NinoFarina
JimClark
DeLaRosa
Nakajima
Patrese
Surtees


import std.stdio;

const int MOD = 1000003;

int main() {
    int n;
    scanf("%d", &n);
    for (int i = 1; i <= 30; ++i)
	if (i * (i + 1) / 2 == n) {
	    writeln("YES");
	    return 0;
	}
    writeln("NO");
    return 0;
}

A triangular number is the number of dots in an equilateral triangle uniformly filled with dots. For example, three dots can be arranged in a triangle; thus three is a triangular number. The n-th triangular number is the number of dots in a triangle with n dots on a side. . You can learn more about these numbers from Wikipedia (http://en.wikipedia.org/wiki/Triangular_number).Your task is to find out if a given integer is a triangular number.

The first line contains the single number n (1≤n≤500) — the given integer.

If the given integer is a triangular number output YES, otherwise output NO.

import std.stdio;

const int MOD = 1000003;

int main() {
    int n;
    scanf("%d", &n);
    for (int i = 1; i <= 100; ++i)
	if (i * (i + 1) / 2 == n) {
	    writeln("YES");
	    return 0;
	}
    writeln("NO");
    return 0;
}


import std;

void main()
{
    readln().strip.to!int % 2 == 0 ? "YES".writeln : "NO".writeln;
}

One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.Pete and Billy are great fans of even numbers, that's why they want to divide the watermelon in such a way that each of the two parts weighs even number of kilos, at the same time it is not obligatory that the parts are equal. The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, if they can divide the watermelon in the way they want. For sure, each of them should get a part of positive weight.

The first (and the only) input line contains integer number w (1≤w≤100) — the weight of the watermelon bought by the boys.

Print YES, if the boys can divide the watermelon into two parts, each of them weighing even number of kilos; and NO in the opposite case.

For example, the boys can divide the watermelon into two parts of 2 and 6 kilos respectively (another variant — two parts of 4 and 4 kilos).

import std.stdio;

void main()
{
    int w;
    readf("%d", &w);

    writeln(w > 2 && w % 2 == 0 ? "YES" : "NO");
}


import std.stdio;
import std.conv;
import std.string;
import std.typecons;
import std.algorithm;
import std.array;
import std.range;
import std.math;
import std.regex;

void main()
{
  int[][] times;
  int sum, diff;

  auto input = readln().split().map!(to!int)();

  a:foreach (s; stdin.byLine()) {
  	auto t = s.split().map!(to!int)().array();

  	while (sum + t[1] > input[1]) {
  		if (t[1] - 1 >= t[0]) {
  			t[1]--;
  		} else {
  			diff = sum + t[1] - input[1];
  			foreach_reverse (tt; times) {
  				while (tt[0] != tt[1] && diff) {
  					tt[1]--;
  					diff--;
  					sum--;
  				}
  			}
  		}
  		if (diff) {writeln("u");break a;}
  	}

  	times ~= t;
  	sum += t[1];
  }

  if (sum != input[1] || diff) {
  	writeln("NO");
  } else {
  	writeln("YES");
  	foreach (t; times[0 .. $-1]) {
  		write(t[1], " ");
  	}
  	writeln(times[$-1][1]);
  }

}

Tomorrow Peter has a Biology exam. He does not like this subject much, but d days ago he learnt that he would have to take this exam. Peter's strict parents made him prepare for the exam immediately, for this purpose he has to study not less than minTimei and not more than maxTimei hours per each i-th day. Moreover, they warned Peter that a day before the exam they would check how he has followed their instructions.So, today is the day when Peter's parents ask him to show the timetable of his preparatory studies. But the boy has counted only the sum of hours sumTime spent him on preparation, and now he wants to know if he can show his parents a timetable sсhedule with d numbers, where each number sсhedulei stands for the time in hours spent by Peter each i-th day on biology studies, and satisfying the limitations imposed by his parents, and at the same time the sum total of all schedulei should equal to sumTime.

The first input line contains two integer numbers d,sumTime (1≤d≤30,0≤sumTime≤240) — the amount of days, during which Peter studied, and the total amount of hours, spent on preparation. Each of the following d lines contains two integer numbers minTimei,maxTimei (0≤minTimei≤maxTimei≤8), separated by a space — minimum and maximum amount of hours that Peter could spent in the i-th day.

In the first line print YES, and in the second line print d numbers (separated by a space), each of the numbers — amount of hours, spent by Peter on preparation in the corresponding day, if he followed his parents' instructions; or print NO in the unique line. If there are many solutions, print any of them.

import std.stdio;
import std.conv;
import std.string;
import std.typecons;
import std.algorithm;
import std.array;
import std.range;
import std.math;
import std.regex;

void main()
{
  int[][] times;
  int sum, diff;

  auto input = readln().split().map!(to!int)();

  a:foreach (s; stdin.byLine()) {
  	auto t = s.split().map!(to!int)().array();

  	while (sum + t[1] > input[1]) {
  		if (t[1] - 1 >= t[0]) {
  			t[1]--;
  		} else {
  			diff = sum + t[1] - input[1];
  			foreach_reverse (tt; times) {
  				while (tt[0] != tt[1] && diff) {
  					tt[1]--;
  					diff--;
  					sum--;
  				}
  			}
  		}
  		if (diff) break a;
  	}

  	times ~= t;
  	sum += t[1];
  }

  if (sum != input[1] || diff) {
  	writeln("NO");
  } else {
  	writeln("YES");
  	foreach (t; times[0 .. $-1]) {
  		write(t[1], " ");
  	}
  	writeln(times[$-1][1]);
  }

}


import std.stdio, std.range, std.string, std.conv, std.algorithm;
import std.math;

void main() {
    readln;
    int k, m;
    readf("%d %d\n", &k, &m);
    int[] a = readln.chomp.split.map!(to!int).array;
    int[] b = readln.chomp.split.map!(to!int).array;

    if (a[k - 1] < b[0]) {
        "YES".writeln;
    } else {
        "NO".writeln;
    }
}

You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.

The first line contains two integers nA,nB (1≤nA,nB≤10^5), separated by a space — the sizes of arrays A and B, correspondingly.
The second line contains two integers k and m (1≤k≤nA,1≤m≤nB), separated by a space.
The third line contains nA numbers a1,a2,... anA (-10^9≤a1≤a2≤...≤anA≤10^9), separated by spaces — elements of array A.
The fourth line contains nB integers b1,b2,... bnB (-10^9≤b1≤b2≤...≤bnB≤10^9), separated by spaces — elements of array B.

Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).

In the first sample test you can, for example, choose numbers 1 and 2 from array A and number 3 from array B (1 < 3 and 2 < 3).
In the second sample test the only way to choose k elements in the first array and m elements in the second one is to choose all numbers in both arrays, but then not all the numbers chosen in A will be less than all the numbers chosen in B: .

import std.stdio, std.range, std.string, std.conv, std.algorithm;
import std.math;

void main() {
    readln;
    int k, m;
    readf("%d %d\n", &k, &m);
    int[] a = readln.chomp.split.map!(to!int).array;
    int[] b = readln.chomp.split.map!(to!int).array;

    if (a[k - 1] < b[$ - m]) {
        "YES".writeln;
    } else {
        "NO".writeln;
    }
}


import std.stdio;
import std.string;
import std.format;

void main() {
    int n;
    string ans;
    formattedRead(strip(readln()), "%d", n);
    while(n-- > 0) {
        string s = strip(readln());
        if (s.length > 10)
            ans ~= s[0] ~ "10" ~ s[$ - 1];
        else
            ans ~= s;
        if (n > 0) ans ~= "\n";
    }
    writeln(ans);
}

Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n".You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.

The first line contains an integer n (1≤n≤100). Each of the following n lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.

Print n lines. The i-th line should contain the result of replacing of the i-th word from the input data.

4
word
localization
internationalization
pneumonoultramicroscopicsilicovolcanoconiosis

import std;

void main() {
    auto input = stdin.byLine();
    input.dropOne.each!(x => abbrev(x.to!string).writeln);
}

string abbrev(string word) {
    auto wl = word.length;
    return wl > 10 ? word[0].to!string ~ (wl-2).to!string ~ word[$-1].to!string : word;
}


import std.format;
import std.stdio;

void main() {
    int n, k, t;
    readf("%s %s %s\n", n, k, t);
    int progress = cast(int)(cast(real)(t * n * k) / 100.0);
    int full = progress / k;
    foreach (i; 0..full) "%d ".format(k).write;
    "%d ".format(progress - full * k).write;
    foreach (i; 0..n - full - 1) "%d ".format(0).write;
    writeln;
}

A progress bar is an element of graphical interface that displays the progress of a process for this very moment before it is completed. Let's take a look at the following form of such a bar.A bar is represented as n squares, located in line. To add clarity, let's number them with positive integers from 1 to n from the left to the right. Each square has saturation (ai for the i-th square), which is measured by an integer from 0 to k. When the bar for some i (1≤i≤n) is displayed, squares 1,2,... ,i-1 has the saturation k, squares i+1,i+2,... ,n has the saturation 0, and the saturation of the square i can have any value from 0 to k.So some first squares of the progress bar always have the saturation k. Some last squares always have the saturation 0. And there is no more than one square that has the saturation different from 0 and k.The degree of the process's completion is measured in percents. Let the process be t% completed. Then the following inequation is fulfilled: An example of such a bar can be seen on the picture. For the given n, k, t determine the measures of saturation for all the squares ai of the progress bar.

We are given 3 space-separated integers n, k, t (1≤n,k≤100, 0≤t≤100).

Print n numbers. The i-th of them should be equal to ai.

import std.format;
import std.stdio;

void main() {
    int n, k, t;
    readf("%s %s %s\n", n, k, t);
    int progress = cast(int)(cast(real)(t * n * k) / 100.0);
    int full = progress / k;
    foreach (i; 0..full) "%d ".format(k).write;
    if (full < n) {
        "%d ".format(progress - full * k).write;
        foreach (i; 0..n - full - 1) "%d ".format(0).write;
    }
    writeln;
}


import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.stdio;

int point(int x, int y) {
    if (32 * x <= y) return 3000;
    else if (16 * x <= y) return 2500;
    else if (8 * x <= y) return 2000;
    else if (4 * x <= y) return 1500;
    else if (2 * x <= y) return 1000;
    else return 500;
}

void main() {
    auto N = readln.chomp.to!int;
    auto A = N.iota.map!(_ => readln.split.map!(to!int).array).array;

    auto solved = new int[](5);
    foreach (i; 0..N) foreach (j; 0..5) if (A[i][j] != -1) solved[j] += 1;

    auto ud = new int[](5);
    foreach (i; 0..5) {
        if (A[0][i] == A[1][i]) ud[i] = 0;
        else if (A[0][i] == -1) ud[i] = -1;
        else if (A[1][i] == -1) ud[i] = 1;
        else if (A[0][i] > A[1][i]) ud[i] = -1;
        else if (A[0][i] < A[1][i]) ud[i] = 1;
    }

    auto P = new int[](N);
    foreach (i; 0..5) P[i] = point(solved[i], N);

    int ans = -1;
    foreach (i; 0..10000) {
        int v, p;
        foreach (j; 0..5) {
            if (ud[i] > 0) P[i] = point(solved[i], N);
            else P[i] = point(solved[i] + i, N);
            if (A[0][i] != -1) v += P[i] / 250 * (250 - A[0][i]);
            if (A[1][i] != -1) p += P[i] / 250 * (250 - A[1][i]);
        }
        if (v > p) {
            ans = i;
            break;
        }
    }

    ans.writeln;
}

Your security guard friend recently got a new job at a new security company. The company requires him to patrol an area of the city encompassing exactly N city blocks, but they let him choose which blocks. That is, your friend must walk the perimeter of a region whose area is exactly N blocks. Your friend is quite lazy and would like your help to find the shortest possible route that meets the requirements. The city is laid out in a square grid pattern, and is large enough that for the sake of the problem it can be considered infinite.

Input will consist of a single integer N (1≤N≤10^6), the number of city blocks that must be enclosed by the route.

Print the minimum perimeter that can be achieved.

Here are some possible shapes for the examples:

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop;

void main() {
    auto N = readln.chomp.to!int;
    int ans = 1 << 29;

    foreach (i; 1..10^^6+1) {
        int x = (N - 1) / i + 1;
        ans = min(ans, x * 2 + i * 2);
    }

    ans.writeln;
}


import std.algorithm;
import std.array;
import std.container;
import std.conv;
import std.math;
import std.range;
import std.stdio;
import std.string;
import std.typecons;

void main()
{
    auto s = readln.chomp.map!(to!dchar).array;

    int ans = 0;
    auto isPal = (dchar[] s) => s == s.retro.array;
    foreach ( st; 0..s.length ) {
        foreach ( end; st+1..s.length ) {
            if ( !isPal( s[st..end] ) ) ans = cast(int) max( ans, cast(int) end - st );
        }
    }

    writeln( ans );
}

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≤l≤r≤|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.

"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 std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, std.bitmanip, std.datetime;

bool is_p(string s) {
    int n = s.length.to!int;
    foreach (i; 0..n/2) if (s[i] != s[n-i-1]) return false;
    return true;
}

void main() {
    auto S = readln.chomp;
    auto N = S.length.to!int;

    foreach_reverse (i; 1..N+1) {
        foreach (j; 0..N-i+1) {
            if (!is_p(S[j..j+i])) {
                writeln(i);
                return;
            }
        }
    }

    writeln(0);
}

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


import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

immutable int limit = 20_000;

void main ()
{
	uint n;
	uint a, b, c, d;
	while (readf (" %s %s %s %s %s", &n, &a, &b, &c, &d) > 0)
	{
		auto s = new bool [limit];
		s[] = true;
		s[0] = false;
		s[1] = false;
		for (uint g = 2; g * g < limit; g++)
		{
			if (s[g])
			{
				for (uint e = g; e * g < limit; e++)
				{
					s[e * g] = false;
				}
			}
		}

		uint [] p;
		foreach (g; 0..limit)
		{
			if (s[g])
			{
				p ~= g;
			}
		}

		uint res = 0;
		n += 1;
		auto t = new bool [limit];
		for (uint start = 0; start < n; start += limit)
		{
			uint finish = min (start + limit, n);
			if (start == 0)
			{
				t[] = s[];
			}
			else
			{
				t[] = true;
				foreach (g; p)
				{
					uint lo = (start + g - 1) / g * g;
					while (lo < finish)
					{
						t[lo - start] = false;
						lo += g;
					}
				}
			}
			foreach (i; start..finish)
			{
				if (t[i - start])
				{
					uint cur = a;
					cur = cur * i + b;
					cur = cur * i + c;
					cur = cur * i + d;

					uint mult = 0;
					uint k = n;
					while (k > 0)
					{
						k /= i;
						mult += k;
					}
					res += cur * mult;
				}
			}
		}
		writeln (res);
	}
}

Notice: unusual memory limit!After the war, destroyed cities in the neutral zone were restored. And children went back to school.The war changed the world, as well as education. In those hard days, a new math concept was created.As we all know, logarithm function can be described as: $$$$$$ \log(p_1^{a_1}p_2^{a_2}...p_k^{a_2}) = a_1 \log p_1 + a_2 \log p_2 + ... + a_k \log p_k $$$$$$ Where $$$p_1^{a_1}p_2^{a_2}...p_k^{a_2}$$$ is the prime factorization of a integer. A problem is that the function uses itself in the definition. That is why it is hard to calculate.So, the mathematicians from the neutral zone invented this: $$$$$$ \text{exlog}_f(p_1^{a_1}p_2^{a_2}...p_k^{a_2}) = a_1 f(p_1) + a_2 f(p_2) + ... + a_k f(p_k) $$$$$$Notice that $$$\text{exlog}_f(1)$$$ is always equal to $$$0$$$.This concept for any function $$$f$$$ was too hard for children. So teachers told them that $$$f$$$ can only be a polynomial of degree no more than $$$3$$$ in daily uses (i.e., $$$f(x) = Ax^3+Bx^2+Cx+D$$$)."Class is over! Don't forget to do your homework!" Here it is: $$$$$$ \sum_{i=1}^n \text{exlog}_f(i) $$$$$$Help children to do their homework. Since the value can be very big, you need to find the answer modulo $$$2^{32}$$$.

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

immutable int limit = 50_000;

void main ()
{
	auto s = new bool [limit];
	s[] = true;
	s[0] = false;
	s[1] = false;
	for (uint g = 2; g * g < limit; g++)
	{
		if (s[g])
		{
			for (uint e = g; e * g < limit; e++)
			{
				s[e * g] = false;
			}
		}
	}

	uint [] p;
	foreach (g; 0..limit)
	{
		if (s[g])
		{
			p ~= g;
		}
	}

	uint n;
	uint a, b, c, d;
	while (readf (" %s %s %s %s %s", &n, &a, &b, &c, &d) > 0)
	{
		uint res = 0;
		auto t = new bool [limit];
		for (uint start = 0; start <= n; start += limit)
		{
			uint finish = min (start + limit, n + 1);
			if (start == 0)
			{
				t[] = s[];
			}
			else
			{
				t[] = true;
				foreach (g; p)
				{
					uint lo = (start + g - 1) / g * g;
					while (lo < finish)
					{
						t[lo - start] = false;
						lo += g;
					}
				}
			}
			foreach (i; start..finish)
			{
				if (t[i - start])
				{
					debug {writeln (i);}
					uint cur = a;
					cur = cur * i + b;
					cur = cur * i + c;
					cur = cur * i + d;

					uint mult = 0;
					uint k = n;
					while (k > 0)
					{
						k /= i;
						mult += k;
					}
					res += cur * mult;
				}
			}
		}
		writeln (res);
	}
}


import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto d = readln.splitter.map !(to !(long)).array;
		auto s = readln.strip;

		auto need = new long [n + 1];
		auto grassAhead = new long [n + 1];
		long cur = 0;
		need[n] = cur;
		grassAhead[n] = 0;
		foreach_reverse (i; 0..n)
		{
			grassAhead[i] = grassAhead[i + 1];
			switch (s[i])
			{
				case 'G': cur -= d[i];
				    grassAhead[i] += d[i]; break;
				case 'W': cur -= d[i]; break;
				case 'L': cur += d[i]; break;
				default: assert (false);
			}
			cur = max (cur, 0);
			need[i] = cur;
		}
		debug {writeln (need);}

		bool seenWater = false;
		long res = 0;
		long energy = 0;
		long walkDist = 0;
		long swimDist = 0;
		long grassFlown = 0;
		foreach (i; 0..n)
		{
			switch (s[i])
			{
				case 'G': energy += d[i];
				    res += d[i] * 5; break;
				case 'W': energy += d[i];
				    seenWater = true;
				    res += d[i] * 3; break;
				case 'L': energy -= d[i];
				    res += d[i] * 1; break;
				default: assert (false);
			}
			if (energy < 0)
			{
				res += (seenWater ? 3 : 5) * (-energy);
				energy = 0;
			}
			if (energy > need[i + 1])
			{
				auto delta = energy - need[i + 1];
				auto deltaGrass = min (delta,
				    grassAhead[i] - grassFlown);
				grassFlown += deltaGrass;
				res -= 2 * deltaGrass;
				res -= 1 * (delta - deltaGrass);
				energy = need[i + 1];
			}
			if (s[i] == 'G')
			{
				grassFlown = max (grassFlown - d[i], 0);
			}
		}

		writeln (res);
	}
}

Bob is a duck. He wants to get to Alice's nest, so that those two can duck!  Duck is the ultimate animal! (Image courtesy of See Bang)The journey can be represented as a straight line, consisting of $$$n$$$ segments. Bob is located to the left of the first segment, while Alice's nest is on the right of the last segment. Each segment has a length in meters, and also terrain type: grass, water or lava. Bob has three movement types: swimming, walking and flying. He can switch between them or change his direction at any point in time (even when he is located at a non-integer coordinate), and doing so doesn't require any extra time. Bob can swim only on the water, walk only on the grass and fly over any terrain. Flying one meter takes $$$1$$$ second, swimming one meter takes $$$3$$$ seconds, and finally walking one meter takes $$$5$$$ seconds.Bob has a finite amount of energy, called stamina. Swimming and walking is relaxing for him, so he gains $$$1$$$ stamina for every meter he walks or swims. On the other hand, flying is quite tiring, and he spends $$$1$$$ stamina for every meter flown. Staying in place does not influence his stamina at all. Of course, his stamina can never become negative. Initially, his stamina is zero.What is the shortest possible time in which he can reach Alice's nest?

The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of segments of terrain.
The second line contains $$$n$$$ integers $$$l_1, l_2, \dots, l_n$$$ ($$$1 \leq l_i \leq 10^{12}$$$). The $$$l_i$$$ represents the length of the $$$i$$$-th terrain segment in meters.
The third line contains a string $$$s$$$ consisting of $$$n$$$ characters "G", "W", "L", representing Grass, Water and Lava, respectively.
It is guaranteed that the first segment is not Lava.

Output a single integer $$$t$$$ — the minimum time Bob needs to reach Alice.

import std.algorithm;
import std.conv;
import std.range;
import std.stdio;
import std.string;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		readln;
		auto d = readln.splitter.map !(to !(long)).array;
		auto s = readln.strip;

		auto need = new long [n + 1];
		auto grassAhead = new long [n + 1];
		long cur = 0;
		need[n] = cur;
		grassAhead[n] = 0;
		foreach_reverse (i; 0..n)
		{
			grassAhead[i] = grassAhead[i + 1];
			switch (s[i])
			{
				case 'G': cur -= d[i];
				    grassAhead[i] += d[i] * 2; break;
				case 'W': cur -= d[i]; break;
				case 'L': cur += d[i]; break;
				default: assert (false);
			}
			cur = max (cur, 0);
			need[i] = cur;
		}
		debug {writeln (need);}
		debug {writeln (grassAhead);}

		bool seenWater = false;
		long res = 0;
		long energy = 0;
		long walkDist = 0;
		long swimDist = 0;
		long grassFlown = 0;
		foreach (i; 0..n)
		{
			switch (s[i])
			{
				case 'G': energy += d[i];
				    res += d[i] * 5; break;
				case 'W': energy += d[i];
				    seenWater = true;
				    res += d[i] * 3; break;
				case 'L': energy -= d[i];
				    res += d[i] * 1; break;
				default: assert (false);
			}
			if (energy < 0)
			{
				res += (seenWater ? 3 : 5) * (-energy);
				energy = 0;
			}
			if (energy > need[i + 1])
			{
				auto delta = energy - need[i + 1];
				auto deltaGrass = min (delta,
				    grassAhead[i] - grassFlown);
				grassFlown += deltaGrass;
				res -= 2 * deltaGrass;
				res -= 1 * (delta - deltaGrass);
				energy = need[i + 1];
			}
			if (s[i] == 'G')
			{
				grassFlown = max (grassFlown - d[i] * 2, 0);
			}
			debug {writeln (grassFlown);}
		}

		writeln (res);
	}
}


import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.string;

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(x => x.to!long % 2).array;

    auto cnt = A.count(1);

    if (cnt % 2 == 1 && (N - cnt) % 2 == 1) {
        writeln("NO");
        return;
    }

    if ((N-1).iota.map!(i => A[i] != A[i+1]).all) {
        writeln("NO");
        return;
    }

    writeln("YES");
}

Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.The current state of the wall can be respresented by a sequence $$$a$$$ of $$$n$$$ integers, with $$$a_i$$$ being the height of the $$$i$$$-th part of the wall.Vova can only use $$$2 \times 1$$$ bricks to put in the wall (he has infinite supply of them, however).Vova can put bricks horizontally on the neighboring parts of the wall of equal height. It means that if for some $$$i$$$ the current height of part $$$i$$$ is the same as for part $$$i + 1$$$, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part $$$1$$$ of the wall or to the right of part $$$n$$$ of it).The next paragraph is specific to the version 1 of the problem.Vova can also put bricks vertically. That means increasing height of any part of the wall by 2.Vova is a perfectionist, so he considers the wall completed when:  all parts of the wall has the same height;  the wall has no empty spaces inside it. Can Vova complete the wall using any amount of bricks (possibly zero)?

The first line contains a single integer $$$n$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$) — the number of parts in the wall.
The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^9$$$) — the initial heights of the parts of the wall.

Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero).
Print "NO" otherwise.

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.string;

void main() {
    auto N = readln.chomp.to!int;
    auto A = readln.split.map!(x => x.to!long % 2).array;

    bool solve() {
        if (A.count(1) % 2 == 1) {
            return false;
        }

        auto even = iota(0, N, 2).filter!(i => A[i] == 1).array.length;
        auto odd = iota(1, N, 2).filter!(i => A[i] == 1).array.length;
        return even == odd;
    }

    if (solve) {
        writeln("YES");
        return;
    }

    foreach (i; 0..N) A[i] ^= 1;

    if (solve) {
        writeln("YES");
        return;
    }

    writeln("NO");
}


import std.stdio;
import std.container;
import std.random;
import std.range;
import std.algorithm;
import std.typecons;
import std.conv;
import std.format;

int[] par;
long[] smallest;

int find_set(int v) {
	if (v == par[v]) return v;
	return par[v] = find_set(par[v]);
}

Mt19937 rng;

void unite(int a, int b) {
	a = find_set(a);
	b = find_set(b);
	if (rng.front % 2) swap(a, b);
	rng.popFront();
	par[b] = a;
	smallest[a] = min(smallest[a], smallest[b]);
}

void main()
{
	par = iota(200000).array;

	int n, m;
	stdin.byLine.front.formattedRead!"%d %d"(n, m);

	auto S = redBlackTree!(Tuple!(long, int));
	auto offers = redBlackTree!(Tuple!(long, int, int));

	smallest = stdin.byLine.front.split(" ").map!`parse!long(a)`.array;

	smallest.writeln;

	foreach (i, e; smallest) {
		S.insert(tuple(e, i.to!int));
	}

	for (int i = 0; i < m; i++) {
		int a, b;
		long w;
		stdin.byLine.front.formattedRead!"%d %d %d"(a, b, w);

		a--; b--;
		offers.insert(tuple(w, a, b));
	}

	long totalCost = 0;
	while (true) {
		if (S.length == 1) {
			writeln(totalCost);
			return;
		}

		while (offers.length > 0 && find_set(offers.front[1]) == find_set(offers.front[2]))
			offers.removeFront();

		auto c1 = S.front; S.removeFront();
		auto c2 = S.front; S.removeFront();
		auto cost = c1[0] + c2[0];

		if (offers.length > 0 && offers.front[0] < cost) {
			S.insert([c1, c2]);
			totalCost += offers.front[0];
			int x = offers.front[1];
			int y = offers.front[2];

			int setx = find_set(x);
			int sety = find_set(y);

			S.removeKey(tuple(smallest[setx], setx));
			S.removeKey(tuple(smallest[sety], sety));
			unite(x, y);
			int setxy = find_set(x);
			S.insert(tuple(smallest[setxy], setxy));
		} else {
			totalCost += cost;
			int x = c1[1];
			int y = c2[1];
			unite(x, y);

			int setxy = find_set(x);
			S.insert(tuple(smallest[setxy], setxy));
		}
	}
}

You are given an undirected graph consisting of $$$n$$$ vertices. A number is written on each vertex; the number on vertex $$$i$$$ is $$$a_i$$$. Initially there are no edges in the graph.You may add some edges to this graph, but you have to pay for them. The cost of adding an edge between vertices $$$x$$$ and $$$y$$$ is $$$a_x + a_y$$$ coins. There are also $$$m$$$ special offers, each of them is denoted by three numbers $$$x$$$, $$$y$$$ and $$$w$$$, and means that you can add an edge connecting vertices $$$x$$$ and $$$y$$$ and pay $$$w$$$ coins for it. You don't have to use special offers: if there is a pair of vertices $$$x$$$ and $$$y$$$ that has a special offer associated with it, you still may connect these two vertices paying $$$a_x + a_y$$$ coins for it.What is the minimum number of coins you have to spend to make the graph connected? Recall that a graph is connected if it's possible to get from any vertex to any other vertex using only the edges belonging to this graph.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \\le n \\le 2 \\cdot 10^5$$$, $$$0 \\le m \\le 2 \\cdot 10^5$$$) — the number of vertices in the graph and the number of special offers, respectively.
The second line contains $$$n$$$ integers $$$a_1, a_2, \\dots, a_n$$$ ($$$1 \\le a_i \\le 10^{12}$$$) — the numbers written on the vertices.
Then $$$m$$$ lines follow, each containing three integers $$$x$$$, $$$y$$$ and $$$w$$$ ($$$1 \\le x, y \\le n$$$, $$$1 \\le w \\le 10^{12}$$$, $$$x \\ne y$$$) denoting a special offer: you may add an edge connecting vertex $$$x$$$ and vertex $$$y$$$, and this edge will cost $$$w$$$ coins.

Print one integer — the minimum number of coins you have to pay to make the graph connected.

import std.stdio, std.array, std.string, std.conv, std.algorithm;
import std.typecons, std.range, std.random, std.math, std.container;
import std.numeric, std.bigint, core.bitop, core.stdc.string;

void main() {
    auto s = readln.split.map!(to!int);
    auto N = s[0];
    auto M = s[1];
    auto A = readln.split.map!(to!long).array;
    auto X = new Tuple!(int, long)[][](N);
    foreach (i; 0..M) {
        auto t = readln.split;
        auto u = t[0].to!int - 1;
        auto v = t[1].to!int - 1;
        auto w = t[2].to!long;
        X[u] ~= tuple(v, w);
        X[v] ~= tuple(u, w);
    }

    long ans = 0;
    int S = A.minIndex.to!int;
    auto pq = new BinaryHeap!(Array!(Tuple!(int, long)), "a[1] > b[1]")();
    auto used = new bool[](N);
    used[S] = true;

    foreach (i; 0..N) {
        if (i == S) continue;
        pq.insert(tuple(i, A[S] + A[i]));
    }

    foreach (t; X[S]) {
        pq.insert(tuple(t[0], t[1]));
    }

    while (!pq.empty) {
        auto t = pq.front;
        pq.removeFront;
        auto u = t[0];
        auto w = t[1];
        if (used[u]) continue;
        ans += w;
        used[u] = true;
        foreach (v; X[u]) {
            if (used[v[0]]) continue;
            pq.insert(tuple(v[0], v[1]));
        }
    }

    ans.writeln;
}


void main() {
import std.stdio;
writeln(long.sizeof);
}

This problem is same as the next one, but has smaller constraints.It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system consisting of many chimneys, electric poles, and wires. Since they are cats, they found those things gigantic.At the entrance of the station, there is a map describing the complicated wiring system. Selena is the best at math among three friends. He decided to draw the map on the Cartesian plane. Each pole is now a point at some coordinates $$$(x_i, y_i)$$$. Since every pole is different, all of the points representing these poles are distinct. Also, every two poles are connected with each other by wires. A wire is a straight line on the plane infinite in both directions. If there are more than two poles lying on the same line, they are connected by a single common wire.Selena thinks, that whenever two different electric wires intersect, they may interfere with each other and cause damage. So he wonders, how many pairs are intersecting? Could you help him with this problem?

The first line contains a single integer $$$n$$$ ($$$2 \\le n \\le 50$$$) — the number of electric poles.
Each of the following $$$n$$$ lines contains two integers $$$x_i$$$, $$$y_i$$$ ($$$-10^4 \\le x_i, y_i \\le 10^4$$$) — the coordinates of the poles.
It is guaranteed that all of these $$$n$$$ points are distinct.

Print a single integer — the number of pairs of wires that are intersecting.

import std.stdio, std.conv, std.string;
import std.array, std.range, std.algorithm, std.container;
import std.math, std.random, std.bigint, std.datetime, std.format;
string read(){ static string[] ss; while(!ss.length) ss = readln.chomp.split; string res = ss[0]; ss.popFront; return res; }

int DEBUG_LEVEL = 0;
void print()(){ writeln(""); }
void print(T, A ...)(T t, lazy A a){ write(t), print(a); }
void print(int level, T, A ...)(T t, lazy A a){ if(level <= DEBUG_LEVEL) print(t, a); }

void main(string[] args){
	if(args.length > 1 && args[1] == "-debug"){
		if(args.length > 2 && args[2].isNumeric) DEBUG_LEVEL = args[2].to!int;
		else DEBUG_LEVEL = 1;
	}

	int n = read.to!int;
	long[] xs, ys;
	foreach(i; 0 .. n) xs ~= read.to!int, ys ~= read.to!int;

	print!1("xs:", xs);
	print!1("ys:", ys);

	long[long] kcnt;
	bool[long] mset;
	foreach(i; 0 .. n) foreach(j; 0 .. i){
		long dx = xs[i] - xs[j];
		long dy = ys[i] - ys[j];
		long c = dx * ys[i] - dy * xs[i];
		print!1("dx:", dx, " dy:", dy, " c:", c);

		if(dx == 0){
			if(dy < 0) dy = -dy, c = -c;
			long g = gcd(dy, c);
			dy /= g, c /= g;
		}
		else if(dy == 0){
			if(dx < 0) dx = -dx, c = -c;
			long g = gcd(dx, c);
			dx /= g, c /= g;
		}
		else if(c == 0){
			if(dx < 0) dx = -dx, dy = -dy;
			long g = gcd(dx, dy);
			dx /= g, dy /= g;
		}
		else{
			if(dx < 0) dx = -dx, dy = -dy, c = -c;
			long g = gcd(gcd(dx, dy), c);
			dx /= g, dy /= g, c /= g;
		}

		print!1(" -> dx:", dx, " dy:", dy, " c:", c);

		long k = 100000 * dy + dx;
		long m = k * 10000000 + c;
		if(m !in mset){
			if(k !in kcnt) kcnt[k] = 0;
			mset[m] = 1;
			kcnt[k] += 1;
		}
	}
	print!1("kcnt:", kcnt);
	print!1("mset:", mset);

	long[] ks = kcnt.keys;
	long[] ms = mset.keys;
	long ans = ms.length * (ms.length - 1) / 2;
	foreach(k; ks) ans -= kcnt[k] * (kcnt[k] - 1) / 2;
	ans.writeln;

}
long gcd(long a, long b){
	if(b == 0) return a;
	if(b < 0) return gcd(a, -b);
	if(a % b == 0) return b;
	if(a < b) return gcd(b, a);
	else return gcd(b, a % b);
}

/*

"How many different direction vectors can we have?"

(x1, y1), (x2, y2) -> (x1 - x2, y1 - y2).
here x1 - x2 and y1 - y2 are relatively prime and x1 - x2 > 0,
or (1, 0), or (0, 1).

O(N^2) = 1000 x 1000.

(y1 - y2)(x - x1) - (x1 - x2)(y - y1) = 0
dy x - dx y + dx y1 - dy x1 = 0

*/