This is an interactive problem.Vladik has favorite game, in which he plays all his free time.Game field could be represented as n × m matrix which consists of cells of three types:   «.» — normal cell, player can visit it.  «F» — finish cell, player has to finish his way there to win. There is exactly one cell of this type.  «*» — dangerous cell, if player comes to this cell, he loses. Initially player is located in the left top cell with coordinates (1, 1). Player has access to 4 buttons "U", "D", "L", "R", each of them move player up, down, left and right directions respectively.But it’s not that easy! Sometimes friends play game and change functions of buttons. Function of buttons "L" and "R" could have been swapped, also functions of buttons "U" and "D" could have been swapped. Note that functions of buttons can be changed only at the beginning of the game.Help Vladik win the game!

First line contains two space-separated integers n and m (1 ≤ n, m ≤ 100) — number of rows and columns respectively. Each of next n lines contains m characters describing corresponding row of field. Set of characters in field is described above. Guaranteed that cell with coordinates (1, 1) is normal and there is at least one way from initial cell to finish cell without dangerous cells.

NoteIn first test case all four directions swapped with their opposite directions. Protocol of interaction In more convenient form:This test could be presenter for hack in following way: 4 3 1 1...**.F*....

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.stdlib;;

void main() {
    immutable int INF = 1 << 28;

    auto s = readln.split.map!(to!int);
    auto H = s[0];
    auto W = s[1];
    auto B = H.iota.map!(_ => readln.chomp).array;

    int gr, gc;
    foreach (i; 0..H) foreach (j; 0..W) if (B[i][j] == 'F') gr = i, gc = j;

    int[] dr = [0, 0, -1, 1];
    int[] dc = [-1, 1, 0, 0];
    auto dist = new int[](H * W);
    fill(dist, INF);
    dist[0] = 0;
    auto prev = new int[](H * W);
    fill(prev, -1);
    alias Tuple!(int, "from", int, "to", int, "cost") Edge;
    auto q = new BinaryHeap!(Array!Edge, "a.cost >= b.cost");
    q.insert(Edge(-1, 0, 0));

    while (!q.empty) {
        auto n = q.front;
        auto pr = n.from / W;
        auto pc = n.from % W;
        auto r = n.to / W;
        auto c = n.to % W;
        q.removeFront;
        if (dist[n.to] < n.cost)
            continue;
        dist[n.to] = n.cost;
        prev[n.to] = n.from;

        foreach (i; 0..4) {
            auto nr = r + dr[i];
            auto nc = c + dc[i];
            auto next = nr * W + nc;
            if (nr < 0 || nr >= H || nc < 0 || nc >= W || B[nr][nc] == '*')
                continue;
            if (dist[next] <= dist[n.to] + 1)
                continue;
            dist[next] = dist[n.to] + 1;
            q.insert(Edge(n.to, next, dist[n.to] + 1));
        }
    }

    int[] root;
    int x = gr * W + gc;
    while (prev[x] != -1) {
        root = x ~ root;
        x = prev[x];
    }

    bool swapLR, swapUD;
    Tuple!(int, int) cmd(char dir) {
        if      (swapLR && dir == 'L') dir = 'R';
        else if (swapLR && dir == 'R') dir = 'L';
        else if (swapUD && dir == 'U') dir = 'D';
        else if (swapUD && dir == 'D') dir = 'U';

        writeln(dir);
        stdout.flush;
        s = readln.split.map!(to!int);

        if (s[0] - 1 == gr && s[1] - 1 == gc)
            exit(0);
        return tuple(s[0] - 1, s[1] - 1);
    }

    Tuple!(int, int) pos;

    if (H == 1) {
        pos = cmd('R');
        if (pos[1] == 0) swapLR = true;
        while (true) pos = cmd('R');
        return;
    }
    if (W == 1) {
        pos = cmd('D');
        if (pos[0] == 0) swapUD = true;
        while (true) pos = cmd('D');
        return;
    }

    if (B[0][1] != '*') {
        pos = cmd('R');
        if (pos[1] == 0) swapLR = true;
        pos = cmd('L');
        while (true) {
            if (B[pos[0]+1][pos[1]] != '*')
                break;
            pos = cmd('R');
        }
        pos = cmd('D');
        if (pos[0] == 0) swapUD = true;
        pos = cmd('U');
        while (pos[1] != 0) pos = cmd('L');
    }
    else {
        pos = cmd('D');
        if (pos[0] == 0) swapUD = true;
        pos = cmd('D');
        while (true) {
            if (B[pos[0]][pos[1]+1] != '*')
                break;
            pos = cmd('D');
        }
        pos = cmd('R');
        if (pos[1] == 0) swapLR = true;
        pos = cmd('L');
        while (pos[0] != 0) pos = cmd('U');
    }

    foreach (co; root) {
        int nr = co / W;
        int nc = co % W;
        if (pos[0] - nr == 1) pos = cmd('U');
        else if (pos[0] - nr == -1) pos = cmd('D');
        else if (pos[1] - nc == 1) pos = cmd('L');
        else pos = cmd('R');
    }
}

import core.bitop;
import core.checkedint;
//import core.stdc.stdio;
import core.stdc.stdlib;
import core.stdc.string;
import std.algorithm;
import std.array;
import std.ascii;
import std.bigint;
import std.bitmanip;
import std.container;
import std.conv;
import std.exception;
import std.functional;
import std.math;
import std.meta;
import std.numeric;
import std.random;
import std.range;
import std.regex;
import std.stdio;
import std.string;
import std.typecons;
import std.variant;

__gshared:

alias BitSet(size_t n) = size_t[(n + size_t.sizeof * 8 - 1) / (size_t.sizeof * 8)];

auto getAddrTuple() {
    return tuple();
}

auto getAddrTuple(T, U...)(ref T head, ref U tail) {
    return tuple(&head, getAddrTuple(tail).expand);
}

bool read(T...)(ref T vars) if (vars.length > 0) {
    return readf(' ' ~ replicate("%s ", vars.length), getAddrTuple(vars).expand) == vars.length;
}

T[ ] allocate(T)(size_t n) {
    return (cast(T*)malloc(n * T.sizeof))[0 .. n];
}

auto pairwise(R)(R range) if (isForwardRange!R) {
    return lockstep(range, dropOne(range));
}

alias Pos = Tuple!(int, `y`, int, `x`);

enum { U, R, D, L }

char[101][100] grid;
char[100][100] way;
Pos[10^^4] q;
char[4] dirs = "URDL";
Pos cur, finish;

void move(int d) {
    writeln(dirs[d]);
    stdout.flush();
    readf(" %s %s", &cur.y, &cur.x);
    if (!~cur.y)
        exit(1);
    cur.y--;
    cur.x--;
    if (cur == finish)
        exit(0);
}

void swapLR() {
    dirs[R] = 'L';
    dirs[L] = 'R';
}

void swapUD() {
    dirs[D] = 'U';
    dirs[U] = 'D';
}

void main() {
    int n, m;
    readf("%s %s ", &n, &m);
    memset(grid.ptr, '*', grid.sizeof);
    foreach (int i, ref row; grid[0 .. n]) {
        auto s = row[ ];
        readln(s);
        s[$ - 1] = '*';
        auto tail = s[0 .. m].find('F');
        if (!tail.empty)
            finish = Pos(i, m - cast(int)tail.length);
    }
    assert(finish.y || finish.x);

    if (n == 1) {
        move(R);
        if (!cur.x)
            swapLR();
        while (true)
            move(R);
    }

    if (m == 1) {
        move(D);
        if (!cur.y)
            swapUD();
        while (true)
            move(D);
    }

    const lrFound = grid[0][1] != '*';
    if (lrFound) {
        move(R);
        if (!cur.x)
            swapLR();
        else
            move(L);
    }

    const udFound = grid[1][0] != '*';
    if (udFound) {
        move(D);
        if (!cur.y)
            swapUD();
        else
            move(U);
    }

    if (!lrFound) {
        assert(udFound);
        foreach (i; 1 .. n) {
            assert(grid[i][0] != '*');
            if (grid[i][1] != '*') {
                foreach (k; 0 .. i)
                    move(D);
                move(R);
                if (!cur.x)
                    swapLR();
                break;
            }
        }
    } else if (!udFound) {
        assert(lrFound);
        foreach (j; 1 .. m) {
            assert(grid[0][j] != '*');
            if (grid[1][j] != '*') {
                foreach (k; 0 .. j)
                    move(R);
                move(D);
                if (!cur.y)
                    swapUD();
                break;
            }
        }
    }

    int qr = 0, qw = 1;
    q[0] = finish;
    while (true) {
        assert(qr != qw);
        Pos p = q[qr++];
        if (p == cur)
            while (true)
                move(way[cur.y][cur.x]);

        enum gen(string cond, char c) = `
            if (`~cond~` && grid[nextPos.y][nextPos.x] != '*') {
                grid[nextPos.y][nextPos.x] = '*';
                way[nextPos.y][nextPos.x] = `~c~`;
                q[qw++] = nextPos;
            }
        `;

        Pos nextPos = Pos(p.y - 1, p.x);
        mixin(gen!(`nextPos.y >= 0`, 'D'));
        nextPos = Pos(p.y, p.x + 1);
        mixin(gen!(`nextPos.x < m`, 'L'));
        nextPos = Pos(p.y + 1, p.x);
        mixin(gen!(`nextPos.y < n`, 'U'));
        nextPos = Pos(p.y, p.x - 1);
        mixin(gen!(`nextPos.x >= 0`, 'R'));
    }
}

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() {
    immutable int INF = 1 << 28;

    auto s = readln.split.map!(to!int);
    auto H = s[0];
    auto W = s[1];
    auto B = H.iota.map!(_ => readln.chomp).array;

    int gr, gc;
    foreach (i; 0..H) foreach (j; 0..W) if (B[i][j] == 'F') gr = i, gc = j;

    int[] dr = [0, 0, -1, 1];
    int[] dc = [-1, 1, 0, 0];
    auto dist = new int[](H * W);
    fill(dist, INF);
    dist[0] = 0;
    auto prev = new int[](H * W);
    fill(prev, -1);
    alias Tuple!(int, "from", int, "to", int, "cost") Edge;
    auto q = new BinaryHeap!(Array!Edge, "a.cost >= b.cost");
    q.insert(Edge(-1, 0, 0));

    while (!q.empty) {
        auto n = q.front;
        auto pr = n.from / W;
        auto pc = n.from % W;
        auto r = n.to / W;
        auto c = n.to % W;
        q.removeFront;
        if (dist[n.to] < n.cost)
            continue;
        dist[n.to] = n.cost;
        prev[n.to] = n.from;

        foreach (i; 0..4) {
            auto nr = r + dr[i];
            auto nc = c + dc[i];
            auto next = nr * W + nc;
            if (nr < 0 || nr >= H || nc < 0 || nc >= W || B[nr][nc] == '*')
                continue;
            if (dist[next] <= dist[n.to] + 1)
                continue;
            dist[next] = dist[n.to] + 1;
            q.insert(Edge(n.to, next, dist[n.to] + 1));
        }
    }

    int[] root;
    int x = gr * W + gc;
    while (prev[x] != -1) {
        root = x ~ root;
        x = prev[x];
    }

    bool swapLR, swapUD;
    Tuple!(int, int) cmd(char dir) {
        if      (swapLR && dir == 'L') dir = 'R';
        else if (swapLR && dir == 'R') dir = 'L';
        else if (swapUD && dir == 'U') dir = 'D';
        else if (swapUD && dir == 'D') dir = 'U';

        writeln(dir);
        stdout.flush;
        s = readln.split.map!(to!int);
        return tuple(s[0] - 1, s[1] - 1);
    }

    Tuple!(int, int) pos;

    if (H == 1) {
        pos = cmd('R');
        if (pos[1] == 0) swapLR = true;
        while (pos[0] != gr || pos[1] != gc) pos = cmd('R');
        return;
    }
    if (W == 1) {
        pos = cmd('D');
        if (pos[0] == 0) swapUD = true;
        while (pos[0] != gr || pos[1] != gc) pos = cmd('D');
        return;
    }

    if (B[0][1] == '.') {
        pos = cmd('R');
        if (pos[1] == 0) swapLR = true;
        while (true) {
            if (pos[0] == gr && pos[1] == gc)
                return;
            if (B[pos[0]+1][pos[1]] == '.')
                break;
            pos = cmd('R');
        }
        pos = cmd('D');
        if (pos[0] == 0) swapUD = true;
        pos = cmd('U');
        while (pos[1] != 0) pos = cmd('L');
    }
    else {
        pos = cmd('D');
        if (pos[0] == 0) swapUD = true;
        while (true) {
            if (pos[0] == gr && pos[1] == gc)
                return;
            if (B[pos[0]][pos[1]+1] == '.')
                break;
            pos = cmd('D');
        }
        pos = cmd('R');
        if (pos[1] == 0) swapLR = true;
        pos = cmd('L');
        while (pos[0] != 0) pos = cmd('U');
    }

    foreach (co; root) {
        int nr = co / W;
        int nc = co % W;
        if (pos[0] - nr == 1) pos = cmd('U');
        else if (pos[0] - nr == -1) pos = cmd('D');
        else if (pos[1] - nc == 1) pos = cmd('L');
        else pos = cmd('R');
    }
}

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.stdlib;;

void main() {
    immutable int INF = 1 << 28;

    auto s = readln.split.map!(to!int);
    auto H = s[0];
    auto W = s[1];
    auto B = H.iota.map!(_ => readln.chomp).array;

    int gr, gc;
    foreach (i; 0..H) foreach (j; 0..W) if (B[i][j] == 'F') gr = i, gc = j;

    int[] dr = [0, 0, -1, 1];
    int[] dc = [-1, 1, 0, 0];
    auto dist = new int[](H * W);
    fill(dist, INF);
    dist[0] = 0;
    auto prev = new int[](H * W);
    fill(prev, -1);
    alias Tuple!(int, "from", int, "to", int, "cost") Edge;
    auto q = new BinaryHeap!(Array!Edge, "a.cost >= b.cost");
    q.insert(Edge(-1, 0, 0));

    while (!q.empty) {
        auto n = q.front;
        auto pr = n.from / W;
        auto pc = n.from % W;
        auto r = n.to / W;
        auto c = n.to % W;
        q.removeFront;
        if (dist[n.to] < n.cost)
            continue;
        dist[n.to] = n.cost;
        prev[n.to] = n.from;

        foreach (i; 0..4) {
            auto nr = r + dr[i];
            auto nc = c + dc[i];
            auto next = nr * W + nc;
            if (nr < 0 || nr >= H || nc < 0 || nc >= W || B[nr][nc] == '*')
                continue;
            if (dist[next] <= dist[n.to] + 1)
                continue;
            dist[next] = dist[n.to] + 1;
            q.insert(Edge(n.to, next, dist[n.to] + 1));
        }
    }

    int[] root;
    int x = gr * W + gc;
    while (prev[x] != -1) {
        root = x ~ root;
        x = prev[x];
    }

    bool swapLR, swapUD;
    Tuple!(int, int) cmd(char dir) {
        if      (swapLR && dir == 'L') dir = 'R';
        else if (swapLR && dir == 'R') dir = 'L';
        else if (swapUD && dir == 'U') dir = 'D';
        else if (swapUD && dir == 'D') dir = 'U';

        writeln(dir);
        stdout.flush;
        s = readln.split.map!(to!int);

        if (s[0] - 1 == gr && s[1] - 1 == gc)
            exit(0);
        return tuple(s[0] - 1, s[1] - 1);
    }

    Tuple!(int, int) pos;

    if (H == 1) {
        pos = cmd('R');
        if (pos[1] == 0) swapLR = true;
        while (true) pos = cmd('R');
        return;
    }
    if (W == 1) {
        pos = cmd('D');
        if (pos[0] == 0) swapUD = true;
        while (true) pos = cmd('D');
        return;
    }

    if (B[0][1] != '*') {
        pos = cmd('R');
        if (pos[1] == 0) swapLR = true;
        while (true) {
            if (B[pos[0]+1][pos[1]] != '*')
                break;
            pos = cmd('R');
        }
        pos = cmd('D');
        if (pos[0] == 0) swapUD = true;
        pos = cmd('U');
        while (pos[1] != 0) pos = cmd('L');
    }
    else {
        pos = cmd('D');
        if (pos[0] == 0) swapUD = true;
        while (true) {
            if (B[pos[0]][pos[1]+1] != '*')
                break;
            pos = cmd('D');
        }
        pos = cmd('R');
        if (pos[1] == 0) swapLR = true;
        pos = cmd('L');
        while (pos[0] != 0) pos = cmd('U');
    }

    foreach (co; root) {
        int nr = co / W;
        int nc = co % W;
        if (pos[0] - nr == 1) pos = cmd('U');
        else if (pos[0] - nr == -1) pos = cmd('D');
        else if (pos[1] - nc == 1) pos = cmd('L');
        else pos = cmd('R');
    }
}

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() {
    immutable int INF = 1 << 28;

    auto s = readln.split.map!(to!int);
    auto H = s[0];
    auto W = s[1];
    auto B = H.iota.map!(_ => readln.chomp).array;

    int gr, gc;
    foreach (i; 0..H) foreach (j; 0..W) if (B[i][j] == 'F') gr = i, gc = j;

    int[] dr = [0, 0, -1, 1];
    int[] dc = [-1, 1, 0, 0];
    auto dist = new int[](H * W);
    fill(dist, INF);
    dist[0] = 0;
    auto prev = new int[](H * W);
    fill(prev, -1);
    alias Tuple!(int, "from", int, "to", int, "cost") Edge;
    auto q = new BinaryHeap!(Array!Edge, "a.cost >= b.cost");
    q.insert(Edge(-1, 0, 0));

    while (!q.empty) {
        auto n = q.front;
        auto pr = n.from / W;
        auto pc = n.from % W;
        auto r = n.to / W;
        auto c = n.to % W;
        q.removeFront;
        if (dist[n.to] < n.cost)
            continue;
        dist[n.to] = n.cost;
        prev[n.to] = n.from;

        foreach (i; 0..4) {
            auto nr = r + dr[i];
            auto nc = c + dc[i];
            auto next = nr * W + nc;
            if (nr < 0 || nr >= H || nc < 0 || nc >= W || B[nr][nc] == '*')
                continue;
            if (dist[next] <= dist[n.to] + 1)
                continue;
            dist[next] = dist[n.to] + 1;
            q.insert(Edge(n.to, next, dist[n.to] + 1));
        }
    }

    int[] root;
    int x = gr * W + gc;
    while (prev[x] != -1) {
        root = x ~ root;
        x = prev[x];
    }

    bool swapLR, swapUD;
    Tuple!(int, int) cmd(char dir) {
        if      (swapLR && dir == 'L') dir = 'R';
        else if (swapLR && dir == 'R') dir = 'L';
        else if (swapUD && dir == 'U') dir = 'D';
        else if (swapUD && dir == 'D') dir = 'U';

        writeln(dir);
        stdout.flush;
        s = readln.split.map!(to!int);
        return tuple(s[0] - 1, s[1] - 1);
    }

    Tuple!(int, int) pos;

    if (H == 1) {
        pos = cmd('R');
        if (pos[1] == 0) swapLR = true;
        while (pos[0] != gr || pos[1] != gc) pos = cmd('R');
        return;
    }
    if (W == 1) {
        pos = cmd('D');
        if (pos[0] == 0) swapUD = true;
        while (pos[0] != gr || pos[1] != gc) pos = cmd('D');
        return;
    }

    if (B[0][1] == '.') {
        pos = cmd('R');
        if (pos[1] == 0) swapLR = true;
        while (true) {
            if (pos[0] == gr && pos[1] == gc)
                return;
            if (B[pos[0]+1][pos[1]] == '.')
                break;
            pos = cmd('R');
        }
        pos = cmd('D');
        if (pos[0] == 0) swapUD = true;
        pos = cmd('U');
        while (pos[1] != 0) pos = cmd('L');
    }
    else {
        pos = cmd('D');
        if (pos[0] == 0) swapUD = true;
        while (true) {
            if (pos[0] == gr && pos[1] == gc)
                return;
            if (B[pos[0]][pos[1]+1] == '.')
                break;
            pos = cmd('D');
        }
        pos = cmd('R');
        if (pos[1] == 0) swapLR = true;
        pos = cmd('L');
        while (pos[0] != 0) pos = cmd('U');
    }

    foreach (co; root) {
        int nr = co / W;
        int nc = co % W;
        if (pos[0] - nr == 1) pos = cmd('U');
        else if (pos[0] - nr == -1) pos = cmd('D');
        else if (pos[0] - nc == 1) pos = cmd('L');
        else pos = cmd('R');
    }
}


Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.Note that the order of the points inside the group of three chosen points doesn't matter.

The first line contains two integers: n and d (1 ≤ n ≤ 105; 1 ≤ d ≤ 109). The next line contains n integers x1, x2, ..., xn, their absolute value doesn't exceed 109 — the x-coordinates of the points that Petya has got. It is guaranteed that the coordinates of the points in the input strictly increase.

Print a single integer — the number of groups of three points, where the distance between two farthest points doesn't exceed d. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.

NoteIn the first sample any group of three points meets our conditions.In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.In the third sample only one group does: {1, 10, 20}.

import std.stdio : writeln, writefln;
import std.array;
import std.range;
import std.algorithm : filter, max, sort;
import std.math : sqrt;

int n;
int d;

void swap(T)(ref T a, ref T b){
	T tmp = a;
	a = b;
	b = tmp;
}

void main(){
	n.next;
	d.next;
	int[] list = new int[n];

	for(int i=0; i<n; ++i){
		list[i] = next!int();
	}

	long count;
	int e;
	for(int s=0; s<n; ++s){
		// 前のところからスタートすればいいから、範囲に入る最後の位置を覚えておく(ココ！)
		while(e<n && list[e] - list[s] <= d)++e;

		long r = e-s-1;	// スタートを覗いた範囲
		if(r>1){
			// rC_2 スタートを除いた範囲から重複を許さず、残り2個選ぶ組み合わせ
			count += r*(r-1)/2;
		}
	}

	count.writeln;
}

import std.stdio : readln, chomp;
import std.conv : to;
import std.string : split;
shared string[] input;
shared string delim = " ";
T next(T)()
in
{
	assert(hasNext());
}
out
{
	input.popFront;
}
body
{
	return input.front.to!T;
}

void next(T)(ref T v){
	v = next!T();
}

bool hasNext(){
	if(input.length > 0){
		return true;
	}

	string str = readln;
	if(str.length > 0){
		input ~= str.chomp.split(delim);
		return true;
	}else{
		return false;
	}
}

void dbg(T...)(T vs)
{
	import std.stdio : stderr;
	foreach(v; vs)
		stderr.write(v.to!string ~ " ");
	stderr.write("\n");
}

T clone(T)(T v){
	T v_;
	static if(isInputRange!(T)){
		foreach(ite; v){
			v_ ~= ite.clone;
		}
	}else{
		v_ = v;
	}

	return v_;
}

import std.stdio : writeln, writefln;
import std.array;
import std.range;
import std.algorithm : filter, max, sort;
import std.math : sqrt;

int n;
int d;

void swap(T)(ref T a, ref T b){
	T tmp = a;
	a = b;
	b = tmp;
}

void main(){
	n.next;
	d.next;
	int[] list = new int[n];

	for(int i=0; i<n; ++i){
		list[i] = next!int();
	}

	int count;
	for(int i=0; i<n; ++i){
		for(int j=i+2; j<n; ++j){
			if(list[j] - list[i] <= d){
				count += j-i-1;
			}
		}
	}
	count.writeln;
}

import std.stdio : readln, chomp;
import std.conv : to;
import std.string : split;
shared string[] input;
shared string delim = " ";
T next(T)()
in
{
	assert(hasNext());
}
out
{
	input.popFront;
}
body
{
	return input.front.to!T;
}

void next(T)(ref T v){
	v = next!T();
}

bool hasNext(){
	if(input.length > 0){
		return true;
	}

	string str = readln;
	if(str.length > 0){
		input ~= str.chomp.split(delim);
		return true;
	}else{
		return false;
	}
}

void dbg(T...)(T vs)
{
	import std.stdio : stderr;
	foreach(v; vs)
		stderr.write(v.to!string ~ " ");
	stderr.write("\n");
}

T clone(T)(T v){
	T v_;
	static if(isInputRange!(T)){
		foreach(ite; v){
			v_ ~= ite.clone;
		}
	}else{
		v_ = v;
	}

	return v_;
}

import std.stdio : writeln, writefln;
import std.array;
import std.range;
import std.algorithm : filter, max, sort;
import std.math : sqrt;

int n;
int d;

void swap(T)(ref T a, ref T b){
	T tmp = a;
	a = b;
	b = tmp;
}

void main(){
	n.next;
	d.next;
	int[] list = new int[n];

	for(int i=0; i<n; ++i){
		list[i] = next!int();
	}

	long count;
	int e;
	for(int s=0; s<n; ++s){
		// 前のところからスタートすればいいから、範囲に入る最後の位置を覚えておく(ココ！)
		while(e<n && list[e] - list[s] <= d)++e;

		int r = e-s-1;	// スタートを覗いた範囲
		if(r>1){
			// rC_2 スタートを除いた範囲から重複を許さず、残り2個選ぶ組み合わせ
			count += r*(r-1)/2;
		}
	}

	count.writeln;
}

import std.stdio : readln, chomp;
import std.conv : to;
import std.string : split;
shared string[] input;
shared string delim = " ";
T next(T)()
in
{
	assert(hasNext());
}
out
{
	input.popFront;
}
body
{
	return input.front.to!T;
}

void next(T)(ref T v){
	v = next!T();
}

bool hasNext(){
	if(input.length > 0){
		return true;
	}

	string str = readln;
	if(str.length > 0){
		input ~= str.chomp.split(delim);
		return true;
	}else{
		return false;
	}
}

void dbg(T...)(T vs)
{
	import std.stdio : stderr;
	foreach(v; vs)
		stderr.write(v.to!string ~ " ");
	stderr.write("\n");
}

T clone(T)(T v){
	T v_;
	static if(isInputRange!(T)){
		foreach(ite; v){
			v_ ~= ite.clone;
		}
	}else{
		v_ = v;
	}

	return v_;
}


Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.You are to determine the minimum possible number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. The square's side should have positive length.

The first line contains two integers n and m (1 ≤ n, m ≤ 100) — the sizes of the sheet. The next n lines contain m letters 'B' or 'W' each — the description of initial cells' colors. If a letter is 'B', then the corresponding cell is painted black, otherwise it is painted white.

Print the minimum number of cells needed to be painted black so that the black cells form a black square with sides parallel to the painting's sides. All the cells that do not belong to the square should be white. If it is impossible, print -1.

NoteIn the first example it is needed to paint 5 cells — (2, 2), (2, 3), (3, 2), (3, 3) and (4, 2). Then there will be a square with side equal to three, and the upper left corner in (2, 2).In the second example all the cells are painted black and form a rectangle, so it's impossible to get a square.In the third example all cells are colored white, so it's sufficient to color any cell black.

import std.algorithm;
import std.stdio;
import std.string;

void main ()
{
	int rows, cols;
	while (readf (" %s %s", &rows, &cols) > 0)
	{
		readln;
		string [] s;
		foreach (row; 0..rows)
		{
			s ~= readln.strip;
		}

		int blacks = 0;
		int minRow = int.max;
		int maxRow = int.min;
		int minCol = int.max;
		int maxCol = int.min;
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				if (s[row][col] == 'B')
				{
					blacks += 1;
					minRow = min (minRow, row);
					maxRow = max (maxRow, row);
					minCol = min (minCol, col);
					maxCol = max (maxCol, col);
				}
			}
		}

		int side = max (maxRow - minRow + 1, maxCol - minCol + 1);
		if (blacks == 0)
		{
			writeln (1);
		}
		else if (side > min (rows, cols))
		{
			writeln (-1);
		}
		else
		{
			writeln (side * side - blacks);
		}
	}
}

import std.algorithm;
import std.stdio;
import std.string;

void main ()
{
	int rows, cols;
	while (readf (" %s %s", &rows, &cols) > 0)
	{
		readln;
		string [] s;
		foreach (row; 0..rows)
		{
			s ~= readln.strip;
		}

		int blacks = 0;
		int minRow = int.max;
		int maxRow = int.min;
		int minCol = int.max;
		int maxCol = int.min;
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				if (s[row][col] == 'B')
				{
					blacks += 1;
					minRow = min (minRow, row);
					maxRow = max (maxRow, row);
					minCol = min (minCol, col);
					maxCol = max (maxCol, col);
				}
			}
		}

		int side = max (maxRow - minRow + 1, maxCol - minCol + 1);
		if (side > min (rows, cols))
		{
			writeln (-1);
		}
		else if (blacks == 0)
		{
			writeln (1);
		}
		else
		{
			writeln (side * side - blacks);
		}
	}
}

import std.algorithm;
import std.stdio;
import std.string;

void main ()
{
	int rows, cols;
	while (readf (" %s %s", &rows, &cols) > 0)
	{
		readln;
		string [] s;
		foreach (row; 0..rows)
		{
			s ~= readln.strip;
		}

		int blacks = 0;
		int minRow = int.max;
		int maxRow = int.min;
		int minCol = int.max;
		int maxCol = int.min;
		foreach (row; 0..rows)
		{
			foreach (col; 0..cols)
			{
				if (s[row][col] == 'B')
				{
					blacks += 1;
					minRow = min (minRow, row);
					maxRow = max (maxRow, row);
					minCol = min (minCol, col);
					maxCol = max (maxCol, col);
				}
			}
		}

		int side = max (maxRow - minRow + 1, maxCol - minCol + 1);
		writeln (side > min (rows, cols) ? -1 : side * side - blacks);
	}
}


Vasya’s elder brother Petya loves playing computer games. In one of his favourite computer games Petya reached the final level where a fight with the boss take place.While playing the game Petya found spell scrolls and now he is about to use them. Let’s describe the way fighting goes on this level:1) The boss has two parameters: max — the initial amount of health and reg — regeneration rate per second.2) Every scroll also has two parameters: powi — spell power measured in percents — the maximal amount of health counted off the initial one, which allows to use the scroll (i.e. if the boss has more than powi percent of health the scroll cannot be used); and dmgi the damage per second inflicted upon the boss if the scroll is used. As soon as a scroll is used it disappears and another spell is cast upon the boss that inflicts dmgi of damage per second upon him until the end of the game.During the battle the actions per second are performed in the following order: first the boss gets the damage from all the spells cast upon him, then he regenerates reg of health (at the same time he can’t have more than max of health), then the player may use another scroll (no more than one per second).The boss is considered to be defeated if at the end of a second he has nonpositive ( ≤ 0) amount of health.Help Petya to determine whether he can win with the set of scrolls available to him and if he can, determine the minimal number of seconds he needs to do it.

The first line contains three integers N, max and reg (1 ≤ N, max, reg ≤ 1000) –– the amount of scrolls and the parameters of the boss. The next N lines contain two integers powi and dmgi each — the parameters of the i-th scroll (0 ≤ powi ≤ 100, 1 ≤ dmgi ≤ 2000).

In case Petya can’t complete this level, output in the single line NO. Otherwise, output on the first line YES. On the second line output the minimal time after which the boss can be defeated and the number of used scrolls. In the next lines for each used scroll output space-separated number of seconds passed from the start of the battle to the moment the scroll was used and the number of the scroll. Scrolls are numbered starting from 1 in the input order. The first scroll is considered to be available to be used after 0 seconds. Output scrolls in the order they were used. It is not allowed to use scrolls after the boss is defeated.

import core.bitop, std.bitmanip;
import core.checkedint;
import std.algorithm, std.functional;
import std.array, std.container;
import std.bigint;
import std.conv;
import std.datetime.stopwatch;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

void main()
{
    int n, mx, reg;
    readf("%s %s %s", &n, &mx, &reg);
    readln;

    struct scroll { int id, pw, dmg; }

    scroll[] scs;
    scs ~= scroll(0, 0, 0);
    foreach (i; 1 .. n+1) {
        int pw, dmg;
        readf("%s %s", &pw, &dmg);
        readln;

        scs ~= scroll(i, pw, dmg);
    }

    auto used = new bool[] (n+1);
    Tuple!(int, int)[] ans;
    int cur = mx;
    int sec = 0;
    int sm = 0;
    for (; sec <= 2100; ++sec) {
        cur = min(cur - sm + reg, mx);
        if (cur <= 0) { break; }

        int best = 0;
        foreach (i, e; scs) {
            if (used[i]) { continue; }

            if (e.pw * mx >= cur * 100 && e.dmg > scs[best].dmg) {
                best = i.to!int;
            }
        }

        if (best != 0) {
            used[best] = true;
            ans ~= tuple(sec, best);
            sm += scs[best].dmg;
        }
    }

    if (sec > 2100) {
        writeln("NO");
        return;
    }

    writeln("YES");
    writeln(sec, ' ', ans.length);
    ans.each!(e => writeln(e[0], ' ', e[1]));
}

import core.bitop, std.bitmanip;
import core.checkedint;
import std.algorithm, std.functional;
import std.array, std.container;
import std.bigint;
import std.conv;
import std.datetime.stopwatch;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

void main()
{
    int n, mx, reg;
    readf("%s %s %s", &n, &mx, &reg);
    readln;

    struct scroll { int id, pw, dmg; }

    scroll[] scs;
    foreach (i; 1 .. n+1) {
        int pw, dmg;
        readf("%s %s", &pw, &dmg);
        readln;

        scs ~= scroll(i, pw, dmg);
    }

    auto used = new bool[] (n+1);
    Tuple!(int, int)[] ans;
    int cur = mx;
    int sec = 0;
    int sm = 0;
    for (; sec <= 2100; ++sec) {
        cur = min(cur - sm + reg, mx);
        if (cur <= 0) { break; }

        foreach (i, e; scs) {
            if (used[i]) { continue; }

            if (e.pw * mx >= cur * 100) {
                used[i] = true;
                sm += e.dmg;
                ans ~= tuple(sec, e.id);
            }
        }
    }

    if (sec > 2100) {
        writeln("NO");
        return;
    }

    writeln("YES");
    writeln(sec, ' ', ans.length);
    ans.each!(e => writeln(e[0], ' ', e[1]));
}


This is an interactive problem.Vasya and Petya are going to play the following game: Petya has some positive integer number $$$a$$$. After that Vasya should guess this number using the following questions. He can say a pair of non-negative integer numbers $$$(x, y)$$$. Petya will answer him:   "x", if $$$(x \bmod a) \geq (y \bmod a)$$$.  "y", if $$$(x \bmod a) < (y \bmod a)$$$. We define $$$(x \bmod a)$$$ as a remainder of division $$$x$$$ by $$$a$$$.Vasya should guess the number $$$a$$$ using no more, than 60 questions.It's guaranteed that Petya has a number, that satisfies the inequality $$$1 \leq a \leq 10^9$$$.Help Vasya playing this game and write a program, that will guess the number $$$a$$$.

NoteIn the first test, you should play $$$3$$$ games with Petya's numbers $$$1$$$, $$$2$$$ and $$$3$$$.In the first game, Petya will answer "x" (without quotes) to any question, because $$$(x \bmod 1) = 0$$$ for any integer $$$x$$$. In the second game, if you will ask pair $$$(0, 0)$$$, the answer will be "x" (without quotes), because $$$(0 \bmod 2) \geq (0 \bmod 2)$$$. But if you will ask pair $$$(2, 5)$$$, the answer will be "y" (without quotes), because $$$(2 \bmod 2) < (5 \bmod 2)$$$, because $$$(2 \bmod 2) = 0$$$ and $$$(5 \bmod 2) = 1$$$.

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;

long X;
int cnt = 0;

void ans(long x) {
    debug {
        writeln((x == X) ? "OK ": "NG");
        writeln(cnt);
        return;
    }
    writeln("! ", x);
    stdout.flush;
}

bool ask(long x, long y) {
    debug {
        cnt += 1;
        return x % X >= y % X;
    }
    writeln("? ", x, " ", y);
    stdout.flush;
    return readln.chomp == "x";
}

void solve() {
    if (ask(1, 2)) {
        if (ask(2, 1)) {
            ans(1);
        } else {
            ans(2);
        }
        return;
    }

    long mn = 2;
    long mx = 4;

    while (true) {
        if (ask(mn, mx)) {
            break;
        } else {
            mx *= 2;
            mn *= 2;
        }
    }

    while (mx - mn > 1) {
        long next_mn = (mx + mn) / 2;
        if (ask(next_mn, mx)) {
            mn = next_mn;
        } else {
            mx = next_mn;
        }
    }

    ans (mx);
}

void main() {
    debug {
        X = readln.chomp.to!int;
        solve;
        return;
    }
    while (true) {
        auto s = readln.chomp;
        if (s == "start") solve;
        else break;
    }
}

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

bool ask (int x, int y)
{
	writeln ("?", " ", x, " ", y);
	stdout.flush ();
	auto s = readln.strip;
	if (s == "e")
	{
		assert (false);
	}
	return (s == "x");
}

void main ()
{
	string s;
	while ((s = readln.strip) != "")
	{
		if (s == "end")
		{
			break;
		}
		if (s != "start")
		{
			assert (false);
		}

		immutable int start = 0;
		int x = start;
		int y = x;
		int d = 1;
		do
		{
			x = y;
			y += d;
			d *= 2;
		}
		while (!ask (x, y));

		int lo = x + 1;
		int hi = y;
		while (lo != hi)
		{
			auto me = (lo + hi) / 2;
			if (ask (x, me))
			{
				hi = me;
			}
			else
			{
				lo = me + 1;
			}
		}

		writeln ("!", " ", lo);
		stdout.flush ();
	}
}


The only difference between easy and hard versions is the constraints.Polycarp has to write a coursework. The coursework consists of $$$m$$$ pages.Polycarp also has $$$n$$$ cups of coffee. The coffee in the $$$i$$$-th cup Polycarp has $$$a_i$$$ caffeine in it. Polycarp can drink some cups of coffee (each one no more than once). He can drink cups in any order. Polycarp drinks each cup instantly and completely (i.e. he cannot split any cup into several days).Surely, courseworks are not being written in a single day (in a perfect world of Berland, at least).Let's consider some day of Polycarp's work. Consider Polycarp drinks $$$k$$$ cups of coffee during this day and caffeine dosages of cups Polycarp drink during this day are $$$a_{i_1}, a_{i_2}, \dots, a_{i_k}$$$. Then the first cup he drinks gives him energy to write $$$a_{i_1}$$$ pages of coursework, the second cup gives him energy to write $$$max(0, a_{i_2} - 1)$$$ pages, the third cup gives him energy to write $$$max(0, a_{i_3} - 2)$$$ pages, ..., the $$$k$$$-th cup gives him energy to write $$$max(0, a_{i_k} - k + 1)$$$ pages.If Polycarp doesn't drink coffee during some day, he cannot write coursework at all that day.Polycarp has to finish his coursework as soon as possible (spend the minimum number of days to do it). Your task is to find out this number of days or say that it is impossible.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 10^9$$$) — the number of cups of coffee and the number of pages in the coursework. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the caffeine dosage of coffee in the $$$i$$$-th cup.

If it is impossible to write the coursework, print -1. Otherwise print the minimum number of days Polycarp needs to do it.

NoteIn the first example Polycarp can drink fourth cup during first day (and write $$$1$$$ page), first and second cups during second day (and write $$$2 + (3 - 1) = 4$$$ pages), fifth cup during the third day (and write $$$2$$$ pages) and third cup during the fourth day (and write $$$1$$$ page) so the answer is $$$4$$$. It is obvious that there is no way to write the coursework in three or less days.In the second example Polycarp can drink third, fourth and second cups during first day (and write $$$4 + (2 - 1) + (3 - 2) = 6$$$ pages) and sixth cup during second day (and write $$$4$$$ pages) so the answer is $$$2$$$. It is obvious that Polycarp cannot write the whole coursework in one day in this test.In the third example Polycarp can drink all cups of coffee during first day and write $$$5 + (5 - 1) + (5 - 2) + (5 - 3) + (5 - 4) = 15$$$ pages of coursework.In the fourth example Polycarp cannot drink all cups during first day and should drink one of them during the second day. So during first day he will write $$$5 + (5 - 1) + (5 - 2) + (5 - 3) = 14$$$ pages of coursework and during second day he will write $$$5$$$ pages of coursework. This is enough to complete it.In the fifth example Polycarp cannot write the whole coursework at all, even if he will drink one cup of coffee during each day, so the answer is -1.

import core.bitop, std.bitmanip;
import std.algorithm, std.functional;
import std.array, std.container;
import std.conv;
import std.math, std.numeric;
import std.range, std.range.interfaces;
import std.stdio, std.string;
import std.typecons;

immutable int INF = 10L ^^ 9 + 23;

void main()
{
    int n, m;
    readf("%s %s", &n, &m);
    readln;

    auto arr = readln.chomp.split.map!(to!int).array;

    arr.sort().reverse();

    debug { arr.writeln; }

    bool isOk(int md) {
        long eng = 0;
        int sb = 0;
        foreach (i, e; arr) {
            if (i > 0 && i % md == 0) { sb += 1; }

            eng += max(e - sb, 0);
        }

        return eng >= m;
    }

    int le = 1, r = n+1;
    while (le < r) {
        int md = (le + r) / 2;
        if (isOk(md)) { r = md; }
        else { le = md + 1; }
    }

    writeln(le == n+1 ? -1 : le);
}

void main() {
  import std.stdio, std.string, std.conv, std.algorithm;

  int n;
  long m;
  rd(n, m);
  auto a = readln.split.to!(long[]);

  sort!"a>b"(a);
  if (m > reduce!"a+b"(a)) {
    writeln(-1);
    return;
  }
  long _s = 0;
  foreach (int i; 0 .. n) {
    _s += max(0L, a[i] - i);
  }
  if (_s >= m) {
    writeln(1);
    return;
  }
  bool enough(long k) {
    long s = 0;
    foreach (i; 0 .. n) {
      s += max(0L, a[i] - (i / k));
    }
    return s >= m;
  }

  long ng = 1, ok = n;
  while (ok - ng > 1) {
    auto md = (ok + ng) / 2;
    if (enough(md)) {
      ok = md;
    } else {
      ng = md;
    }
  }
  writeln(ok);
}

void rd(T...)(ref T x) {
  import std.stdio : readln;
  import std.string : split;
  import std.conv : to;

  auto l = readln.split;
  assert(l.length == x.length);
  foreach (i, ref e; x)
    e = l[i].to!(typeof(e));
}


You are given a sequence a1, a2, ..., an of one-dimensional segments numbered 1 through n. Your task is to find two distinct indices i and j such that segment ai lies within segment aj.Segment [l1, r1] lies within segment [l2, r2] iff l1 ≥ l2 and r1 ≤ r2.Print indices i and j. If there are multiple answers, print any of them. If no answer exists, print -1 -1.

The first line contains one integer n (1 ≤ n ≤ 3·105) — the number of segments. Each of the next n lines contains two integers li and ri (1 ≤ li ≤ ri ≤ 109) — the i-th segment.

Print two distinct indices i and j such that segment ai lies within segment aj. If there are multiple answers, print any of them. If no answer exists, print -1 -1.

NoteIn the first example the following pairs are considered correct:  (2, 1), (3, 1), (4, 1), (5, 1) — not even touching borders;  (3, 2), (4, 2), (3, 5), (4, 5) — touch one border;  (5, 2), (2, 5) — match exactly.

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.regex;

immutable long INF = 1L << 59;

void main() {
    auto N = readln.chomp.to!int;
    auto A = new Tuple!(int, int)[](N);
    foreach (i; 0..N) {
        auto s = readln.split.map!(to!int);
        A[i] = tuple(s[0], s[1]);
    }

    Tuple!(int, int)[][int] B;
    foreach (i, a; A.enumerate)
        B[a[0]] ~= tuple(a[1], (i+1).to!int);

    foreach (k; B.keys)
        B[k].sort();

    foreach (k; B.keys)
        if (B[k].length > 1) {
            writeln(B[k].front[1], " ", B[k].back[1]);
            return;
        }

    auto K = B.keys.dup;
    K.sort!"a > b"();
    Tuple!(int, int) minv = B[K[0]].front;

    foreach (i; 1..K.length) {
        if (B[K[i]].back[0] >= minv[0]) {
            writeln(minv[1], " ", B[K[i]].back[1]);
            return;
        }
        minv = min(minv, B[K[i]].front);
    }

    writeln(-1, " ", -1);
}

import std.stdio, std.string;
import std.typecons: Tuple, tuple;
import std.algorithm;

bool within(Tuple!(int, int, int) t0, Tuple!(int, int, int) t1)
{
    if (t0[0] >= t1[0] && t0[1] <= t1[1])
    {
        return true;
    }
    return false;
}

void solve(Tuple!(int, int, int)[] s)
{
    s.sort();
    foreach (idx; 0 .. s.length - 1)
    {
        if (within(s[idx], s[idx + 1]))
        {
            writeln(s[idx][2], " ", s[idx + 1][2]);
            return;
        }
        if (within(s[idx + 1], s[idx]))
        {
            writeln(s[idx + 1][2], " ", s[idx][2]);
            return;
        }
    }
    writeln("-1 -1");
}

int main(string[] args)
{
    int n;
    while (readf("%d\n", &n) == 1)
    {
        auto s = new Tuple!(int, int, int)[n];
        foreach (i; 0 .. n)
        {
            int l, r;
            readf("%d %d\n", &l, &r);
            s[i] = tuple(l, r, i + 1);
        }
        solve(s);
    }
    return 0;
}

import std.algorithm.sorting;
import std.conv;
import std.stdio;
import std.typecons;

void main()
{
  uint n;
  readf!"%d\n"(n);

  Tuple!(uint, uint, uint)[] x;

  foreach (i; 0..n) {
    uint a, b;

    readf!"%d %d\n"(a, b);

    x ~= tuple(a, b, i+1);
  }

  x.sort!((a, b) => (a[0] == b[0]) ? (a[1] > b[1]) : (a[0] < b[0]));

  // current max
  auto m = x[0][1];
  auto mi = x[0][2];

  foreach (i; 1..n) {
    if (x[i][0] <= m && x[i][1] <= m) {
      writefln("%d %d", x[i][2], mi);
      return;
    }

    if (x[i][1] > m) {
      m = x[i][1];
      mi = x[i][2];
    }
  }
  writeln("-1 -1");
}

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()
{
    int n;
    readf ("%s", &n);
    readln;
    Tuple!(ulong, ulong)[] r;
    foreach (_; 0..n) {
        auto nrs = readln.splitter.map!(to!ulong).array;
        r ~= tuple(nrs[0], nrs[1]);
    }
    int[] b = new int[] (r.length);
    makeIndex!(q{a[0] != b[0] ? a[0] < b[0] : a[1] > b[1]})(r, b);

    debug { writeln (r); }
    debug { writeln (b); }

    int outer = cast(int) b.front;
    auto ans = tuple(-1, -1);
    foreach (p; b.dropOne()) {
        if (r[p][1] <= r[outer][1]) {
            ans = tuple(cast(int) p, outer);
            break;
        } else {
            outer = cast(int) p;
        }
    }

    if (ans[0] != -1) ans[0] += 1, ans[1] += 1;
    writeln (ans[0], ' ', ans[1]);
}

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()
{
    int n;
    readf ("%s", &n);
    readln;
    Tuple!(int, int)[] r;
    foreach (_; 0..n) {
        auto nrs = readln.splitter.map!(to!int).array;
        r ~= tuple(nrs[0], nrs[1]);
    }
    auto b = r.length.iota.array
        .multiSort!((x, y) => r[x][0] < r[y][0], (x,y) => r[x][1] > r[y][1]);

    debug { writeln (r); }
    debug { writeln (b); }

    int right = cast(int) b.front();
    auto ans = tuple(-1, -1);
    foreach (p; b.dropOne()) {
        debug { writeln(p); }
        if (r[p][1] <= r[right][1]) {
            ans = tuple(cast(int) p, right);
            break;
        } else {
            right = cast(int) p;
        }
    }

    if (ans[0] != -1) ans[0] += 1, ans[1] += 1;
    writeln (ans[0], ' ', ans[1]);
}

void main(){
  import std.stdio, std.string, std.conv, std.algorithm;

  int n; scanf("%d", &n);
  struct P{int l, r;}
  auto seq=new P[](0);
  foreach(i; 0..n){
    int a, b; scanf("%d %d", &a, &b);
    seq~=P(a, b);
  }

  struct LRi{int l, r, id;}
  auto lri=new LRi[](0);
  foreach(i; 0..n) lri~=LRi(seq[i].l, seq[i].r, i);
  sort!((a, b)=>(a.l==b.l ? a.r>b.r : a.l<b.l))(lri);
  struct Ri{int r, id;}
  import std.container;
  auto tree=new RedBlackTree!(Ri, "a.r==b.r ? a.id<b.id : a.r<b.r", true);
  foreach(i; 0..n) tree.insert(Ri(seq[i].r, i));
  foreach(elem; lri){
    // writeln(elem.id, " ", elem.l, " ", elem.r);
    int id=elem.id, r=seq[id].r;
    // writeln(id, " ", r);
    // writeln(tree);
    tree.removeKey(Ri(r, id));
    auto eq=tree.equalRange(Ri(r, -1));
    if((eq.empty)==false){
      writeln(-1, " ", -1); return;
      writeln(eq.front.id+1, " ", id+1);
      goto heaven;
    }else{
      auto lb=tree.lowerBound(Ri(r, 1_000_000_000));
      if(lb.empty) continue;
      writeln(lb.back.id+1, " ", id+1);
      goto heaven;
    }
  }

  writeln(-1, " ", -1);
  heaven:;
}

// rbt.equalRange(elem) の挙動？

void rd(Type...)(ref Type x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}

void main(){
  import std.stdio, std.string, std.conv, std.algorithm;

  int n; scanf("%d", &n);
  struct P{int l, r;}
  auto seq=new P[](0);
  foreach(i; 0..n){
    int a, b; scanf("%d %d", &a, &b);
    seq~=P(a, b);
  }

  struct LRi{int l, r, id;}
  auto lri=new LRi[](0);
  foreach(i; 0..n) lri~=LRi(seq[i].l, seq[i].r, i);
  sort!((a, b)=>(a.l==b.l ? a.r>b.r : a.l<b.l))(lri);
  struct Ri{int r, id;}
  import std.container;
  auto tree=new RedBlackTree!(Ri, "a.r==b.r ? a.id<b.id : a.r<b.r", true);
  foreach(i; 0..n) tree.insert(Ri(seq[i].r, i));
  foreach(elem; lri){
    int id=elem.id, r=seq[id].r;
    tree.removeKey(Ri(r, id));
    auto lb=tree.lowerBound(Ri(r, 1_000_000_000));
    if((lb.empty)==false){
      writeln(lb.back.id+1, " ", id+1);
      goto heaven;
    }
  }

  writeln(-1, " ", -1);
  heaven:;
}

void rd(Type...)(ref Type x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}

void main(){
  import std.stdio, std.string, std.conv, std.algorithm;

  int n; scanf("%d", &n);
  struct P{int l, r;}
  auto seq=new P[](0);
  foreach(i; 0..n){
    int a, b; scanf("%d %d", &a, &b);
    seq~=P(a, b);
  }

  struct LRi{int l, r, id;}
  auto lri=new LRi[](0);
  foreach(i; 0..n) lri~=LRi(seq[i].l, seq[i].r, i);
  sort!((a, b)=>(a.l==b.l ? a.r>b.r : a.l<b.l))(lri);
  struct Ri{int r, id;}
  import std.container;
  auto tree=new RedBlackTree!(Ri, "a.r==b.r ? a.id<b.id : a.r<b.r", true);
  foreach(i; 0..n) tree.insert(Ri(seq[i].r, i));
  foreach(elem; lri){
    // writeln(elem.id, " ", elem.l, " ", elem.r);
    int id=elem.id, r=seq[id].r;
    // writeln(id, " ", r);
    // writeln(tree);
    tree.removeKey(Ri(r, id));
    auto eq=tree.equalRange(Ri(r, -1));
    if((eq.empty)==false){
      writeln(eq.front.id+1, " ", id+1);
      goto heaven;
    }else{
      auto lb=tree.lowerBound(Ri(r, 1_000_000_000));
      if(lb.empty) continue;
      writeln(lb.back.id+1, " ", id+1);
      goto heaven;
    }
  }

  writeln(-1, " ", -1);
  heaven:;
}

void rd(Type...)(ref Type x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}

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.regex;

immutable long INF = 1L << 59;

void main() {
    auto N = readln.chomp.to!int;
    auto A = new Tuple!(int, int)[](N);
    foreach (i; 0..N) {
        auto s = readln.split.map!(to!int);
        A[i] = tuple(s[0], s[1]);
    }

    Tuple!(int, int)[int] B;
    foreach (i, a; A.enumerate) {
        if (a[0] in B && B[a[0]][0] == a[1]) {
            writeln(i + 1, " ", B[a[0]][1]);
            return;
        }
        if (a[0] in B) B[a[0]] = min(B[a[0]], tuple(a[1], (i+1).to!int));
        else B[a[0]] = tuple(a[1], (i+1).to!int);
    }

    auto K = B.keys.dup;
    K.sort!"a > b"();
    Tuple!(int, int) minv = B[K[0]];

    foreach (i; 1..K.length) {
        if (B[K[i]][0] >= minv[0]) {
            writeln(minv[1], " ", B[K[i]][1]);
            return;
        }
        minv = min(minv, B[K[i]]);
    }

    writeln(-1, " ", -1);
}

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.regex;

immutable long INF = 1L << 59;

void main() {
    auto N = readln.chomp.to!int;
    auto A = new Tuple!(int, int)[](N);
    foreach (i; 0..N) {
        auto s = readln.split.map!(to!int);
        A[i] = tuple(s[0], s[1]);
    }

    Tuple!(int, int)[][int] B;
    foreach (i, a; A.enumerate)
        B[a[0]] ~= tuple(a[1], (i+1).to!int);

    foreach (k; B.keys)
        B[k].sort();

    foreach (k; B.keys)
        foreach (i; 0..B[k].length.to!int-1)
            if (B[k][i][0] == B[k][i+1][0]) {
                writeln(B[k][i][1], " ", B[k][i+1][1]);
                return;
            }

    auto K = B.keys.dup;
    K.sort!"a > b"();
    Tuple!(int, int) minv = B[K[0]].front;

    foreach (i; 1..K.length) {
        if (B[K[i]].back[0] >= minv[0]) {
            writeln(minv[1], " ", B[K[i]].front[1]);
            return;
        }
        minv = min(minv, B[K[i]].back);
    }

    writeln(-1, " ", -1);
}

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.regex;

immutable long INF = 1L << 59;

void main() {
    auto N = readln.chomp.to!int;
    auto A = new Tuple!(int, int)[](N);
    foreach (i; 0..N) {
        auto s = readln.split.map!(to!int);
        A[i] = tuple(s[0], s[1]);
    }

    Tuple!(int, int)[][int] B;
    foreach (i, a; A.enumerate)
        B[a[0]] ~= tuple(a[1], (i+1).to!int);

    foreach (k; B.keys)
        B[k].sort();

    foreach (k; B.keys)
        foreach (i; 0..B[k].length.to!int-1)
            if (B[k][i][0] == B[k][i+1][0]) {
                writeln(B[k][i][1], " ", B[k][i+1][1]);
                return;
            }

    auto K = B.keys.dup;
    K.sort!"a > b"();
    Tuple!(int, int) minv = B[K[0]].front;

    foreach (i; 1..K.length) {
        if (B[K[i]].back[0] >= minv[0]) {
            writeln(minv[1], " ", B[K[i]].back[1]);
            return;
        }
        minv = min(minv, B[K[i]].front);
    }

    writeln(-1, " ", -1);
}

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.regex;

immutable long INF = 1L << 59;

void main() {
    auto sc = new Scanner(stdin);

    int N; sc.read(N);
    auto A = new Tuple!(int, int)[](N);
    foreach (i; 0..N) {
        int a, b; sc.read(a); sc.read(b);
        A[i] = tuple(a-1, b-1);
    }

    Tuple!(int, int)[][int] B;
    foreach (i, a; A.enumerate)
        B[a[0]] ~= tuple(a[1], (i+1).to!int);

    foreach (k; B.keys)
        B[k].sort();

    foreach (k; B.keys)
        foreach (i; 0..B[k].length.to!int-1)
            if (B[k][i][0] == B[k][i+1][0]) {
                writeln(B[k][i][1], " ", B[k][i+1][1]);
                return;
            }

    auto K = B.keys.dup;
    K.sort!"a > b"();
    Tuple!(int, int) minv = B[K[0]].front;

    foreach (i; 1..K.length) {
        if (B[K[i]].back[0] >= minv[0]) {
            writeln(minv[1], " ", B[K[i]].back[1]);
            return;
        }
        minv = min(minv, B[K[i]].front);
    }

    writeln(-1, " ", -1);
}

class Scanner {
    import std.stdio : File;
    import std.conv : to;
    import std.range : front, popFront, array, ElementType;
    import std.array : split;
    import std.traits : isSomeChar, isStaticArray, isArray;
    import std.algorithm : map;
    File f;
    this(File f) {
        this.f = f;
    }
    char[512] lineBuf;
    char[] line;
    private bool succ() {
        import std.range.primitives : empty, front, popFront;
        import std.ascii : isWhite;
        while (true) {
            while (!line.empty && line.front.isWhite) {
                line.popFront;
            }
            if (!line.empty) break;
            if (f.eof) return false;
            line = lineBuf[];
            f.readln(line);
        }
        return true;
    }

    private bool readSingle(T)(ref T x) {
        import std.algorithm : findSplitBefore;
        import std.string : strip;
        import std.conv : parse;
        if (!succ()) return false;
        static if (isArray!T) {
            alias E = ElementType!T;
            static if (isSomeChar!E) {

                auto r = line.findSplitBefore(" ");
                x = r[0].strip.dup;
                line = r[1];
            } else {
                auto buf = line.split.map!(to!E).array;
                static if (isStaticArray!T) {

                    assert(buf.length == T.length);
                }
                x = buf;
                line.length = 0;
            }
        } else {
            x = line.parse!T;
        }
        return true;
    }
    int read(T, Args...)(ref T x, auto ref Args args) {
        if (!readSingle(x)) return 0;
        static if (args.length == 0) {
            return 1;
        } else {
            return 1 + read(args);
        }
    }
}

import std.algorithm.sorting;
import std.conv;
import std.stdio;
import std.typecons;

void main()
{
  uint n;
  readf!"%d\n"(n);

  Tuple!(uint, uint)[] x;

  foreach (i; 0..n) {
    uint a, b;

    readf!"%d %d\n"(a, b);

    x ~= tuple(a, b);
  }

  x.sort!((a, b) => (a[0] == b[0]) ? (b[0] > a[0]) : (a[0] < b[0]));

  // current max
  auto m = x[0][1];
  auto mi = 1;

  foreach (i; 1..n) {
    if (x[i][0] <= m && x[i][1] <= m) {
      writefln("%d %d", i+1, mi);
      return;
    }

    if (x[i][1] > m) {
      m = x[i][1];
      mi = i+1;
    }
  }
  writeln("-1 -1");
}

import std.algorithm.sorting;
import std.conv;
import std.stdio;
import std.typecons;

void main()
{
  uint n;
  readf!"%d\n"(n);

  Tuple!(uint, uint, uint)[] x;

  foreach (i; 0..n) {
    uint a, b;

    readf!"%d %d\n"(a, b);

    x ~= tuple(a, b, i+1);
  }

  x.sort!((a, b) => (a[0] == b[0]) ? (b[0] > a[0]) : (a[0] < b[0]));

  // current max
  auto m = x[0][1];
  auto mi = x[0][2];

  foreach (i; 1..n) {
    if (x[i][0] <= m && x[i][1] <= m) {
      writefln("%d %d", x[i][2], mi);
      return;
    }

    if (x[i][1] > m) {
      m = x[i][1];
      mi = x[i][2];
    }
  }
  writeln("-1 -1");
}

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()
{
    int n;
    readf ("%s", &n);
    readln;
    Tuple!(int, int)[] a;
    foreach (_; 0..n) {
        auto nrs = readln.splitter.map!(to!int).array;
        a ~= tuple(nrs[0], nrs[1]);
    }

    debug { writeln (a); }

    a.multiSort!(q{ a[0] < b[0] }, q{ a[1] > b[1] });

    debug { writeln (a); }

    int right = 0;
    auto ans = tuple(-1, -1);
    foreach (int i, e; a.dropOne()) {
        debug { writeln(e); }
        if (e[1] <= a[right][1]) {
            ans = tuple(right, i);
            break;
        } else {
            right = i;
        }
    }

    writeln (ans[0], ' ', ans[1]);
}

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()
{
    int n;
    readf ("%s", &n);
    readln;
    Tuple!(int, int)[] r;
    foreach (_; 0..n) {
        auto nrs = readln.splitter.map!(to!int).array;
        r ~= tuple(nrs[0], nrs[1]);
    }
    auto b = r.length.iota.array;

    debug { writeln (r); }

    b.multiSort!((x, y) => r[x][0] < r[y][0], (x,y) => r[x][1] > r[y][1]);

    debug { writeln (b); }

    int right = 0;
    auto ans = tuple(-1, -1);
    foreach (p; b.dropOne()) {
        debug { writeln(p); }
        auto e = r[p];
        if (e[1] <= r[right][1]) {
            ans = tuple(cast(int) p, right);
            break;
        } else {
            right = cast(int) p;
        }
    }

    if (ans[0] != -1) ans[0] += 1, ans[1] += 1;
    writeln (ans[0], ' ', ans[1]);
}

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()
{
    int n;
    readf ("%s", &n);
    readln;
    Tuple!(int, int)[] a;
    foreach (_; 0..n) {
        auto nrs = readln.splitter.map!(to!int).array;
        a ~= tuple(nrs[0], nrs[1]);
    }

    debug { writeln (a); }

    a.multiSort!(q{ a[0] < b[0] }, q{ a[1] > b[1] });

    debug { writeln (a); }

    int right = 0;
    auto ans = tuple(-1, -1);
    foreach (int i, e; a.dropOne().enumerate(1)) {
        debug { writeln(e); }
        if (e[1] <= a[right][1]) {
            ans = tuple(right, i);
            break;
        } else {
            right = i;
        }
    }

    if (ans[0] != -1) ans[0] += 1, ans[1] += 1;
    writeln (ans[0], ' ', ans[1]);
}

void main(){
  import std.stdio, std.string, std.conv, std.algorithm;

  int n; scanf("%d", &n);
  struct P{int l, r;}
  auto seq=new P[](0);
  foreach(i; 0..n){
    int a, b; scanf("%d %d", &a, &b);
    seq~=P(a, b);
  }

  struct LRi{int l, r, id;}
  auto lri=new LRi[](0);
  foreach(i; 0..n) lri~=LRi(seq[i].l, seq[i].r, i);
  sort!((a, b)=>(a.l==b.l ? a.r>b.r : a.l<b.l))(lri);
  struct Ri{int r, id;}
  import std.container;
  auto tree=new RedBlackTree!(Ri, "a.r==b.r ? a.id<b.id : a.r<b.r", true);
  foreach(i; 0..n) tree.insert(Ri(seq[i].r, i));
  foreach(elem; lri){
    int id=elem.id, r=seq[id].r;
    auto lb=tree.lowerBound(Ri(r, 1_000_000_000));
    if((lb.empty)==false){
      writeln(lb.back.id+1, " ", id+1);
      goto heaven;
    }
  }

  writeln(-1, " ", -1);
  heaven:;
}

void rd(Type...)(ref Type x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}

void main(){
  import std.stdio, std.string, std.conv, std.algorithm;

  int n; scanf("%d", &n);
  struct P{int l, r;}
  auto seq=new P[](n);
  foreach(i; 0..n){
    int a, b; scanf("%d %d", &a, &b);
    seq[i]=P(a, b);
  }

  struct T{int x, idx;}
  import std.container;
  auto tree=new RedBlackTree!(T, "a.x<b.x", true);
  foreach(i; 0..n) tree.insert(T(seq[i].r, i));
  auto y=new T[](n);
  foreach(i; 0..n) y[i]=T(seq[i].l, i);
  sort!"a.x<b.x"(y);
  foreach(i; 0..n){
    // writeln(i);
    int id=y[i].idx;
    auto lb=tree.lowerBound(T(seq[id].r, id));
    if(lb.empty==false){
      writeln(lb.front.idx+1, " ", id+1);
      goto heaven;
    }else{
      auto eq=tree.equalRange(T(seq[id].r, id));
      if((eq.front==eq.back)==false){
        int j1=eq.front.idx.to!int, j2=eq.back.idx.to!(int);
        if(i!=j1){
          writeln(j1+1, " ", id+1);
        }else if(i!=j2){
          writeln(j2+1, " ", id+1);
        }
        goto heaven;
      }
    }
    // writeln("re");
    tree.removeKey(T(seq[y[i].idx].r, y[i].idx));
  }
  writeln(-1, " ", -1);

  heaven:;
  // writeln(tree);
}

void rd(Type...)(ref Type x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}

void main(){
  import std.stdio, std.string, std.conv, std.algorithm;

  int n; scanf("%d", &n);
  struct P{int l, r;}
  auto seq=new P[](0);
  foreach(i; 0..n){
    int a, b; scanf("%d %d", &a, &b);
    seq~=P(a, b);
  }

  struct LRi{int l, r, id;}
  auto lri=new LRi[](0);
  foreach(i; 0..n) lri~=LRi(seq[i].l, seq[i].r, i);
  sort!((a, b)=>(a.l==b.l ? a.r>b.r : a.l<b.l))(lri);
  struct Ri{int r, id;}
  import std.container;
  auto tree=new RedBlackTree!(Ri, "a.r<b.r");
  foreach(i; 0..n) tree.insert(Ri(seq[i].r, i));
  foreach(elem; lri){
    int id=elem.id, r=seq[id].r;
    tree.removeKey(Ri(r, id));
    auto eq=tree.equalRange(Ri(r, -1));
    if((eq.empty)==false){
      writeln(eq.front.id+1, " ", id+1);
      goto heaven;
    }else{
      auto lb=tree.lowerBound(Ri(r, -1));
      if(lb.empty) continue;
      writeln(lb.back.id+1, " ", id+1);
      goto heaven;
    }
  }

  writeln(-1, " ", -1);
  heaven:;
}

void rd(Type...)(ref Type x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}

void main(){
  import std.stdio, std.string, std.conv, std.algorithm;

  int n; scanf("%d", &n);
  struct P{int l, r;}
  auto seq=new P[](0);
  foreach(i; 0..n){
    int a, b; scanf("%d %d", &a, &b);
    seq~=P(a, b);
  }

  struct LRi{int l, r, id;}
  auto lri=new LRi[](0);
  foreach(i; 0..n) lri~=LRi(seq[i].l, seq[i].r, i);
  sort!((a, b)=>(a.l==b.l ? a.r>b.r : a.l<b.l))(lri);
  struct Ri{int r, id;}
  import std.container;
  auto tree=new RedBlackTree!(Ri, "a.r<b.r", true);
  foreach(i; 0..n) tree.insert(Ri(seq[i].r, i));
  foreach(elem; lri){
    int id=elem.id, r=seq[id].r;
    tree.removeKey(Ri(r, id));
    auto eq=tree.equalRange(Ri(r, -1));
    if((eq.empty)==false){
      writeln(eq.front.id+1, " ", id+1);
      goto heaven;
    }else{
      auto lb=tree.lowerBound(Ri(r, -1));
      if(lb.empty) continue;
      writeln(lb.back.id+1, " ", id+1);
      goto heaven;
    }
  }

  writeln(-1, " ", -1);
  heaven:;
}

void rd(Type...)(ref Type x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}

void main(){
  import std.stdio, std.string, std.conv, std.algorithm;

  int n; scanf("%d", &n);
  struct P{int l, r;}
  auto seq=new P[](n);
  foreach(i; 0..n){
    int a, b; scanf("%d %d", &a, &b);
    seq[i]=P(a, b);
  }

  struct T{int x, idx;}
  import std.container;
  auto tree=new RedBlackTree!(T, "a.x<b.x", true);
  foreach(i; 0..n) tree.insert(T(seq[i].r, i));
  auto y=new T[](n);
  foreach(i; 0..n) y[i]=T(seq[i].l, i);
  sort!"a.x<b.x"(y);
  foreach(i; 0..n){
    // writeln(i);
    int id=y[i].idx;
    auto lb=tree.lowerBound(T(seq[id].r, id));
    if(lb.empty==false){
      writeln(id+1, " ", lb.front.idx+1);
      goto heaven;
    }else{
      auto eq=tree.equalRange(T(seq[id].r, id));
      if((eq.front==eq.back)==false){
        int j1=eq.front.idx.to!int, j2=eq.back.idx.to!(int);
        if(i!=j1){
          writeln(id+1, " ", j1+1);
        }else if(i!=j2){
          writeln(id+1, " ", j2+1);
        }
        goto heaven;
      }
    }
    // writeln("re");
    tree.removeKey(T(seq[y[i].idx].r, y[i].idx));
  }
  writeln(-1, " ", -1);

  heaven:;
  // writeln(tree);
}

void rd(Type...)(ref Type x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  assert(l.length==x.length);
  foreach(i, ref e; x) e=l[i].to!(typeof(e));
}


Fedya has a string $$$S$$$, initially empty, and an array $$$W$$$, also initially empty.There are $$$n$$$ queries to process, one at a time. Query $$$i$$$ consists of a lowercase English letter $$$c_i$$$ and a nonnegative integer $$$w_i$$$. First, $$$c_i$$$ must be appended to $$$S$$$, and $$$w_i$$$ must be appended to $$$W$$$. The answer to the query is the sum of suspiciousnesses for all subsegments of $$$W$$$ $$$[L, \ R]$$$, $$$(1 \leq L \leq R \leq i)$$$.We define the suspiciousness of a subsegment as follows: if the substring of $$$S$$$ corresponding to this subsegment (that is, a string of consecutive characters from $$$L$$$-th to $$$R$$$-th, inclusive) matches the prefix of $$$S$$$ of the same length (that is, a substring corresponding to the subsegment $$$[1, \ R - L + 1]$$$), then its suspiciousness is equal to the minimum in the array $$$W$$$ on the $$$[L, \ R]$$$ subsegment. Otherwise, in case the substring does not match the corresponding prefix, the suspiciousness is $$$0$$$.Help Fedya answer all the queries before the orderlies come for him!

The first line contains an integer $$$n$$$ $$$(1 \leq n \leq 600\,000)$$$ — the number of queries. The $$$i$$$-th of the following $$$n$$$ lines contains the query $$$i$$$: a lowercase letter of the Latin alphabet $$$c_i$$$ and an integer $$$w_i$$$ $$$(0 \leq w_i \leq 2^{30} - 1)$$$. All queries are given in an encrypted form. Let $$$ans$$$ be the answer to the previous query (for the first query we set this value equal to $$$0$$$). Then, in order to get the real query, you need to do the following: perform a cyclic shift of $$$c_i$$$ in the alphabet forward by $$$ans$$$, and set $$$w_i$$$ equal to $$$w_i \oplus (ans \ \& \ MASK)$$$, where $$$\oplus$$$ is the bitwise exclusive "or", $$$\&$$$ is the bitwise "and", and $$$MASK = 2^{30} - 1$$$.

Print $$$n$$$ lines, $$$i$$$-th line should contain a single integer — the answer to the $$$i$$$-th query.

import std.stdio : stdin, write, writeln;

struct Solver {
    this(int n) {
        s = new byte[n], w = new uint[n], fail = new int[n], nextDiff = new int[n],
            stack = new int[n], parent = new int[n], size = new int[n];
    }

    ulong add(int i) {
        fail[i] = -1;
        if (i) {
            int j = i - 1;
            nextDiff[j] = ~fail[j] ? (s[fail[j] + 1] == s[i] ? nextDiff[fail[j]] : fail[j]) : -1;
            while (~j) {
                j = fail[j];
                if (s[j + 1] == s[i]) {
                    fail[i] = j + 1;
                    break;
                }
            }
            for (j = i - 1; ~j;) {
                if (s[j + 1] != s[i]) {
                    int r = findRoot(i - 1 - j);
                    // writeln("remove: ", i - j, " ", i, " ", j);
                    result -= w[r], size[r]--;
                    j = fail[j];
                }
                else {
                    j = nextDiff[j];
                }
            }
        }
        parent[i] = i, size[i] = s[0] == s[i];
        while (top && w[stack[top - 1]] >= w[i]) {
            int j = stack[--top];
            result -= cast(long) size[j] * w[j];
            size[i] += size[j], parent[j] = i;
        }
        stack[top++] = i, result += cast(long) size[i] * w[i];
        // for (i = 0; i < top; ++i) {
        //     write("(", w[stack[i]], " ", size[stack[i]], "),");
        // }
        // writeln();
        return result;
    }

    int findRoot(int u) {
        if (parent[u] != u) {
            parent[u] = findRoot(parent[u]);
        }
        return parent[u];
    }

    byte[] s;
    uint[] w;
    int top = 0;
    ulong result = 0;
    int[] fail, nextDiff, stack, parent, size;
}

void main() {
    import std.bigint : BigInt;
    import std.conv : to;
    import std.string : chomp;

    const int q = stdin.readln.chomp.to!int;
    auto s = new Solver(q);
    BigInt ans = 0;
    for (int i = 0; i < q; ++i) {
        string line = stdin.readln;
        s.s[i] = cast(byte)((line[0] - 'a' + ans) % 26);
        s.w[i] = cast(uint)(line[2 .. $].chomp.to!uint ^ (ans & 0x3FFFFFFF));
        // writeln("append ", cast(char)('a' + s.s[i]), ' ', s.w[i]);
        ans += s.add(i);
        writeln(ans);
    }
}

import std.stdio : stdin, writeln;

struct Solver {
    this(int n) {
        s = new byte[n], w = new uint[n], fail = new int[n], nextDiff = new int[n],
            stack = new int[n], parent = new int[n], size = new int[n];
    }

    ulong add(int i) {
        fail[i] = -1;
        if (i) {
            int j = i - 1;
            nextDiff[j] = ~fail[j] ? (s[fail[j] + 1] == s[i] ? nextDiff[fail[j]] : fail[j]) : -1;
            while (~j) {
                j = fail[j];
                if (s[j + 1] == s[i]) {
                    fail[i] = j + 1;
                    break;
                }
            }
            for (j = i - 1; ~j;) {
                if (s[j + 1] != s[i]) {
                    int r = findRoot(i - j);
                    result -= w[r], size[r]--;
                    j = fail[j];
                }
                else {
                    j = nextDiff[j];
                }
            }
        }
        parent[i] = i, size[i] = s[0] == s[i];
        while (top && w[stack[top - 1]] >= w[i]) {
            int j = stack[--top];
            result -= cast(long) size[j] * w[j];
            size[i] += size[j], parent[j] = i;
        }
        stack[top++] = i, result += cast(long) size[i] * w[i];
        return result;
    }

    int findRoot(int u) {
        if (parent[u] != u) {
            parent[u] = findRoot(parent[u]);
        }
        return parent[u];
    }

    byte[] s;
    uint[] w;
    int top = 0;
    ulong result = 0;
    int[] fail, nextDiff, stack, parent, size;
}

void main() {
    import std.bigint : BigInt;
    import std.conv : to;
    import std.string : chomp;

    const int q = stdin.readln.chomp.to!int;
    auto s = new Solver(q);
    BigInt ans = 0;
    for (int i = 0; i < q; ++i) {
        string line = stdin.readln;
        s.s[i] = cast(byte)((line[0] - 'a' + ans) % 26);
        s.w[i] = cast(uint)(line[2 .. $].chomp.to!uint ^ (ans & 0x3FFFFFFF));
        ans += s.add(i);
        writeln(ans);
    }
}


You are given an integer $$$n$$$. In one move, you can either multiply $$$n$$$ by two or divide $$$n$$$ by $$$6$$$ (if it is divisible by $$$6$$$ without the remainder).Your task is to find the minimum number of moves needed to obtain $$$1$$$ from $$$n$$$ or determine if it's impossible to do that.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 2 \cdot 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow.  The only line of the test case contains one integer $$$n$$$ ($$$1 \le n \le 10^9$$$).

For each test case, print the answer — the minimum number of moves needed to obtain $$$1$$$ from $$$n$$$ if it's possible to do that or -1 if it's impossible to obtain $$$1$$$ from $$$n$$$.

NoteConsider the sixth test case of the example. The answer can be obtained by the following sequence of moves from the given integer $$$15116544$$$:  Divide by $$$6$$$ and get $$$2519424$$$;  divide by $$$6$$$ and get $$$419904$$$;  divide by $$$6$$$ and get $$$69984$$$;  divide by $$$6$$$ and get $$$11664$$$;  multiply by $$$2$$$ and get $$$23328$$$;  divide by $$$6$$$ and get $$$3888$$$;  divide by $$$6$$$ and get $$$648$$$;  divide by $$$6$$$ and get $$$108$$$;  multiply by $$$2$$$ and get $$$216$$$;  divide by $$$6$$$ and get $$$36$$$;  divide by $$$6$$$ and get $$$6$$$;  divide by $$$6$$$ and get $$$1$$$.

import std.stdio;

void main() {
    uint t, n, twos, threes;

    scanf("%d", &t);
    while(t--) {
        int ans;
        scanf("%d", &n);

        twos = 0;
        while(n % 2 ==0) {
            twos++;
            n /= 2;
        }

        threes = 0;
        while(n % 3 == 0) {
            threes++;
            n /= 3;
        }

        if(n != 1 || twos > threes) ans = -1;
        else if (twos == threes) ans = twos;
        else ans = twos + (threes - twos) * 2;

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

}

import std.stdio;

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

  foreach (i; 0..t) {
    long n;
    readf!"%d\n"(n);

    auto s = 0;
    // remove as many factors of 6 as possible
    while (n % 6 == 0) {
      n /= 6;
      s += 1;
    }

    while (n % 3 == 0) {
      n /= 3;
      s += 2; // multiply, then divide
    }

    if (n == 1) {
      writeln(s);
    } else {
      writeln(-1);
    }
  }
}

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

int solve (int n)
{
	if (n == 1)
	{
		return 0;
	}
	else if (n % 3 != 0)
	{
		return -1;
	}
	else if (n % 2 != 0)
	{
		int res = solve (n * 2);
		return (res == -1) ? -1 : res + 1;
	}
	else
	{
		int res = solve (n / 6);
		return (res == -1) ? -1 : res + 1;
	}
}

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		readln.strip.to !(int).solve.writeln;
	}
}


There is a frog staying to the left of the string $$$s = s_1 s_2 \ldots s_n$$$ consisting of $$$n$$$ characters (to be more precise, the frog initially stays at the cell $$$0$$$). Each character of $$$s$$$ is either 'L' or 'R'. It means that if the frog is staying at the $$$i$$$-th cell and the $$$i$$$-th character is 'L', the frog can jump only to the left. If the frog is staying at the $$$i$$$-th cell and the $$$i$$$-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell $$$0$$$.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the $$$n+1$$$-th cell. The frog chooses some positive integer value $$$d$$$ before the first jump (and cannot change it later) and jumps by no more than $$$d$$$ cells at once. I.e. if the $$$i$$$-th character is 'L' then the frog can jump to any cell in a range $$$[max(0, i - d); i - 1]$$$, and if the $$$i$$$-th character is 'R' then the frog can jump to any cell in a range $$$[i + 1; min(n + 1; i + d)]$$$.The frog doesn't want to jump far, so your task is to find the minimum possible value of $$$d$$$ such that the frog can reach the cell $$$n+1$$$ from the cell $$$0$$$ if it can jump by no more than $$$d$$$ cells at once. It is guaranteed that it is always possible to reach $$$n+1$$$ from $$$0$$$.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. The next $$$t$$$ lines describe test cases. The $$$i$$$-th test case is described as a string $$$s$$$ consisting of at least $$$1$$$ and at most $$$2 \cdot 10^5$$$ characters 'L' and 'R'. It is guaranteed that the sum of lengths of strings over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum |s| \le 2 \cdot 10^5$$$).

For each test case, print the answer — the minimum possible value of $$$d$$$ such that the frog can reach the cell $$$n+1$$$ from the cell $$$0$$$ if it jumps by no more than $$$d$$$ at once.

NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example, the frog can only jump directly from $$$0$$$ to $$$n+1$$$.In the third test case of the example, the frog can choose $$$d=3$$$, jump to the cell $$$3$$$ from the cell $$$0$$$ and then to the cell $$$4$$$ from the cell $$$3$$$.In the fourth test case of the example, the frog can choose $$$d=1$$$ and jump $$$5$$$ times to the right.In the fifth test case of the example, the frog can only jump directly from $$$0$$$ to $$$n+1$$$.In the sixth test case of the example, the frog can choose $$$d=1$$$ and jump $$$2$$$ times to the right.

import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric;

void main()
{
    auto T = readln.chomp.to!int;
    foreach (_; 0..T) {
        auto S = readln.chomp;
        int max_l, l;
        foreach (c; S) {
            if (c == 'L') {
                l += 1;
                max_l = max(l, max_l);
            } else {
                l = 0;
            }
        }
        writeln(max_l + 1);
    }
}

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

string FMT_F = "%.10f";

static File _f;
void file_io(string fn) { _f = File(fn, "r"); }
static string[] s_rd;
T _RD(T = long)() { while(!s_rd.length) s_rd = readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T _RD(T = long)(File f) { while(!s_rd.length) s_rd = f.readln.chomp.split; string res = s_rd[0]; s_rd.popFront; return res.to!T; }
T[] _RDA(T = long)(T fix = 0) { auto r = readln.chomp.split.to!(T[]); r[] += fix; return r; }
T[] _RDA(T = long)(File f, T fix = 0) { auto r = f.readln.chomp.split.to!(T[]); r[] += fix; return r; }
T RD(T = long)() { if (_f.isOpen) return _RD!T(_f); else return _RD!T; }
T[] RDA(T = long)(T fix = 0) { if (_f.isOpen)  return _RDA!T(_f, fix); else return _RDA!T(fix); }

size_t[] MAKE_IDX(alias less = "a < b", Range)(Range range) { auto idx = new size_t[](range.length); makeIndex!(less)(range, idx); return idx;}
size_t MIN_POS(alias less = "a < b", Range)(Range range) { auto r = minPos!(less)(range); return range.length - r.length; }

void chmin(T)(ref T x, T y) { x = min(x, y); } void chmax(T)(ref T x, T y) { x = max(x, y); }
bool inside(T)(T x, T b, T e) { return x >= b && x < e; }
T lcm(T)(T x, T y) { return x * (y / gcd(x, y)); }

//long mod = 10^^9 + 7;
long mod = 998244353;
//long mod = 1_000_003;
void moda(T)(ref T x, T y) { x = (x + y) % mod; }
void mods(T)(ref T x, T y) { x = ((x + mod) - (y % mod)) % mod; }
void modm(T)(ref T x, T y) { x = (x * y) % mod; }
void modpow(T)(ref T x, T y) { if (!y) { x = 1; return; } auto t = x; x.modpow(y>>1); x.modm(x); if (y&1) x.modm(t); }
void modd(T)(ref T x, T y) { x.modm(y.modpow(mod - 2)); }

T binarySearch(alias pred, T)(T ok, T ng)
{
	while (abs(ok-ng) > 1)
	{
		auto mid = (ok+ng)/2;
		if (unaryFun!pred(mid)) ok = mid;
		else ng = mid;
	}
	return ok;
}

void main()
{
	auto t = RD!int;
	auto ans = new int[](t);
	foreach (ti; 0..t)
	{
		auto s = RD!string;
		auto n = cast(int)s.length;
		bool f(int d)
		{
			int[] open = [0, d-1];
			auto used = new bool[](n+1);
			while (!open.empty)
			{
				auto pos = open.front; open.popFront;
				if (pos == n) return true;
				int nPos1, nPos2;
				if (s[pos] == 'L')
				{
					nPos1 = max(0, pos-1);
					nPos2 = max(0, pos-d);
				}
				else
				{
					nPos1 = min(n, pos+1);
					nPos2 = min(n, pos+d);
				}
				if (used[nPos1] == false)
				{
					open ~= nPos1;
					used[nPos1] = true;
				}
				if (used[nPos2] == false)
				{
					open ~= nPos2;
					used[nPos2] = true;
				}
			}
			return false;
		}
		ans[ti] = binarySearch!(f)(n+1, 0);
	}

	foreach (e; ans)
		writeln(e);
	stdout.flush;
	debug readln;
}


The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).

The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages. Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages. The numbers in the lines are separated by single spaces.

Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).

NoteIn the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.In the third sample employee 2 must learn language 2.

import std.algorithm;
import std.container;
import std.exception;
import std.math;
import std.stdio;
import std.string;
import std.typecons;

immutable int MAX_N = 205;

bool [MAX_N] [MAX_N] a;
bool [MAX_N] b;
int n, m;

void recur (int v)
{
	if (b[v])
	{
		return;
	}
	b[v] = true;
	foreach (i; 0..n + m)
	{
		if (a[v][i])
		{
			recur (i);
		}
	}
}

void main ()
{
	while (readf (" %s %s", &n, &m) > 0)
	{
		foreach (i; 0..n + m)
		{
			foreach (j; 0..n + m)
			{
				a[i][j] = false;
			}
		}
		bool ok = false;
		foreach (i; 0..n)
		{
			int k;
			readf (" %s", &k);
			foreach (j; 0..k)
			{
				int p;
				readf (" %s", &p);
				p--;
				a[i][n + p] = true;
				a[n + p][i] = true;
				ok = true;
			}
		}
		foreach (i; 0..n + m)
		{
			b[i] = false;
		}
		int res = !ok;
		foreach (i; 0..n)
		{
			if (!b[i])
			{
				recur (i);
				res++;
			}
		}
		res--;
		writefln ("%s", res);
	}
}

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, m;
    readVars(n, m);

    int z;
    auto uf = new UnionFind(m + 1);
    auto exist = new bool[](m + 1);

    foreach(i ; 0 .. n){
        auto line = readln.split.to!(int[]);
        if(line[0] == 0){
            z++;
        }
        else{
            foreach(j ; 1 .. line.length){
                exist[line[j]] = true;

                if(j > 1){
                    uf.unite(line[j], line[j - 1]);
                }
            }
        }
    }

    if(z == n){
        writeln(n);
        return;
    }

    auto rbt = redBlackTree!int;

    foreach(i ; 1 .. m + 1){
        if (exist[i]) {
            rbt.insert(uf.find_root(i));
        }
    }

    auto ans = rbt.length.to!int + z - 1;

    writeln(ans);
}

class UnionFind {
private:
    int[] p;
    int[] rank;

public:
    this(int N){
        p = iota(N).array;
        rank = new int[](N);
    }

    int find_root(int x){
        if(x != p[x]){
            p[x] = find_root(p[x]);
        }

        return p[x];
    }

    bool same(int x, int y){
        return find_root(x) == find_root(y);
    }

    void unite(int x, int y){
        x = find_root(x);
        y = find_root(y);

        if(x == y) return;

        if(rank[x] < rank[y]){
            p[x] = y;
        }
        else {
            p[y] = x;

            if(rank[x] == rank[y]) rank[x]++;
        }
    }
}

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, std.string, std.algorithm;
import std.conv, std.array;
import std.container;
import std.typecons;
import std.c.stdio;

void main() {
    int n, m; readf("%d %d\n", &n, &m);
    bool[][] F = new bool[][n];
    foreach (ref L; F) L = new bool[m];
    for (int i = 0; i < n; i++) {
        int c; scanf("%d ", &c);
        for (int j = 0; j < c; j++) {
            int l; scanf("%d", &l);
            l--;
            F[i][l] = true;
        }
    }
    bool[] U = new bool[n];
    int c = 0;
    void dfs(int v) {
        if (U[v]) return;
        U[v] = true;
        for (int i = 0; i < m; i++) {
            if (F[v][i]) {
                for (int j = 0; j < n; j++) {
                    if (F[j][i]) {
                        dfs(j);
                    }
                }
            }
        }
    }
    for (int i = 0; i < n; i++) {
        if (U[i]) continue;
        c++;
        dfs(i);
    }
    int f = 0;
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            if (F[i][j])
               f = 1;
    writeln(c-f);
}

import std.algorithm;
import std.container;
import std.exception;
import std.math;
import std.stdio;
import std.string;
import std.typecons;

immutable int MAX_N = 205;

bool [MAX_N] [MAX_N] a;
bool [MAX_N] b;
int n, m;

void recur (int v)
{
	if (b[v])
	{
		return;
	}
	b[v] = true;
	foreach (i; 0..n + m)
	{
		if (a[v][i])
		{
			recur (i);
		}
	}
}

void main ()
{
	while (readf (" %s %s", &n, &m) > 0)
	{
	        foreach (i; 0..n + m)
	        {
	        	foreach (j; 0..n + m)
	        	{
	        		a[i][j] = false;
	        	}
	        }
		foreach (i; 0..n)
		{
			int k;
			readf (" %s", &k);
			foreach (j; 0..k)
			{
				int p;
				readf (" %s", &p);
				p--;
				a[i][n + p] = true;
				a[n + p][i] = true;
			}
		}
		foreach (i; 0..n + m)
		{
			b[i] = false;
		}
		int res;
		foreach (i; 0..n)
		{
			if (!b[i])
			{
				recur (i);
				res++;
			}
		}
		res--;
		writefln ("%s", res);
	}
}

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, m;
    readVars(n, m);

    int z;
    auto uf = new UnionFind(m + 1);
    auto exist = new bool[](m + 1);

    foreach(i ; 0 .. n){
        auto line = readln.split.to!(int[]);
        if(line[0] == 0){
            z++;
        }
        else{
            foreach(j ; 1 .. line.length){
                exist[line[j]] = true;

                if(j > 1){
                    uf.unite(line[j], line[j - 1]);
                }
            }
        }
    }

    auto rbt = redBlackTree!int;

    foreach(i ; 1 .. m + 1){
        if (exist[i]) {
            rbt.insert(uf.find_root(i));
        }
    }

    auto ans = rbt.length.to!int + z - 1;

    writeln(ans);
}

class UnionFind {
private:
    int[] p;
    int[] rank;

public:
    this(int N){
        p = iota(N).array;
        rank = new int[](N);
    }

    int find_root(int x){
        if(x != p[x]){
            p[x] = find_root(p[x]);
        }

        return p[x];
    }

    bool same(int x, int y){
        return find_root(x) == find_root(y);
    }

    void unite(int x, int y){
        x = find_root(x);
        y = find_root(y);

        if(x == y) return;

        if(rank[x] < rank[y]){
            p[x] = y;
        }
        else {
            p[y] = x;

            if(rank[x] == rank[y]) rank[x]++;
        }
    }
}

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, std.string, std.algorithm;
import std.conv, std.array;
import std.container;
import std.typecons;

void main() {
    int n, m; readf("%d %d\n", &n, &m);
    bool[][] F = new bool[][n];
    foreach (ref L; F) L = new bool[m];
    for (int i = 0; i < n; i++) {
        int c; readf("%d ", &c);
        int[] ls = stdin.readln.split.map!(function int(x){return x.to!int - 1;}).array;
        foreach (l; ls) {
            F[i][l] = true;
        }
    }
    bool[] U = new bool[n];
    int c = 0;
    void dfs(int v) {
        if (U[v]) return;
        U[v] = true;
        for (int i = 0; i < m; i++) {
            if (F[v][i]) {
                for (int j = 0; j < n; j++) {
                    if (F[j][i]) {
                        dfs(j);
                    }
                }
            }
        }
    }
    for (int i = 0; i < n; i++) {
        if (U[i]) continue;
        c++;
        dfs(i);
    }
    writeln(c-1);
}


Polycarp has $$$x$$$ of red and $$$y$$$ of blue candies. Using them, he wants to make gift sets. Each gift set contains either $$$a$$$ red candies and $$$b$$$ blue candies, or $$$a$$$ blue candies and $$$b$$$ red candies. Any candy can belong to at most one gift set.Help Polycarp to find the largest number of gift sets he can create.For example, if $$$x = 10$$$, $$$y = 12$$$, $$$a = 5$$$, and $$$b = 2$$$, then Polycarp can make three gift sets:   In the first set there will be $$$5$$$ red candies and $$$2$$$ blue candies;  In the second set there will be $$$5$$$ blue candies and $$$2$$$ red candies;  In the third set will be $$$5$$$ blue candies and $$$2$$$ red candies. Note that in this example there is one red candy that Polycarp does not use in any gift set.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$). Then $$$t$$$ test cases follow. Each test case consists of a single string containing four integers $$$x$$$, $$$y$$$, $$$a$$$, and $$$b$$$ ($$$1 \le x, y, a, b \le 10^9$$$).

For each test case, output one number — the maximum number of gift sets that Polycarp can make.

// code by cutx64

module main;

import std.string, std.array, std.container, std.typecons;
import std.stdio, std.format, std.file;
import std.algorithm, std.conv, std.functional, std.range, core.bitop;
// import std.bigint, std.complex, std.bitmanip;
// import std.math, std.mathspecial, std.numeric;

void main() {

  int tests;
  readf!"%s\n"(tests);
  foreach(per_test; 0 .. tests) {
    long x, y, a, b;
    readf!"%s %s %s %s\n"(x, y, a, b);
    if (a < b) swap(a, b);
    long low = 0, high = 10 ^^ 9, ans = 0;
    bool check(long v) {
      if (v * b > x) return false;
      long low = 0, high = v, ans = 0;
      while (low <= high) {
        long mid = (low + high) >> 1;
        if (mid * a + (v - mid) * b <= x) ans = mid, low = mid + 1;
        else high = mid - 1;
      }
      return ans * b + (v - ans) * a <= y;
    }
    while (low <= high) {
      long mid = (low + high) >> 1;
      if (check(mid)) low = mid + 1, ans = mid;
      else high = mid - 1;
    }
    ans.writeln;
  }

} // main


You are given two integers $$$n$$$ and $$$m$$$ and an array $$$a$$$ of $$$n$$$ integers. For each $$$1 \le i \le n$$$ it holds that $$$1 \le a_i \le m$$$.Your task is to count the number of different arrays $$$b$$$ of length $$$n$$$ such that:   $$$1 \le b_i \le m$$$ for each $$$1 \le i \le n$$$, and  $$$\gcd(b_1,b_2,b_3,...,b_i) = a_i$$$ for each $$$1 \le i \le n$$$. Here $$$\gcd(a_1,a_2,\dots,a_i)$$$ denotes the greatest common divisor (GCD) of integers $$$a_1,a_2,\ldots,a_i$$$.Since this number can be too large, print it modulo $$$998\,244\,353$$$.

Each test consist of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5$$$, $$$1 \le m \le 10^9$$$) — the length of the array $$$a$$$ and the maximum possible value of the element. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le m$$$) — the elements of the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ across all test cases doesn't exceed $$$2 \cdot 10^5$$$.

For each test case, print a single integer — the number of different arrays satisfying the conditions above. Since this number can be large, print it modulo $$$998\,244\,353$$$.

NoteIn the first test case, the possible arrays $$$b$$$ are:   $$$[4,2,1]$$$;  $$$[4,2,3]$$$;  $$$[4,2,5]$$$. In the second test case, the only array satisfying the demands is $$$[1,1]$$$.In the third test case, it can be proven no such array exists.

import core.bitop;
import std.algorithm;
import std.conv;
import std.numeric;
import std.range;
import std.stdio;
import std.string;

immutable int mod = 998_244_353;

void main ()
{
	auto tests = readln.strip.to !(int);
	foreach (test; 0..tests)
	{
		int n, m;
		readf !(" %s %s") (n, m);
		readln;
		auto a = readln.splitter.map !(to !(int)).array;

		int res = 1;
		int cur = 0;
		foreach (ref next; a)
		{
			if (cur % next != 0)
			{
				res = 0;
				break;
			}

			int num;
			if (cur == 0)
			{
				num = 1;
			}
			else
			if (cur == next || cur == 0)
			{
				num = m / next;
			}
			else
			{
				int s = cur / next;
				int [] p;
				for (int d = 2; d * d <= s; d++)
				{
					if (s % d == 0)
					{
						p ~= d;
						do
						{
							s /= d;
						}
						while (s % d == 0);
					}
				}
				if (s > 1)
				{
					p ~= s;
				}
				debug {writeln ("p = ", p);}

				num = 0;
				auto len = p.length.to !(int);
				foreach (u; 0..(1 << len))
				{
					int e = 1;
					foreach (i; 0..len)
					{
						if (u & (1 << i))
						{
							e *= -p[i];
						}
					}
					num += m / (next * e);
				}
			}

			debug {writeln ("num = ", num);}
			res = (res * 1L * num) % mod;
			cur = next;
		}
		writeln (res);
	}
}