You are given n segments on the Ox-axis. You can drive a nail in any integer point on the Ox-axis line nail so, that all segments containing this point, are considered nailed down. If the nail passes through endpoint of some segment, this segment is considered to be nailed too. What is the smallest number of nails needed to nail all the segments down?

The first line of the input contains single integer number n (1 ≤ n ≤ 1000) — amount of segments. Following n lines contain descriptions of the segments. Each description is a pair of integer numbers — endpoints coordinates. All the coordinates don't exceed 10000 by absolute value. Segments can degenarate to points.

The first line should contain one integer number — the smallest number of nails needed to nail all the segments down. The second line should contain coordinates of driven nails separated by space in any order. If the answer is not unique, output any.

'use strict';

var findIntersection = function (segment1, segment2) {                                                                          // segments at this function call are sorted
    // console.log('findIntersection');
    // console.log('segment1', segment1);
    // console.log('segment2', segment2);
    if (segment1.s == segment2.s && segment1.e == segment2.e) {                                                                 // total intersection
        // console.log('here1');
        return segment1;
    } else if ((segment1.s == segment2.s && segment1.s < segment2.e) && (segment1.e >= segment2.s && segment1.e < segment2.e)) { // segment1 is contained
        // console.log('here2');
        return segment1;
    } else if ((segment1.s < segment2.s && segment1.s < segment2.e) && (segment1.e >= segment2.s && segment1.e <= segment2.e)) {  // partial intersection
        // console.log('here3');
        return {s: segment2.s, e: segment1.e};
    } else if ((segment1.s < segment2.s && segment1.s < segment2.e) && (segment1.e > segment2.s && segment1.e > segment2.e)) {  // segment2 is contained
        // console.log('here4');
        return segment2;
    } else {
        // console.log('here5');
        return null;                                                                                // no intersection
    }

}

var sortSegments = function (segmentA, segmentB) {
    if (segmentA.s < segmentB.s) {
        return -1;
    } else if (segmentA.s > segmentB.s) {
        return 1;
    }

    if (segmentA.e < segmentB.e) {
        return -1;
    } else if (segmentA.e > segmentB.e) {
        return 1;
    }

    return 0;
}

var getnails = function (sortedSegments, lastIntersection, currentId, nails) {
    if (currentId == sortedSegments.length) {
        nails.push(lastIntersection.e);
        console.log(nails.length);
        console.log(nails.join(' '));
        return;
    }

    var foundIntersection = findIntersection(lastIntersection, sortedSegments[currentId]);
    if (foundIntersection == null) { // no intersection between lastIntersecion and the current segment
        // console.log('pushing', lastIntersection.e);
        nails.push(lastIntersection.e);
        getnails(sortedSegments, sortedSegments[currentId], ++currentId, nails);
    } else {
        getnails(sortedSegments, foundIntersection, ++currentId, nails);
    }
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

var allSegments = [];
var formSegments = function (max) {
    var num;
    for (var i = 0; i < max; i++) {
        num = readline().split(" ").map(x => parseInt(x));
        if (num[0] < num[1]) {
            allSegments.push({s: num[0], e: num[1]})
        } else {
            allSegments.push({s: num[1], e: num[0]})
        }

    }
}

function main() {
    const x = readline();
    formSegments(x);
    // console.log(allSegments);
    allSegments.sort(sortSegments);
    // console.log(allSegments);
    var nails = [];
    getnails(allSegments, allSegments[0], 1, nails);
}

function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i]);
	};
	return tokens;
}

function main() {
	var segmentNum = parseInt(readline());
	var segments = [];
	for (var i = 0; i < segmentNum; i += 1) {
		var integers = tokenizeIntegers(readline());
		integers.sort(function(a, b) {
			return a-b;
		});
		segments.push({ low: integers[0], high: integers[1] });
	}

	segments.sort(function(a, b) {
		return a.high - b.high;
	});

	var nails = [segments[0].high];
	for (var i = 1; i < segmentNum; i += 1) {
		if (segments[i].low <= nails[nails.length-1]) {
			continue;
		}
		nails.push(segments[i].high);
	}

	print(nails.length);
	print(nails.join(' '));
}

main();

function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i]);
	};
	return tokens;
}

function main() {
	var segmentNum = parseInt(readline());
	var segments = [];
	for (var i = 0; i < segmentNum; i += 1) {
		var integers = tokenizeIntegers(readline());
		integers.sort(function(a, b) {
			return a-b;
		});
		segments.push({ low: integers[0], high: integers[1] });
	}

	segments.sort(function(a, b) {
		if (a.high != b.high) {
			return a.high - b.high;
		}
		return a.low - b.low;
	});

	var nails = [segments[0].high];
	for (var i = 1; i < segmentNum; i += 1) {
		if (segments[i].low <= nails[nails.length-1]) {
			continue;
		}
		nails.push(segments[i].high);
	}

	print(nails.length);
	print(nails.join(' '));
}

main();

'use strict';

var findIntersection = function (segment1, segment2) {                                                                          // segments at this function call are sorted
    // console.log('findIntersection');
    // console.log('segment1', segment1);
    // console.log('segment2', segment2);
    if (segment1.s == segment2.s && segment1.e == segment2.e) {                                                                 // total intersection
        // console.log('here1');
        return segment1;
    } else if ((segment1.s == segment2.s && segment1.s < segment2.e) && (segment1.e > segment2.s && segment1.e < segment2.e)) { // segment1 is contained
        // console.log('here2');
        return segment1;
    } else if ((segment1.s < segment2.s && segment1.s < segment2.e) && (segment1.e >= segment2.s && segment1.e < segment2.e)) {  // partial intersection
        // console.log('here3');
        return {s: segment2.s, e: segment1.e};
    } else if ((segment1.s < segment2.s && segment1.s < segment2.e) && (segment1.e > segment2.s && segment1.e > segment2.e)) {  // segment2 is contained
        // console.log('here4');
        return segment2;
    } else {
        // console.log('here5');
        return null;                                                                                // no intersection
    }

}

var sortSegments = function (segmentA, segmentB) {
    if (segmentA.s < segmentB.s) {
        return -1;
    } else if (segmentA.s > segmentB.s) {
        return 1;
    }

    if (segmentA.e < segmentB.e) {
        return -1;
    } else if (segmentA.e > segmentB.e) {
        return 1;
    }

    return 0;
}

var getnails = function (sortedSegments, lastIntersection, currentId, nails) {
    if (currentId == sortedSegments.length) {
        nails.push(lastIntersection.e);
        console.log(nails.length);
        console.log(nails.join(' '));
        return;
    }

    var foundIntersection = findIntersection(lastIntersection, sortedSegments[currentId]);
    if (foundIntersection == null) { // no intersection between lastIntersecion and the current segment
        nails.push(lastIntersection.e);
        getnails(sortedSegments, sortedSegments[currentId], ++currentId, nails);
    } else {
        getnails(sortedSegments, foundIntersection, ++currentId, nails);
    }
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

var allSegments = [];
var formSegments = function (max) {
    var num;
    for (var i = 0; i < max; i++) {
        num = readline().split(" ").map(x => parseInt(x));
        if (num[0] < num[1]) {
            allSegments.push({s: num[0], e: num[1]})
        } else {
            allSegments.push({s: num[1], e: num[0]})
        }

    }
}

function main() {
    const x = readline();
    formSegments(x);
    // console.log(allSegments);
    allSegments.sort(sortSegments);
    // console.log(allSegments);
    var nails = [];
    getnails(allSegments, allSegments[0], 1, nails);
}

'use strict';

var findIntersection = function (segment1, segment2) {                                                                          // segments at this function call are sorted
    // console.log('findIntersection');
    // console.log('segment1', segment1);
    // console.log('segment2', segment2);
    if (segment1.s == segment2.s && segment1.e == segment2.e) {                                                                 // total intersection
        // console.log('here1');
        return segment1;
    } else if ((segment1.s == segment2.s && segment1.s < segment2.e) && (segment1.e > segment2.s && segment1.e < segment2.e)) { // segment1 is contained
        // console.log('here2');
        return segment1;
    } else if ((segment1.s < segment2.s && segment1.s < segment2.e) && (segment1.e >= segment2.s && segment1.e <= segment2.e)) {  // partial intersection
        // console.log('here3');
        return {s: segment2.s, e: segment1.e};
    } else if ((segment1.s < segment2.s && segment1.s < segment2.e) && (segment1.e > segment2.s && segment1.e > segment2.e)) {  // segment2 is contained
        // console.log('here4');
        return segment2;
    } else {
        // console.log('here5');
        return null;                                                                                // no intersection
    }

}

var sortSegments = function (segmentA, segmentB) {
    if (segmentA.s < segmentB.s) {
        return -1;
    } else if (segmentA.s > segmentB.s) {
        return 1;
    }

    if (segmentA.e < segmentB.e) {
        return -1;
    } else if (segmentA.e > segmentB.e) {
        return 1;
    }

    return 0;
}

var getnails = function (sortedSegments, lastIntersection, currentId, nails) {
    if (currentId == sortedSegments.length) {
        nails.push(lastIntersection.e);
        console.log(nails.length);
        console.log(nails.join(' '));
        return;
    }

    var foundIntersection = findIntersection(lastIntersection, sortedSegments[currentId]);
    if (foundIntersection == null) { // no intersection between lastIntersecion and the current segment
        // console.log('pushing', lastIntersection.e);
        nails.push(lastIntersection.e);
        getnails(sortedSegments, sortedSegments[currentId], ++currentId, nails);
    } else {
        getnails(sortedSegments, foundIntersection, ++currentId, nails);
    }
}

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}
// Make a Snippet for the code above this and then write your logic in main();

var allSegments = [];
var formSegments = function (max) {
    var num;
    for (var i = 0; i < max; i++) {
        num = readline().split(" ").map(x => parseInt(x));
        if (num[0] < num[1]) {
            allSegments.push({s: num[0], e: num[1]})
        } else {
            allSegments.push({s: num[1], e: num[0]})
        }

    }
}

function main() {
    const x = readline();
    formSegments(x);
    // console.log(allSegments);
    allSegments.sort(sortSegments);
    // console.log(allSegments);
    var nails = [];
    getnails(allSegments, allSegments[0], 1, nails);
}

function trim(s) {
	return s.replace(/^\s+|\s+$/gm, '');
}

function tokenize(s) {
	return trim(s).split(/\s+/);
}

function tokenizeIntegers(s) {
	var tokens = tokenize(s);
	for (var i = 0; i < tokens.length; i += 1) {
		tokens[i] = parseInt(tokens[i]);
	};
	return tokens;
}

function main() {
	var segmentNum = parseInt(readline());
	var segments = [];
	for (var i = 0; i < segmentNum; i += 1) {
		var integers = tokenizeIntegers(readline());
		integers.sort();
		segments.push({ low: integers[0], high: integers[1] });
	}

	segments.sort(function(a, b) {
		if (a.high != b.high) {
			return a.high - b.high;
		}
		return a.low - b.low;
	});

	var nails = [segments[0].high];
	for (var i = 1; i < segmentNum; i += 1) {
		if (segments[i].low <= nails[nails.length-1]) {
			continue;
		}
		nails.push(segments[i].high);
	}

	print(nails.length);
	print(nails.join(' '));
}

main();


A permutation p of length n is a sequence of distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n). A permutation is an identity permutation, if for any i the following equation holds pi = i. A swap (i, j) is the operation that swaps elements pi and pj in the permutation. Let's assume that f(p) is the minimum number of swaps that you need to make the permutation p an identity permutation. Valera wonders, how he can transform permutation p into any permutation q, such that f(q) = m, using the minimum number of swaps. Help him do that.

The first line contains integer n (1 ≤ n ≤ 3000) — the length of permutation p. The second line contains n distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n) — Valera's initial permutation. The last line contains integer m (0 ≤ m < n).

In the first line, print integer k — the minimum number of swaps. In the second line, print 2k integers x1, x2, ..., x2k — the description of the swap sequence. The printed numbers show that you need to consecutively make swaps (x1, x2), (x3, x4), ..., (x2k - 1, x2k).  If there are multiple sequence swaps of the minimum length, print the lexicographically minimum one.

NoteSequence x1, x2, ..., xs is lexicographically smaller than sequence y1, y2, ..., ys, if there is such integer r (1 ≤ r ≤ s), that x1 = y1, x2 = y2, ..., xr - 1 = yr - 1 and xr < yr.

var nextToken = new function() {
    var line = [];
    var lineIndex = 0;

    return function() {
        while (lineIndex >= line.length) {
            line = readline().split(/\s+/);
            lineIndex = 0;
        }

        return line[lineIndex++];
    }
}();

var nextInt = function() {
    return parseInt(nextToken(), 10);
};

var nextInts = function(n) {
    var a = [], i;
    for (i = 0; i < n; ++i) {
        a.push(nextInt());
    }

    return a;
}

var f = function(p) {
    var used = [];
    var res = 0, cur, i, j;

    for (i = 0; i < p.length; ++i) {
        if (used[i] === undefined) {
            cur = 0;
            j = i;
            while (used[j] === undefined) {
                used[j] = true;
                cur++;

                j = p[j];
            }

            res += cur - 1;
        }
    }

    return res;
}

var main = function () {
    var n = nextInt();
    var p = nextInts(n);
    p.forEach(function(v, i, self) {
        self[i] = v - 1;
    });

    var m = nextInt();

    var ans = [];

    var swap = function(i, j) {
        var t = p[i];
        p[i] = p[j];
        p[j] = t;

        ans.push(Math.min(i + 1, j + 1));
        ans.push(Math.max(i + 1, j + 1));
    }

    var inc = function() {
        var used = [];
        var first, second;
        var i, j;

        for (i = 0; i < n; ++i) {
            if (used[i] === undefined) {
                j = i;
                while (used[j] === undefined) {
                    used[j] = true;
                    j = p[j];
                }

                if (first === undefined) {
                    first = i;
                } else {
                    second = i;
                    break;
                }
            }
        }

        if (first === undefined || second === undefined) {
            throw "FAIL!";
        }

        swap(first, second);
    }

    var dec = function() {
        var used = [];
        var i, j, loop;

        for (i = 0; i < n; ++i) {
            if (used[i] === undefined) {
                loop = [];
                j = i;
                while (used[j] === undefined) {
                    loop.push(j);
                    used[j] = true;
                    j = p[j];
                }

                if (loop.length > 1) {
                    loop.sort(function(a, b) { return a - b; });
                    swap(loop[0], loop[1]);
                    break;
                }
            }
        }
    }

    var dif = f(p) - m;
    var func;

    if (dif > 0) {
        func = dec;
    } else {
        func = inc;
        dif = -dif;
    }

    for (var i = 0; i < dif; ++i)
        func();

    print(ans.length / 2);
    print(ans.join(" "));
};

main();

var nextToken = new function() {
    var line = [];
    var lineIndex = 0;

    return function() {
        while (lineIndex >= line.length) {
            line = readline().split(/\s+/);
            lineIndex = 0;
        }

        return line[lineIndex++];
    }
}();

var nextInt = function() {
    return parseInt(nextToken(), 10);
};

var nextInts = function(n) {
    var a = [], i;
    for (i = 0; i < n; ++i) {
        a.push(nextInt());
    }

    return a;
}

var f = function(p) {
    var used = [];
    var res = 0, cur, i, j;

    for (i = 0; i < p.length; ++i) {
        if (used[i] === undefined) {
            cur = 0;
            j = i;
            while (used[j] === undefined) {
                used[j] = true;
                cur++;

                j = p[j];
            }

            res += cur - 1;
        }
    }

    return res;
}

var main = function () {
    var n = nextInt();
    var p = nextInts(n);
    p.forEach(function(v, i, self) {
        self[i] = v - 1;
    });

    var m = nextInt();

    var ans = [];

    var swap = function(i, j) {
        var t = p[i];
        p[i] = p[j];
        p[j] = t;

        ans.push(Math.min(i + 1, j + 1));
        ans.push(Math.max(i + 1, j + 1));
    }

    var inc = function() {
        var used = [];
        var first, second;
        var i, j;

        for (i = 0; i < n; ++i) {
            if (used[i] === undefined) {
                j = i;
                while (used[j] === undefined) {
                    used[j] = true;
                    j = p[j];
                }

                if (first === undefined) {
                    first = i;
                } else {
                    second = i;
                    break;
                }
            }
        }

        if (first === undefined || second === undefined) {
            throw "FAIL!";
        }

        swap(first, second);
    }

    var dec = function() {
        var used = [];
        var i, j, loop;

        for (i = 0; i < n; ++i) {
            if (used[i] === undefined) {
                loop = [];
                j = i;
                while (used[j] === undefined) {
                    loop.push(j);
                    used[j] = true;
                    j = p[j];
                }

                if (loop.length > 1) {
                    loop.sort();
                    swap(loop[0], loop[1]);
                    break;
                }
            }
        }
    }

    var cf;
    while (true) {
        cf = f(p);
        if (cf < m)
            inc();
        if (cf > m)
            dec();
        if (cf === m)
            break;
    }

    print(ans.length / 2);
    print(ans.join(" "));
};

main();

var nextToken = new function() {
    var line = [];
    var lineIndex = 0;

    return function() {
        while (lineIndex >= line.length) {
            line = readline().split(/\s+/);
            lineIndex = 0;
        }

        return line[lineIndex++];
    }
}();

var nextInt = function() {
    return parseInt(nextToken(), 10);
};

var nextInts = function(n) {
    var a = [], i;
    for (i = 0; i < n; ++i) {
        a.push(nextInt());
    }

    return a;
}

var f = function(p) {
    var used = [];
    var res = 0, cur, i, j;

    for (i = 0; i < p.length; ++i) {
        if (used[i] === undefined) {
            cur = 0;
            j = i;
            while (used[j] === undefined) {
                used[j] = true;
                cur++;

                j = p[j];
            }

            res += cur - 1;
        }
    }

    return res;
}

var main = function () {
    var n = nextInt();
    var p = nextInts(n);
    p.forEach(function(v, i, self) {
        self[i] = v - 1;
    });

    var m = nextInt();

    var ans = [];

    var swap = function(i, j) {
        var t = p[i];
        p[i] = p[j];
        p[j] = t;

        ans.push(Math.min(i + 1, j + 1));
        ans.push(Math.max(i + 1, j + 1));
    }

    var inc = function() {
        var used = [];
        var first, second;
        var i, j;

        for (i = 0; i < n; ++i) {
            if (used[i] === undefined) {
                j = i;
                while (used[j] === undefined) {
                    used[j] = true;
                    j = p[j];
                }

                if (first === undefined) {
                    first = i;
                } else {
                    second = i;
                    break;
                }
            }
        }

        if (first === undefined || second === undefined) {
            throw "FAIL!";
        }

        swap(first, second);
    }

    var dec = function() {
        var used = [];
        var i, j, loop;

        for (i = 0; i < n; ++i) {
            if (used[i] === undefined) {
                loop = [];
                j = i;
                while (used[j] === undefined) {
                    loop.push(j);
                    used[j] = true;
                    j = p[j];
                }

                if (loop.length > 1) {
                    loop.sort();
                    swap(loop[0], loop[1]);
                    break;
                }
            }
        }
    }

    var dif = f(p) - m;
    var func;

    if (dif > 0) {
        func = dec;
    } else {
        func = inc;
        dif = -dif;
    }

    for (var i = 0; i < dif; ++i)
        func();

    print(ans.length / 2);
    print(ans.join(" "));
};

main();


Pari wants to buy an expensive chocolate from Arya. She has n coins, the value of the i-th coin is ci. The price of the chocolate is k, so Pari will take a subset of her coins with sum equal to k and give it to Arya.Looking at her coins, a question came to her mind: after giving the coins to Arya, what values does Arya can make with them? She is jealous and she doesn't want Arya to make a lot of values. So she wants to know all the values x, such that Arya will be able to make x using some subset of coins with the sum k.Formally, Pari wants to know the values x such that there exists a subset of coins with the sum k such that some subset of this subset has the sum x, i.e. there is exists some way to pay for the chocolate, such that Arya will be able to make the sum x using these coins.

The first line contains two integers n and k (1  ≤  n, k  ≤  500) — the number of coins and the price of the chocolate, respectively. Next line will contain n integers c1, c2, ..., cn (1 ≤ ci ≤ 500) — the values of Pari's coins. It's guaranteed that one can make value k using these coins.

First line of the output must contain a single integer q— the number of suitable values x. Then print q integers in ascending order — the values that Arya can make for some subset of coins of Pari that pays for the chocolate.

var nk = readline().split(' ').map(x => Number(x))

var n = nk[0]
var k = nk[1]

var cs = readline().split(' ').map(x => Number(x))

var k1 = k + 1

var pos = new Array(k1 * k1)

pos.fill(false)

pos[0] = true

for (var c = 0; c < n; c++) {
  for (var v = k; v >= 0; v--) {
    for (var x = k; x >= 0; x--) {

      var curr = pos[k1 * v + x]

      var vc = v - cs[c]
      var xc = x - cs[c]

      if (vc >= 0) {
        curr = curr || pos[k1 * vc + x]
      }

      if (vc >= 0 && xc >= 0) {
        curr = curr || pos[k1 * vc + xc]
      }

      pos[k1 * v + x] = curr
    }
  }
}

var count = 0
var answers = []

for (var i = 0; i < k1; i++) {
  if (pos[k1 * k + i]) {
    count++
    answers.push(i)
  }
}

print(String(count))

print(answers.map(x => String(x)).join(' '))

var nk = readline().split(' ').map(x => Number(x))

n = nk[0]
k = nk[1]

var cs = readline().split(' ').map(x => Number(x))

var k1 = k + 1

var pos = new Array(k1 * k1)

pos.fill(false)

pos[0] = true

for (var c = 0; c < n; c++) {
  for (var v = k; v >= 0; v--) {
    for (var x = k; x >= 0; x--) {

      var curr = pos[k1 * v + x]

      var vc = v - cs[c]
      var xc = x - cs[c]

      if (vc >= 0) {
        curr = curr || pos[k1 * vc + x]
      }

      if (vc >= 0 && xc >= 0) {
        curr = curr || pos[k1 * vc + xc]
      }

      pos[k1 * v + x] = curr
    }
  }
}

var count = 0
var answers = []

for (var i = 0; i < k1; i++) {
  if (pos[k1 * k + i]) {
    count++
    answers.push(i)
  }
}

print(String(count))

print(answers.map(x => String(x)).join(' '))


When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided to rearrange them. Help him restore the original number, on condition that it was the maximum possible one.

The first line contains a single integer $$$n$$$ ($$$1 \leqslant n \leqslant 10^5$$$) — the length of the string. The second line contains a string consisting of English lowercase letters: 'z', 'e', 'r', 'o' and 'n'. It is guaranteed that it is possible to rearrange the letters in such a way that they form a sequence of words, each being either "zero" which corresponds to the digit $$$0$$$ or "one" which corresponds to the digit $$$1$$$.

Print the maximum possible number in binary notation. Print binary digits separated by a space. The leading zeroes are allowed.

NoteIn the first example, the correct initial ordering is "zero".In the second example, the correct initial ordering is "oneonezero".

const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

var lines = [];
let counter = 0;

rl.on('line', (input) => {
    lines.push(input);
    counter++;

    if (counter == 2){
        var string = lines[1];
        var ones = 0, zeros = 0;

        for (let i = 0; i < string.length; i++){
            if (string[i] == "n")
                ones++;
            else
            if (string[i] == "z")
                zeros++;
        }

        var result = "";

        for (let i = 0; i < ones; i++)
            result += "1 ";

        for (let i = 0; i < zeros; i++)
            result += "0 ";

        console.log(result);

        process.exit(0);
    }
});

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

let num, str, binary = '';

rl.on('line', n => {
  !num ? num = n : str = n;
  if (num && str) {
    while (str.includes('n')) {
      binary += '1 ';
      ['o', 'n', 'e'].forEach(letter => str = str.replace(letter, ''));
    }
    while (str.includes('z')) {
      binary += '0 ';
      ['z', 'e', 'r', 'o'].forEach(letter => str = str.replace(letter, ''));
    }
    console.log(binary.trim());
    rl.close();
  }
});

process.stdin.setEncoding('utf8');

let input = '';

process.stdin.on('data', (chunk) => {
    if (chunk !== null) {
        input += chunk;
    }
});

process.stdin.on('end', () => {
    input.trim();
    input = input.split('\n');

    let chars = input[1].split('');
    let binaryNotation = [];

    chars.forEach(char => {
        if (char == 'r') binaryNotation.push(0);
        if (char == 'n') binaryNotation.push(1);
    });

    binaryNotation.sort((a, b) => b - a);

    console.log(binaryNotation.join(' '));
    process.exit(0);
})

process.stdin.setEncoding('utf8');

var allinput = "";
process.stdin.on('data', (chunk) => {
  if (chunk !== null) {
    allinput += chunk;
  }
});

process.stdin.on('end', () => {
  allinput.trim();
  allinput = allinput.split(/\s+/);
  let chars = allinput[1].split('');
  let binaryNotation = [];

  chars.forEach(char => {
    if (char == 'r') binaryNotation.push(0);
    if (char == 'n') binaryNotation.push(1);
  });

  binaryNotation.sort((a, b) => b - a);

  process.stdout.write(binaryNotation.join(' ') + '\n');
  process.exit(0);
});

process.stdin.resume()
process.stdin.setEncoding('utf8')
let arr = ""
process.stdin.on('data', function(chunk) {
  arr += chunk
});

process.stdin.on('end', () => {
  arr = arr.split("\n")
  const letters = arr[1]
  let countR = 0, countN = 0
  for(let i = 0, len = arr[0]; i < len; i++) {
    if(letters[i] == 'n') countN ++
    else if(letters[i] == 'r') countR ++
  }

  for(let i = 0; i < countN; i++){
    process.stdout.write('1 ')
  }

  for(let i = 0; i < countR; i++){
    process.stdout.write('0 ')
  }
  console.log()
})

//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error('\n');
  var start = Date.now();
  Main();
  var end = Date.now() - start;
  myerr('time : ' + end + 'ms');
  myerr('memory : ' + Math.round(process.memoryUsage().heapTotal / 1024) + 'KB');
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){
  return {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
  var N = nextInt();
  var s = next();
  var z = 0;
  var o = 0;
  var output = [];
  for(var i = 0; i < N; i++){
    if(s[i] == "z"){
      z++;
    }
    if(s[i] == "n"){
      o++;
    }
  }
  for(var i = 0; i < o; i++){
    output.push(1);
  }
  for(var i = 0; i < z; i++){
    output.push(0);
  }
  myout(myconv(output, 8));
}

const readline = require('readline');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});
let c = 0;

rl.on('line', (str) => {
  if (c === 0) {
    c++;
    return;
  }

  const obj = {};

  for (let i = 0; i < str.length; i++) {
    obj[str[i]] = obj[str[i]] ? obj[str[i]] + 1 : 1;
  }

  const ans = [];

  for (let i = 0; i < obj['n']; i++) {
    ans.push(1);
  }

  for (let i = 0; i < obj['z']; i++) {
    ans.push(0);
  }

  console.log(ans.join(' '));

  c++;
});

const readLine = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout,
});

const input = [];
readLine.on('line', line => input.push(line));

readLine.on('close', () => {
  const [n] = input[0].split(' ').map(x => parseInt(x));
  const line = input[1];

  let lN = 0, lZ = 0, lO = 0, lR = 0, lE = 0;
  for (let i = 0; i < line.length; i += 1)
    if (line[i] === 'e') lE += 1;
    else if (line[i] === 'r') lR += 1;
    else if (line[i] === 'z') lZ += 1;
    else if (line[i] === 'o') lO += 1;
    else lN += 1;

  let min = Math.min(lN, lO, lE);
  let cntOne = min;
  lN -= min; lO -= min; lE -= min;

  let cntZero = Math.min(lZ, lE, lR, lO);
  const answer = [];
  for (let i = 0; i < cntOne; i += 1) answer.push(1);
  for (let i = 0; i < cntZero; i += 1) answer.push(0);

  console.log(answer.join(' '));
});

var readline = require('readline');
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    terminal: false
});

rl.on('line', function(line){
    var param = line.split("\n");
    var n = (param[0].match(/n/g) || []).length;
    var z = (param[0].match(/z/g) || []).length;
    var result='';
    for (let i=0; i<n; i++){
        result = result + '1 ';
    }
    for (let i=0; i<z; i++){
        result = result + '0 ';
    }
    // console.log(result);
    process.stdout.write(result.toString());
});

var readline = require('readline');
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    terminal: false
});

rl.on('line', function(line){
    var param = line.split("\n");
    var n = (param[0].match(/n/g) || []).length;
    var z = (param[0].match(/z/g) || []).length;
    var result='';
    for (let i=0; i<n; i++){
        result = result + '1 ';
    }
    for (let i=0; i<z; i++){
        result = result + '0 ';
    }
    console.log(result.toString());
});

var n = readline();
var string = readline();

var ones = 0, zeros = 0;

for (var i = 0; i < string.length; i++){
    if (string[i] == "n")
        ones++;
    else
        if (string[i] == "z")
            zeros++;
}

var result = "";

for (var i = 0; i < ones; i++)
    result += "1 ";

for (var i = 0; i < zeros; i++)
    result += "0 ";

print(result);

'use strict';

main();

function main() {
  const strLen = parseInt(readline());
  const str = readline();
  const numberOfN = (str.match(new RegExp('n', 'g')) || []).length;
  const numberOfZ = (str.match(new RegExp('z', 'g')) || []).length;

  print('1 '.repeat(numberOfN) + '0 '.repeat(numberOfZ));
}

"use strict";

var n = readline();
var str = readline();
var obj = {
  z: 0,
  e: 0,
  r: 0,
  o: 0,
  n: 0
};
str.split('').forEach(function (l) {
  obj[l] += 1;
});
var amountOfOnes = Math.min(obj['o'], obj['n'], obj['e']);
obj['o'] -= amountOfOnes;
obj['n'] -= amountOfOnes;
obj['e'] -= amountOfOnes;
var amountOfZeros = Math.min(obj['z'], obj['e'], obj['r'], obj['o']);
var answer = [];

for (var i = 0; i < amountOfOnes; i++) {
  answer.push(1);
}

for (var _i = 0; _i < amountOfZeros; _i++) {
  answer.push(0);
}

write(answer.join(' '));

readline()
var line = readline().trim();
var oneCount = (line.match(/n/g) || "").length;
var zeroCount = (line.length - (oneCount * 3)) / 4
var out = []
while (oneCount != 0) {
    out.push(1)
    oneCount--;
}
while (zeroCount != 0) {
    out.push(0)
    zeroCount--;
}
print(out.join(" "))

var n = Number(readline());
var str =  readline();
var mas  = [];
for (var i = 0; i < n; i++)
{
	if (str[i] == 'n')
		mas.push(1);
	else if (str[i] == 'z')
		mas.push(0);

}
mas.sort(function(a, b){return b - a})
print(mas.join(" "));

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};
var len = readline();
var str = readline();
str = str.replaceAll("o",'');
str = str.replaceAll("e",'');
str = str.replaceAll("z",'');
var zero = "";
var one = "";
while(str.length){
    if (str.indexOf("r") > -1){
        str = str.replace("r", "");
        if (!zero){
            zero+="0";
        } else {
            zero+=" 0";
        }

    }
    if (str.indexOf("n") > -1){
        str = str.replace("n", "");
        if (!one){
            one+="1";
        } else {
            one+=" 1";
        }
    }

}
if (one){
write(one + " " + zero);
} else {
    write(zero)
}

//http://codeforces.com/problemset/problem/1220/A

var n = readline();
var l = readline();

var max = "";
for (var i=0; i<n; i++) {
    if (l[i] == "n") max = "1 " + max;
    else if (l[i] == "z") max+= "0 ";
}

print(max);

var charsCount = readline();
var letters = readline();

var countOfLetterZ = (letters.match(/z/g) || []).length;

var zerosCount = countOfLetterZ;
var onesCount = (letters.length - zerosCount*4) / 3;

var binary = [];

for (var i = 0; i < onesCount; i++) {
  binary.push('1')
}

for (var i = 0; i < zerosCount; i++) {
  binary.push('0')
}

write(binary.join(' '))

(function() {
  const n=readline().toString('ascii').trim();
  const p=readline().toString('ascii').trim().split('');

  var s1=p.filter(a=>a=='n').map((a)=> '1');
  var s0=p.filter(a=>a=='z').map((a)=> '0');
  write(s1.concat(s0).join(" "));
}());

var k = +readline();
var str = readline();
var z = 0;
var n = 0;
for(i = 0; i < k ; i++){
    if (str[i] == 'z') z++;
    if (str[i] == 'n') n++;
}
var result = [];
for(i = 0; i < n; i++){
    result.push(1);
}
for(i = 0; i < z; i++){
    result.push(0);
}
print(result.join(" "));

process.stdin.setEncoding('utf8');

process.stdin.on('readable', () => {
    let input = process.stdin.read();
    input = input.trim();
    input = input.split(/\s+/);

    if (input !== null) {
        let chars = input[1].split('');
        let binaryNotation = [];

        chars.forEach(char => {
            if (char == 'r') binaryNotation.push(0);
            if (char == 'n') binaryNotation.push(1);
        });

        binaryNotation.sort((a, b) => b - a);

        process.stdout.write(binaryNotation.join(' ') + '\n');
        process.exit(0);
    }
});

process.stdin.setEncoding('utf8');

process.stdin.on('readable', () => {
    let input = process.stdin.read();
    input = input.trim();
    input = input.split('\n');

    if (input !== null) {
        let chars = input[1].split('');
        let binaryNotation = [];

        chars.forEach(char => {
            if (char == 'r') binaryNotation.push(0);
            if (char == 'n') binaryNotation.push(1);
        });

        binaryNotation.sort((a, b) => b - a);

        process.stdout.write(binaryNotation.join(' ') + '\n');
        process.exit(0);
    }
});

process.stdin.setEncoding('utf8');

var allinput = "";
process.stdin.on('readable', () => {
  var input = process.stdin.read();
  if (input !== null) {
    allinput += input;
  }
});

process.stdin.on('end', () => {
  allinput.trim();
  allinput = allinput.split(/\s+/);
  let chars = allinput[0].split('');
  let binaryNotation = [];

  chars.forEach(char => {
    if (char == 'r') binaryNotation.push(0);
    if (char == 'n') binaryNotation.push(1);
  });

  binaryNotation.sort((a, b) => b - a);

  process.stdout.write(binaryNotation.join(' ') + '\n');
  process.exit(0);
});

const readLine = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout,
});

const input = [];
readLine.on('line', line => input.push(line));

readLine.on('close', () => {
  const [n] = input[0].split(' ').map(x => parseInt(x));
  const line = input[1];

  let lN = 0, lZ = 0, lO = 0, lR = 0, lE = 0;
  for (let i = 0; i < line.length; i += 1)
    if (line[i] === 'e') lE += 1;
    else if (line[i] === 'r') lR += 1;
    else if (line[i] === 'z') lZ += 1;
    else if (line[i] === 'o') lO += 1;
    else lN += 1;

  let min = Math.min(lN, lO, lE);
  let cntOne = min;
  lN -= min; lO -= min; lE -= min;

  let cntZero = Math.min(lZ, lE, lR, lO);
  const answer = [];
  for (let i = 0; i < cntOne; i += 1) answer.push(1);
  if (answer.length === 0) answer.push(0);
  else {
    for (let i = 0; i < cntZero; i += 1) answer.push(0);
  }

  console.log(answer.join(' '));
});

var n = Number(readline());
var str =  readline();
var mas  = [];
for (var i = 0; i < n; i++)
{
	if (str[i] == 'n')
		mas.push(1);
	else if (str[i] == 'z')
		mas.push(0);

}
print(mas.sort(function(a, b){return b - a}));

var charsCount = readline();
var letters = readline();

var countOfLetterZ = (letters.match(/z/g) || []).length;

var zerosCount = countOfLetterZ;
var onesCount = (letters.length / 4) - zerosCount;

var binary = [];

for (var i = 0; i < onesCount; i++) {
  binary.push('1')
}

for (var i = 0; i < zerosCount; i++) {
  binary.push('0')
}

if (parseInt(binary.join('')) === 0)
  write('0')
else
  write(binary.join(' '))

var charsCount = readline();
var letters = readline();

var countOfLetterZ = (letters.match(/z/g) || []).length;

var zerosCount = countOfLetterZ;
var onesCount = (letters.length / 4) - zerosCount;

var binary = [];

for (var i = 0; i < onesCount; i++) {
  binary.push('1')
}

for (var i = 0; i < zerosCount; i++) {
  binary.push('0')
}

write(parseInt(binary.join('')));

var charsCount = readline();
var letters = readline();

var countOfLetterZ = (letters.match(/z/g) || []).length;

var zerosCount = countOfLetterZ;
var onesCount = (letters.length / 4) - zerosCount;

var binary = [];

for (var i = 0; i < onesCount; i++) {
  binary.push('1')
}

for (var i = 0; i < zerosCount; i++) {
  binary.push('0')
}

write(binary.join(' '))

var charsCount = readline();
var letters = readline();

var countOfLetterZ = (letters.match(/z/g) || []).length;

var zerosCount = countOfLetterZ;
var onesCount = (letters.length / 4) - zerosCount;

var binary = [];

for (var i = 0; i < onesCount; i++) {
  binary.push('1')
}

for (var i = 0; i < zerosCount; i++) {
  binary.push('0')
}

write(binary.join(''));

var charsCount = readline();
var letters = readline();
// var letters = 'zerooneone'

var countOfLetterZ = (letters.match(/z/g) || []).length;

var zerosCount = countOfLetterZ;
var onesCount = (letters.length / 4) - zerosCount;

var binary = [];

for (var i = 0; i < onesCount; i++) {
  binary.push('1')
}

for (var i = 0; i < zerosCount; i++) {
  binary.push('0')
}

// console.log(binary)
binary.forEach(function(note) {
  write(note);
})

var charsCount = readline();
var letters = readline();

var countOfLetterZ = (letters.match(/z/g) || []).length;

var zerosCount = countOfLetterZ;
var onesCount = letters.length - zerosCount*4;

var binary = [];

for (var i = 0; i < onesCount; i++) {
  binary.push('1')
}

for (var i = 0; i < zerosCount; i++) {
  binary.push('0')
}

write(binary.join(' '))

var charsCount = readline();
var letters = readline();

var countOfLetterZ = (letters.match(/z/g) || []).length;

var zerosCount = countOfLetterZ;
var onesCount = (letters.length / 4) - zerosCount;

var binary = [];

for (var i = 0; i < onesCount; i++) {
  binary.push('1')
}

for (var i = 0; i < zerosCount; i++) {
  binary.push('0')
}

binary.forEach(function(note) {
  write(note)
});


International Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where y stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string y that has never been used before. Among all such valid abbreviations they choose the shortest one and announce it to be the abbreviation of this year's competition.For example, the first three Olympiads (years 1989, 1990 and 1991, respectively) received the abbreviations IAO'9, IAO'0 and IAO'1, while the competition in 2015 received an abbreviation IAO'15, as IAO'5 has been already used in 1995.You are given a list of abbreviations. For each of them determine the year it stands for.

The first line of the input contains a single integer n (1 ≤ n ≤ 1000) — the number of abbreviations to process.  Then n lines follow, each containing a single abbreviation. It's guaranteed that each abbreviation contains at most nine digits.

For each abbreviation given in the input, find the year of the corresponding Olympiad.

var n = parseInt(readline());
var limits = [undefined, 1989];
for (var i = 2; i <= 10; i++) {
    limits[i] = limits[i-1] + Math.pow(10, i-1);
}
//print(limits);
function getLastDigits(start, noOfDigits) {
    return start.toString().substr(noOfDigits*-1);
}
for(var i = 0; i < n; i++){
    var input = readline().split("'")[1];
    var noOfDigits = input.length;
    //print(noOfDigits, input);
    var diff = parseInt(input) - parseInt(getLastDigits(limits[noOfDigits], noOfDigits));
    if(diff < 0){
        noOfDigits++;
    }
    print(limits[noOfDigits]+diff);
}


A group of tourists is going to kayak and catamaran tour. A rented lorry has arrived to the boat depot to take kayaks and catamarans to the point of departure. It's known that all kayaks are of the same size (and each of them occupies the space of 1 cubic metre), and all catamarans are of the same size, but two times bigger than kayaks (and occupy the space of 2 cubic metres).Each waterborne vehicle has a particular carrying capacity, and it should be noted that waterborne vehicles that look the same can have different carrying capacities. Knowing the truck body volume and the list of waterborne vehicles in the boat depot (for each one its type and carrying capacity are known), find out such set of vehicles that can be taken in the lorry, and that has the maximum total carrying capacity. The truck body volume of the lorry can be used effectively, that is to say you can always put into the lorry a waterborne vehicle that occupies the space not exceeding the free space left in the truck body.

The first line contains a pair of integer numbers n and v (1 ≤ n ≤ 105; 1 ≤ v ≤ 109), where n is the number of waterborne vehicles in the boat depot, and v is the truck body volume of the lorry in cubic metres. The following n lines contain the information about the waterborne vehicles, that is a pair of numbers ti, pi (1 ≤ ti ≤ 2; 1 ≤ pi ≤ 104), where ti is the vehicle type (1 – a kayak, 2 – a catamaran), and pi is its carrying capacity. The waterborne vehicles are enumerated in order of their appearance in the input file.

In the first line print the maximum possible carrying capacity of the set. In the second line print a string consisting of the numbers of the vehicles that make the optimal set. If the answer is not unique, print any of them.

var line = readline().split(' ');
var n = parseInt(line[0]);
var v = parseInt(line[1]);

var k = [];
var c = [];
for(var i=0;i<n;i++){
	line = readline().split(' ');
	( line[0]=='1' ? k : c ).push( {
		i: i+1,
		v: parseInt(line[1])
	} );
}
k.sort(function(a,b){return a.v<b.v?1:-1});
c.sort(function(a,b){return a.v<b.v?1:-1});

var av = 0;
var aa = Math.floor(v/2);
var list = [];
for(var i=1,j=0,co=0; co<aa && (i<k.length || j<c.length); co++){
	var kv=cv=-1;
	if(i<k.length){
		kv = k[i].v + k[i-1].v;
	}
	if(j<c.length){
		cv = c[j].v;
	}

	if( kv > cv){
		av += kv;
		list.push(k[i].i, k[i-1].i);
		i += 2;
	}else{
		av += cv;
		list.push(c[j].i);
		j++;
	}
}

if( v > co*2 && k[i-1]){
	//try{
		if(k[i-2] && c[j] && k[i-2].v + k[i-1].v < c[j].v){
			list [ list.indexOf( k[i-2].i ) ] = '';
			av -= k[i-2].v;

			list.push(c[j].i);
			av += c[j].v;
		}else{
			av += k[i-1].v;
			list.push(k[i-1].i);
		}
	// }catch(e){
	// 	print(i-1]);
	// }

}else if( v > co*2 && k[i-2] && c[j] && k[i-2].v<c[j].v){
	list [ list.indexOf( k[i-2].i ) ] = '';
	av -= k[i-2].v;

	list.push(c[j].i);
	av += c[j].v;
}

print(av);
print(list.join(' '));

readline = readline || ''
write = write || ''
print = print || ''

var line = readline().split(' ')
var nps = +line[0]
var m = +line[1]

var ls = []
var cs = []
for (var i = 0; i < nps; i++) {
  line = readline()
  line = line.split(' ')
  ;(line[0] == 1 ? ls : cs).push([+line[1], i + 1, +line[0]])
}

ls.sort(function (a, b) {return a[0] - b[0]})
cs.sort(function (a, b) {return a[0] - b[0]})

var ncs = Math.min(cs.length, m / 2 | 0)
var lpss = cs.slice(cs.length - ncs)
var nbls = Math.min(m - lpss.length * 2, ls.length)
;[].push.apply(lpss, ls.slice(ls.length - nbls))
ls = ls.slice(0, ls.length - nbls)
if (ls.length) {
  i = -1
  var ps, l1, l2
  while (((ps = lpss[++i]) && ps[2] == 2) && ps[0] <= (l1 = ls.pop() || [0])[0] + (l2 = ls.pop() || [0])[0]) {
    l2[1] ? lpss.splice(i, 1, l1, l2) : lpss.splice(i, 1, l1)
    i++
  }
}
print(lpss.reduce(function (r, ps) {return r + ps[0]}, 0))
print(lpss.map(function (ps) {return ps[1]}).sort(function (a, b) {return a - b}).join(' '))

/**
 * fill truck with max density vehicles first
 */

var input = readline().split(' ');

// number of waterborne vehicles and the truck body volume
var numOfVehicles = parseInt(input[0]);
var truckVolume = parseInt(input[1]);

var vehicles = [];

for (var i = 1; i < numOfVehicles + 1; i++) {
  input = readline().split(' ');

  // type: 1 – kayak, 2 – catamaran
  var type = parseInt(input[0]);
  var capacity = parseInt(input[1]);
  vehicles.push([type, capacity, i, Math.floor(10 * capacity / type)]);
}

// sort vehicles by density (capacity / volume)
vehicles.sort(function(a, b) {
  return b[3] - a[3];
});

var lVeh = [];
var lVol = 0;
var lCap = 0;
var lastKayak = null;

var i = 0;
while (truckVolume > (lVol + 3) && i < vehicles.length) {
  var nextVeh = vehicles[i++];
  lVeh.push(nextVeh[2]);
  lVol += nextVeh[0];
  lCap += nextVeh[1];
  if (nextVeh[0] == 1) {
    lastKayak = nextVeh;
  }
}

if (i < vehicles.length) {
  vehicles = vehicles.slice(i);
} else {
  vehicles = [];
}

// remove the last added kayak and solve as set
if (lastKayak !== null) {
  lVeh.splice(lVeh.indexOf(lastKayak[2]), 1);
  lVol -= lastKayak[0]; // always 1
  lCap -= lastKayak[1];
  vehicles.unshift(lastKayak); // put back into vehicles list
}

var maxCap = lCap;
var maxCapVeh = lVeh.slice();

checkCapacity(lVeh, lVol, lCap, 0);

print(maxCap);
print(maxCapVeh.join(' '));

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

// loaded vehicles, loaded volume, loaded capacity
function checkCapacity(loadedVeh, loadedVol, loadedCap, i) {
  // print('@', loadedVeh, loadedVol, loadedCap, i);
  var type = vehicles[i][0];
  var cap = vehicles[i][1];
  var veh = vehicles[i][2];

  var newLoadedVol = loadedVol + type;
  var newLoadedCap = loadedCap + cap;
  var newLoadedVeh = loadedVeh.slice();
  newLoadedVeh.push(veh);

  if (newLoadedVol <= truckVolume && newLoadedCap > maxCap) {
    maxCap = newLoadedCap;
    maxCapVeh = newLoadedVeh;
  }

  if (i < vehicles.length - 1 && i < 5) {
    // including
    if (newLoadedVol < truckVolume) {
      checkCapacity(newLoadedVeh, newLoadedVol, newLoadedCap, i + 1);
    }

    // not including
    if (loadedVol < truckVolume) {
      checkCapacity(loadedVeh, loadedVol, loadedCap, i + 1);
    }
  }
}

input = readline().split(' ');
n = parseInt(input[0]);
totalVolume = parseInt(input[1]);

bla1 = [];
bla2 = [];

for(i = 0; i<n; i++) {
    input = readline().split(' ');
    volume = parseInt(input[0]);
    boat = {
        id: i+1,
        cap: parseInt(input[1]),
    };
    ((volume === 1) ? bla1 : bla2).push(boat);
}

bla1.sort((b1, b2) => b2.cap - b1.cap);
bla2.sort((b1, b2) => b2.cap - b1.cap);

for(i=1; i<bla1.length; i++) bla1[i].cap += bla1[i-1].cap;
for(i=1; i<bla2.length; i++) bla2[i].cap += bla2[i-1].cap;
bla1.unshift({id: null, cap:0});
bla2.unshift({id: null, cap:0});

best = Number.NEGATIVE_INFINITY;
bestn = null;
for(i=0; i<bla2.length; i++) {
    complement = totalVolume - i*2;
    if (complement < 0) break;
    current = bla2[i].cap + bla1[Math.min(complement,bla1.length-1)].cap;
    //print(`${i} ${complement}: ${current}`);
    if(current > best) best = current, bestn = i;
}

print(best);

numbers = "";
complement = totalVolume - bestn*2;
for(i=1; i<=bestn; i++) numbers += bla2[i].id+' ';
for(i=1; i<=Math.min(complement, bla1.length-1); i++) numbers += bla1[i].id+' ';

print(numbers);

var line = readline().split(' ');
var n = parseInt(line[0]);
var v = parseInt(line[1]);

var k = [];
var c = [];
for(var i=0;i<n;i++){
	line = readline().split(' ');
	( line[0]=='1' ? k : c ).push( {
		i: i+1,
		v: parseInt(line[1])
	} );
}
k.sort(function(a,b){return a.v<b.v});
c.sort(function(a,b){return a.v<b.v});

var av = 0;
var aa = Math.floor(v/2);
var list = [];
for(var i=1,j=0,co=0; co<aa && (i<k.length || j<c.length); co++){
	var kv=cv=-1;
	if(i<k.length){
		kv = k[i].v + k[i-1].v;
	}
	if(j<c.length){
		cv = c[j].v;
	}

	if( kv > cv){
		av += kv;
		list.push(k[i].i, k[i-1].i);
		i += 2;
	}else{
		av += cv;
		list.push(c[j].i);
		j++;
	}
}
if( v > co*2 && k[i-1]){
	av += k[i-1].v;
	list.push(k[i-1].i);
}else if( v > co*2 && k[i-2] && c[j] && k[i-2].v<c[j].v){
	list [ list.indexOf( k[i-2].i ) ] = '';
	av -= k[i-2].v;

	list.push(c[j].i);
	av += c[j].v;
}

print(av);
print(list.join(' '));

var line = readline().split(' ');
var n = parseInt(line[0]);
var v = parseInt(line[1]);

var k = [];
var c = [];
for(var i=0;i<n;i++){
	line = readline().split(' ');
	( line[0]=='1' ? k : c ).push( {
		i: i+1,
		v: parseInt(line[1])
	} );
}
k.sort(function(a,b){return a.v<b.v});
c.sort(function(a,b){return a.v<b.v});

var av = 0;
var aa = Math.floor(v/2);
var list = [];
for(var i=1,j=0,co=0; co<aa && (i<k.length || j<c.length); co++){
	var kv=cv=-1;
	if(i<k.length){
		kv = k[i].v + k[i-1].v;
	}
	if(j<c.length){
		cv = c[j].v;
	}

	if( kv > cv){
		av += kv;
		list.push(k[i].i, k[i-1].i);
		i += 2;
	}else{
		av += cv;
		list.push(c[j].i);
		j++;
	}
}
if( v > co*2 && k[i-1]){
	av += k[i-1].v;
	list.push(k[i-1].i);
}

if( v > co*2 && k[i-2] && c[j] && k[i-2].v<c[j].v){
	list [ list.indexOf( k[i-2].i ) ] = '';
	av -= k[i-2].v;

	list.push(c[j].i);
	av += c[j].v;
}

print(av);
print(list.join(' '));

var line = readline().split(' ');
var n = parseInt(line[0]);
var v = parseInt(line[1]);

var k = [];
var c = [];
for(var i=0;i<n;i++){
	line = readline().split(' ');
	( line[0]=='1' ? k : c ).push( {
		i: i+1,
		v: parseInt(line[1])
	} );
}
k.sort(function(a,b){return a.v<b.v?1:-1});
c.sort(function(a,b){return a.v<b.v?1:-1});

var av = 0;
var aa = Math.floor(v/2);
var list = [];
for(var i=1,j=0,co=0; co<aa && (i<k.length || j<c.length); co++){
	var kv=cv=-1;
	if(i<k.length){
		kv = k[i].v + k[i-1].v;
	}
	if(j<c.length){
		cv = c[j].v;
	}

	if( kv > cv){
		av += kv;
		list.push(k[i].i, k[i-1].i);
		i += 2;
	}else{
		av += cv;
		list.push(c[j].i);
		j++;
	}
}

if( v > co*2 && k[i-1]){
	try{
		if(k[i-2] && k[i-2].v+k[i-1].v<c[j].v){
			list [ list.indexOf( k[i-2].i ) ] = '';
			av -= k[i-2].v;

			list.push(c[j].i);
			av += c[j].v;
		}else{
			av += k[i-1].v;
			list.push(k[i-1].i);
		}
	}catch(e){
		print(k[i-1]);
	}

}else if( v > co*2 && k[i-2] && c[j] && k[i-2].v<c[j].v){
	list [ list.indexOf( k[i-2].i ) ] = '';
	av -= k[i-2].v;

	list.push(c[j].i);
	av += c[j].v;
}

print(av);
print(list.join(' '));

var line = readline().split(' ');
var n = parseInt(line[0]);
var v = parseInt(line[1]);

var k = [];
var c = [];
for(var i=0;i<n;i++){
	line = readline().split(' ');
	( line[0]=='1' ? k : c ).push( {
		i: i+1,
		v: parseInt(line[1])
	} );
}
k.sort(function(a,b){return a.v<b.v});
c.sort(function(a,b){return a.v<b.v});

var av = 0;
var aa = Math.floor(v/2);
var list = [];
for(var i=1,j=0,co=0; co<aa && (i<k.length || j<c.length); co++){
	var kv=cv=-1;
	if(i<k.length){
		kv = k[i].v + k[i-1].v;
	}
	if(j<c.length){
		cv = c[j].v;
	}

	if( kv > cv){
		av += kv;
		list.push(k[i].i, k[i-1].i);
		i += 2;
	}else{
		av += cv;
		list.push(c[j].i);
		j++;
	}
}

if( v > co*2 && k[--i]){
	av += k[i].v;
	list.push(k[i].i);
}
print(av);
print(list.join(' '));

var line = readline().split(' ');
var n = parseInt(line[0]);
var v = parseInt(line[1]);

var k = [];
var c = [];
for(var i=0;i<n;i++){
	line = readline().split(' ');
	( line[0]=='1' ? k : c ).push( {
		i: i,
		v: parseInt(line[1])
	} );
}
k.sort(function(a,b){return a.v<b.v});
c.sort(function(a,b){return a.v<b.v});

var av = 0;
var aa = Math.floor(v/2);
var list = [];
for(var i=1,j=0,co=0; co<aa && (i<k.length || j<c.length); co++){
	var kv=cv=-1;
	if(i<k.length){
		kv = k[i].v + k[i-1].v;
	}
	if(j<c.length){
		cv = c[j].v;
	}

	if( kv > cv){
		av += kv;
		list.push(k[i].i, k[i-1].i);
		i += 2;
	}else{
		av += cv;
		list.push(c[j].i);
		j++;
	}
}

if( v > co*2 && k[--i]){
	av += k[i].v;
	list.push(k[i].i);
}
print(av);
print(list.join(' '));

var line = readline().split(' ');
var n = parseInt(line[0]);
var v = parseInt(line[1]);

var k = [];
var c = [];
for(var i=0;i<n;i++){
	line = readline().split(' ');
	( line[0]=='1' ? k : c ).push( {
		i: i+1,
		v: parseInt(line[1])
	} );
}
k.sort(function(a,b){return a.v<b.v?1:-1});
c.sort(function(a,b){return a.v<b.v?1:-1});

var av = 0;
var aa = Math.floor(v/2);
var list = [];
for(var i=1,j=0,co=0; co<aa && (i<k.length || j<c.length); co++){
	var kv=cv=-1;
	if(i<k.length){
		kv = k[i].v + k[i-1].v;
	}
	if(j<c.length){
		cv = c[j].v;
	}

	if( kv > cv){
		av += kv;
		list.push(k[i].i, k[i-1].i);
		i += 2;
	}else{
		av += cv;
		list.push(c[j].i);
		j++;
	}
}

if( v > co*2 && k[i-1]){
	try{
		if(k[i-2] && k[i-2].v + (k[i-1].v)<c[j].v){
			list [ list.indexOf( k[i-2].i ) ] = '';
			av -= k[i-2].v;

			list.push(c[j].i);
			av += c[j].v;
		}else{
			av += k[i-1].v;
			list.push(k[i-1].i);
		}
	}catch(e){
		print(k[i-1]);
	}

}else if( v > co*2 && k[i-2] && c[j] && k[i-2].v<c[j].v){
	list [ list.indexOf( k[i-2].i ) ] = '';
	av -= k[i-2].v;

	list.push(c[j].i);
	av += c[j].v;
}

print(av);
print(list.join(' '));

var line = readline().split(' ');
var n = parseInt(line[0]);
var v = parseInt(line[1]);

var k = [];
var c = [];
for(var i=0;i<n;i++){
	line = readline().split(' ');
	( line[0]=='1' ? k : c ).push( {
		i: i+1,
		v: parseInt(line[1])
	} );
}
k.sort(function(a,b){return a.v<b.v?1:-1});
c.sort(function(a,b){return a.v<b.v?1:-1});

var av = 0;
var aa = Math.floor(v/2);
var list = [];
for(var i=1,j=0,co=0; co<aa && (i<k.length || j<c.length); co++){
	var kv=cv=-1;
	if(i<k.length){
		kv = k[i].v + k[i-1].v;
	}
	if(j<c.length){
		cv = c[j].v;
	}

	if( kv > cv){
		av += kv;
		list.push(k[i].i, k[i-1].i);
		i += 2;
	}else{
		av += cv;
		list.push(c[j].i);
		j++;
	}
}

if( v > co*2 && k[i-1]){
	try{
		if(k[i-2] && k[i-2].v+k[i-1].v<c[j].v){
			list [ list.indexOf( k[i-2].i ) ] = '';
			av -= k[i-2].v;

			list.push(c[j].i);
			av += c[j].v;
		}else{
			av += k[i-1].v;
			list.push(k[i-1].i);
		}
	}catch(e){
		print(i-1);
	}

}else if( v > co*2 && k[i-2] && c[j] && k[i-2].v<c[j].v){
	list [ list.indexOf( k[i-2].i ) ] = '';
	av -= k[i-2].v;

	list.push(c[j].i);
	av += c[j].v;
}

print(av);
print(list.join(' '));

readline = readline || ''
write = write || ''
print = print || ''

var line = readline().split(' ')
var nps = +line[0]
var m = +line[1]

var ls = []
var cs = []
for (var i = 0; i < nps; i++) {
  line = readline()
  line = line.split(' ')
  ;(line[0] == 1 ? ls : cs).push([+line[1], i + 1, +line[0]])
}

ls.sort(function (a, b) {return a[0] - b[0]})
cs.sort(function (a, b) {return a[0] - b[0]})

var ncs = Math.min(cs.length, m / 2 | 0)
var lpss = cs.slice(cs.length - ncs)
var nbls = Math.min(m - lpss.length * 2, ls.length)
;[].push.apply(lpss, ls.slice(ls.length - nbls))
ls = ls.slice(0, ls.length - nbls)
if (ls.length) {
  i = -1
  var ps, l1, l2
  while (((ps = lpss[++i]) && ps[2] == 2) && ps[0] < (l1 = ls.pop() || [0])[0] + (l2 = ls.pop() || [0])[0]) {
    l2[1] ? lpss.splice(i, 1, l1, l2) : lpss.splice(i, 1, l1)
  }
}
print(lpss.reduce(function (r, ps) {return r + ps[0]}, 0))
print(lpss.map(function (ps) {return ps[1]}).sort().join(' '))

readline = readline || ''
write = write || ''
print = print || ''

var line = readline().split(' ')
var nps = +line[0]
var m = +line[1]

var pss = []
for (var i = 0; i < nps; i++) {
  line = readline()
  line = line.split(' ')
  pss.push([line[1] / line[0], +line[1], +line[0], i + 1])
}

pss.sort(function (a, b) {
  return a[0] - b[0]
})

var bpss = []
var gp = 0
while (m > 2) {
  var bps = pss.pop()
  if (!bps) break
  bpss.push([bps[3]])
  m -= bps[2]
  gp += bps[1]
}

if (m == 1 && pss.length) {
  while ((bps = pss.pop()) && bps[2] != 1) {}
  if (bps) {
    bpss.push([bps[3]])
    gp += bps[1]
  }
} else if (m == 2 && pss.length) {
  var tl = []
  var c
  while ((bps = pss.pop()) && !(tl.length == 2 && c)) {
    if (bps[2] == 2) {c = bps}
    else {tl.push(bps)}
  }
  if (!c) {
    [].push.apply(bpss, tl.map(function (l) {return l[3]}))
    gp += (tl[0] ? tl[0][1] : 0) + (tl[1] ? tl[1][1] : 0)
  } else if (c || !tl.length) {
    bpss.push(c[3])
    gp += c[1]
  } else if (c && tl.length == 1) {
    var ps = c[1] >= tl[0][1] ? c : tl[0]
    bpss.push(ps[3])
    gp += ps[1]
  } else {
    ps = c[1] >= tl[0][1] + tl[1][1] ? [c] : tl
    ;[].push.apply(bpss, ps.map(function (s) {return s[3]}))
    gp += ps.reduce(function (r, s) {return r + s[3]}, 0)
  }
}

print(gp)
print(bpss.sort(function (a, b) {return a - b}).join('\n'))

readline = readline || ''
write = write || ''
print = print || ''

var line = readline().split(' ')
var nps = +line[0]
var m = +line[1]

var pss = []
for (var i = 0; i < nps; i++) {
  line = readline()
  line = line.split(' ')
  pss.push([line[1] / line[0], +line[1], +line[0], i + 1])
}

pss.sort(function (a, b) {
  return a[0] - b[0]
})

var bpss = []
var gp = 0
while (m > 2) {
  var bps = pss.pop()
  if (!bps) break
  bpss.push([bps[3]])
  m -= bps[2]
  gp += bps[1]
}

if (m == 1 && pss.length) {
  while ((bps = pss.pop()) && bps[2] != 1) {}
  if (bps) {
    bpss.push([bps[3]])
    gp += bps[1]
  }
} else if (m == 2 && pss.length) {
  var tl = []
  var c
  while ((bps = pss.pop()) && !(tl.length == 2 && c)) {
    if (bps[2] == 2) {c = bps}
    else {tl.push(bps)}
  }
  if (!c) {
    [].push.apply(bpss, tl.map(function (l) {return l[3]}))
    gp += (tl[0] ? tl[0][1] : 0) + (tl[1] ? tl[1][1] : 0)
  } else if (c && !tl.length) {
    bpss.push(c[3])
    gp += c[1]
  } else if (c && tl.length == 1) {
    var ps = c[1] >= tl[0][1] ? c : tl[0]
    bpss.push(ps[3])
    gp += ps[1]
  } else {
    ps = c[1] >= tl[0][1] + tl[1][1] ? [c] : tl
    ;[].push.apply(bpss, ps.map(function (s) {return s[3]}))
    gp += ps.reduce(function (r, s) {return r + s[1]}, 0)
  }
}

print(gp)
print(bpss.join(' '))

var n,v;
var boat=[];
function main()
{
	var i;
	tmp=readline().split(" ");
	n=Number(tmp[0]);v=Number(tmp[1]);
	for(i=1;i<=n;i++)
	{
		boat[i-1]=readline().split(" ");
		boat[i-1][0]=parseInt(boat[i-1][0]);
		boat[i-1][1]=parseInt(boat[i-1][1]);
		boat[i-1][2]=parseInt(i);
	}
	boat.sort(function cmp(a,b)
			{
				if(a[0]==b[0]) return b[1]-a[1];
				else
					if(a[0]>b[0]) return 2*b[1]-a[1];
					else return b[1]-2*a[1];
				return 0;
			}
	)
	var ans=0;
	var xh=[];
	for(i=0;i<=n-1;i++)
		if(v>=boat[i][0]) {v-=boat[i][0];ans+=boat[i][1];xh.push(boat[i][2]);}
	print(ans);
	print(xh.join(" "));
}
main();

/**
 * fill truck with max density vehicles first
 */

var input = readline().split(' ');

// number of waterborne vehicles and the truck body volume
var numOfVehicles = parseInt(input[0]);
var truckVolume = parseInt(input[1]);

var vehicles = [];

for (var i = 1; i < numOfVehicles + 1; i++) {
  input = readline().split(' ');

  // type: 1 – kayak, 2 – catamaran
  var type = parseInt(input[0]);
  var capacity = parseInt(input[1]);
  vehicles.push([type, capacity, i, Math.floor(10 * capacity / type)]);
}

// sort vehicles by density (capacity / volume)
vehicles.sort(function(a, b) {
  return b[3] - a[3];
});

var lVeh = [];
var lVol = 0;
var lCap = 0;
var lastKayak = null;

var i = 0;
while (truckVolume > (lVol + 3) && i < vehicles.length) {
  var nextVeh = vehicles[i++];
  lVeh.push(nextVeh[2]);
  lVol += nextVeh[0];
  lCap += nextVeh[1];
  if (nextVeh[0] == 1) {
    lastKayak = nextVeh;
  }
}

if (i < vehicles.length) {
  vehicles = vehicles.slice(i);
} else {
  vehicles = [];
}

if (numOfVehicles == 84659) {
  print('ce')
}

// remove the last added kayak and solve as set
if (lastKayak !== null) {
  lVeh.splice(lVeh.indexOf(lastKayak[2]), 1);
  lVol -= lastKayak[0]; // always 1
  lCap -= lastKayak[1];
  vehicles.unshift(lastKayak); // put back into vehicles list
}

var maxCap = lCap;
var maxCapVeh = lVeh.slice();

if (numOfVehicles == 84659) {
  print('d4')
}

checkCapacity(lVeh, lVol, lCap, 0);

if (numOfVehicles == 84659) {
  print('d4')
}

print(maxCap);
print(maxCapVeh.join(' '));

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

// loaded vehicles, loaded volume, loaded capacity
function checkCapacity(loadedVeh, loadedVol, loadedCap, i) {
  // print('@', loadedVeh, loadedVol, loadedCap, i);
  var type = vehicles[i][0];
  var cap = vehicles[i][1];
  var veh = vehicles[i][2];

  var newLoadedVol = loadedVol + type;
  var newLoadedCap = loadedCap + cap;
  var newLoadedVeh = loadedVeh.slice();
  newLoadedVeh.push(veh);

  if (newLoadedVol <= truckVolume && newLoadedCap > maxCap) {
    maxCap = newLoadedCap;
    maxCapVeh = newLoadedVeh;
  }

  if (i < vehicles.length - 1 && i < 5) {
    // including
    if (newLoadedVol < truckVolume) {
      checkCapacity(newLoadedVeh, newLoadedVol, newLoadedCap, i + 1);
    }

    // not including
    if (loadedVol < truckVolume) {
      checkCapacity(loadedVeh, loadedVol, loadedCap, i + 1);
    }
  }
}

var input = readline().split(' ');

// number of waterborne vehicles and the truck body volume
var numOfVehicles = parseInt(input[0]);
var truckVolume = parseInt(input[1]);

// map capacity to count
var catamarans = {};
var kayaks = {};

for (var i = 0; i < numOfVehicles; i++) {
  input = readline().split(' ');

  var capacity = input[1];
  var type = input[0];

  // type: 1 – kayak, 2 – catamaran
  if (type == '1') {
    kayaks[capacity] = kayaks[capacity] || 0;
    kayaks[capacity]++;
  } else {
    catamarans[capacity] = catamarans[capacity] || 0;
    catamarans[capacity]++;
  }
}

var catamaranCaps = sortDesc(catamarans); // ints
var kayakCaps = sortDesc(kayaks);

// add to truck until full
var loadedVolume = 0;
var carryingCap = 0;
// var numOfLoadedVehicles = 0;
var loadedVehicles = [];

while (loadedVolume < truckVolume && catamaranCaps.length > 0 && kayakCaps.length > 0) {
  var catamaranCap = catamaranCaps[0] || 0;
  var kayakCap = kayakCaps[0] || 0;

  if (truckVolume - loadedVolume > 1) {
    if (catamaranCap / 2 >= kayakCap && catamaranCap > 0) { // density
      loadedVolume += 2;
      carryingCap += catamaranCap;
      removeVehicle(catamarans, catamaranCaps, catamaranCap);
      // numOfLoadedVehicles++;
      loadedVehicles.push(2);
    } else if (kayakCap > 0) {
      loadedVolume += 1;
      carryingCap += kayakCap;
      removeVehicle(kayaks, kayakCaps, kayakCap);
      // numOfLoadedVehicles++;
      loadedVehicles.push(1);
    } else {
      // nothing to load
      print('weird');
      break;
    }
  } else if (kayakCap > 0) {
    // load one more kayak
    loadedVolume += 1;
    carryingCap += kayakCap;
    removeVehicle(kayaks, kayakCaps, kayakCap);
    // numOfLoadedVehicles++;
    loadedVehicles.push(1);
  } else {
    // can't load another catamaran
    break;
  }
}

print(carryingCap);
// print(numOfLoadedVehicles);
print(loadedVehicles);

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

function sortDesc(input) {
  return Object.keys(input).map(function(e) {
    return parseInt(e);
  }).sort(function(a, b) {
    return b - a
  });
}

function removeVehicle(vehicles, caps, cap) {
  var key = cap.toString();
  vehicles[key]--;
  if (vehicles[key] == 0) {
    delete vehicles[key];
    caps.splice(0, 1);
  }
}

var input = readline().split(' ');

// number of waterborne vehicles and the truck body volume
var numOfVehicles = parseInt(input[0]);
var truckVolume = parseInt(input[1]);

// map capacity to count
var catamarans = {};
var kayaks = {};

for (var i = 0; i < numOfVehicles; i++) {
  input = readline().split(' ');

  var capacity = input[1];
  var type = input[0];

  // type: 1 – kayak, 2 – catamaran
  if (type == '1') {
    kayaks[capacity] = kayaks[capacity] || 0;
    kayaks[capacity]++;
  } else {
    catamarans[capacity] = catamarans[capacity] || 0;
    catamarans[capacity]++;
  }
}

var catamaranCaps = sortDesc(catamarans); // ints
var kayakCaps = sortDesc(kayaks);

// add to truck until full
var loadedVolume = 0;
var carryingCap = 0;
var numOfLoadedVehicles = 0;

while (loadedVolume < truckVolume && catamaranCaps.length > 0 && kayakCaps.length > 0) {
  var catamaranCap = catamaranCaps[0] || 0;
  var kayakCap = kayakCaps[0] || 0;

  if (truckVolume - loadedVolume > 1) {
    if (catamaranCap / 2 >= kayakCap && catamaranCap > 0) { // density
      loadedVolume += 2;
      carryingCap += catamaranCap;
      removeVehicle(catamarans, catamaranCaps, catamaranCap);
      numOfLoadedVehicles++;
    } else if (kayakCap > 0) {
      loadedVolume += 1;
      carryingCap += kayakCap;
      removeVehicle(kayaks, kayakCaps, kayakCap);
      numOfLoadedVehicles++;
    } else {
      // nothing to load
      print('weird');
      break;
    }
  } else if (kayakCap > 0) {
    // load one more kayak
    loadedVolume += 1;
    carryingCap += kayakCap;
    removeVehicle(kayaks, kayakCaps, kayakCap);
  } else {
    // can't load another catamaran
    break;
  }
}

print(carryingCap);
print(numOfLoadedVehicles);

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

function sortDesc(input) {
  return Object.keys(input).map(function(e) {
    return parseInt(e);
  }).sort(function(a, b) {
    return b - a
  });
}

function removeVehicle(vehicles, caps, cap) {
  var key = cap.toString();
  vehicles[key]--;
  if (vehicles[key] == 0) {
    delete vehicles[key];
    caps.splice(0, 1);
  }
}

var input = readline().split(' ');

// number of waterborne vehicles and the truck body volume
var numOfVehicles = parseInt(input[0]);
var truckVolume = parseInt(input[1]);

// map capacity to count
var catamarans = {};
var kayaks = {};

for (var i = 1; i < numOfVehicles + 1; i++) {
  input = readline().split(' ');

  var capacity = input[1];
  var type = input[0];

  // type: 1 – kayak, 2 – catamaran
  if (type == '1') {
    kayaks[capacity] = kayaks[capacity] || [];
    kayaks[capacity].push(i);
  } else {
    catamarans[capacity] = catamarans[capacity] || [];
    catamarans[capacity].push(i);
  }
}

var catamaranCaps = sortDesc(catamarans); // ints
var kayakCaps = sortDesc(kayaks);

// add to truck until full
var loadedVolume = 0;
var carryingCap = 0;
var loadedVehicles = [];

while (loadedVolume < truckVolume && catamaranCaps.length > 0 && kayakCaps.length > 0) {
  var catamaranCap = catamaranCaps[0] || 0;
  var kayakCap = kayakCaps[0] || 0;

  if (truckVolume - loadedVolume > 1) {
    if (catamaranCap / 2 >= kayakCap && catamaranCap > 0) { // density
      loadedVolume += 2;
      carryingCap += catamaranCap;
      loadedVehicles.push(removeVehicle(catamarans, catamaranCaps, catamaranCap));
    } else if (kayakCap > 0) {
      loadedVolume += 1;
      carryingCap += kayakCap;
      loadedVehicles.push(removeVehicle(kayaks, kayakCaps, kayakCap));
    }
  } else if (kayakCap > 0) {
    // load one more kayak
    loadedVolume += 1;
    carryingCap += kayakCap;
    loadedVehicles.push(removeVehicle(kayaks, kayakCaps, kayakCap));
  } else {
    // can't load another catamaran
    break;
  }
}

print(carryingCap);
// print(numOfLoadedVehicles);
print(loadedVehicles.join(' '));

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

function sortDesc(input) {
  return Object.keys(input).map(function(e) {
    return parseInt(e);
  }).sort(function(a, b) {
    return b - a
  });
}

function removeVehicle(vehicles, caps, cap) {
  var key = cap.toString();
  var removed = vehicles[key].splice(0, 1);
  if (vehicles[key].length == 0) {
    delete vehicles[key];
    caps.splice(0, 1);
  }
  return removed[0];
}

/**
 * fill truck with max density vehicles first
 */

var input = readline().split(' ');

// number of waterborne vehicles and the truck body volume
var numOfVehicles = parseInt(input[0]);
var truckVolume = parseInt(input[1]);

var vehicles = [];

for (var i = 1; i < numOfVehicles + 1; i++) {
  input = readline().split(' ');

  // type: 1 – kayak, 2 – catamaran
  var type = parseInt(input[0]);
  var capacity = parseInt(input[1]);
  vehicles.push([type, capacity, i, Math.floor(10 * capacity / type)]);
}

// sort vehicles by density (capacity / volume)
vehicles.sort(function(a, b) {
  return b[3] - a[3];
});

var lVeh = [];
var lVol = 0;
var lCap = 0;
var lastKayak = null;

while (truckVolume > (lVol + 3) && vehicles.length > 0) {
  var nextVeh = vehicles[0];
  lVeh.push(nextVeh[2]);
  lVol += nextVeh[0];
  lCap += nextVeh[1];
  vehicles.splice(0, 1);
  if (nextVeh[0] == 1) {
    lastKayak = nextVeh;
  }
}

// remove the last added kayak and solve as set
if (lastKayak !== null) {
  lVeh.splice(lVeh.indexOf(lastKayak[2]), 1);
  lVol -= lastKayak[0]; // always 1
  lCap -= lastKayak[1];
  vehicles.unshift(lastKayak); // put back into vehicles list
}

if (numOfVehicles == 5000) {
  print('c3')
}

var maxCap = lCap;
var maxCapVeh = lVeh.slice();

checkCapacity(lVeh, lVol, lCap, 0);

if (numOfVehicles == 5000) {
  print('d4')
}

print(maxCap);
print(maxCapVeh.join(' '));

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

// loaded vehicles, loaded volume, loaded capacity
function checkCapacity(loadedVeh, loadedVol, loadedCap, i) {
  // print('@', loadedVeh, loadedVol, loadedCap, i);
  var type = vehicles[i][0];
  var cap = vehicles[i][1];
  var veh = vehicles[i][2];

  var newLoadedVol = loadedVol + type;
  var newLoadedCap = loadedCap + cap;
  var newLoadedVeh = loadedVeh.slice();
  newLoadedVeh.push(veh);

  if (newLoadedVol <= truckVolume && newLoadedCap > maxCap) {
    maxCap = newLoadedCap;
    maxCapVeh = newLoadedVeh;
  }

  if (i < vehicles.length - 1 && i < 10) {
    // including
    if (newLoadedVol < truckVolume) {
      checkCapacity(newLoadedVeh, newLoadedVol, newLoadedCap, i + 1);
    }

    // not including
    if (loadedVol < truckVolume) {
      checkCapacity(loadedVeh, loadedVol, loadedCap, i + 1);
    }
  }
}

/**
 * fill truck with max density vehicles first
 */

var input = readline().split(' ');

// number of waterborne vehicles and the truck body volume
var numOfVehicles = parseInt(input[0]);
var truckVolume = parseInt(input[1]);

var vehicles = [];

for (var i = 1; i < numOfVehicles + 1; i++) {
  input = readline().split(' ');

  // type: 1 – kayak, 2 – catamaran
  var type = parseInt(input[0]);
  var capacity = parseInt(input[1]);
  vehicles.push([type, capacity, i]);
}

// sort vehicles by density (capacity / volume)
vehicles.sort(function(a, b) {
  var densityA = a[1] / a[0];
  var densityB = b[1] / b[0];
  return densityB - densityA;
});

var lVeh = [];
var lVol = 0;
var lCap = 0;

while (truckVolume > (lVol + 5) && vehicles.length > 0) {
  var nextVeh = vehicles[0];
  lVeh.push(nextVeh[2]);
  lVol += nextVeh[0];
  lCap += nextVeh[1];
  vehicles.splice(0, 1);
}

// try filling with different combinations of vehicles for max
var maxCap = lCap;
var maxCapVeh = lVeh.slice();

checkCapacity(lVeh, lVol, lCap, 0);

print(maxCap);
print(maxCapVeh.join(' '));

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

// loaded vehicles, loaded volume, loaded capacity
function checkCapacity(loadedVeh, loadedVol, loadedCap, i) {
  // print('@', loadedVeh, loadedVol, loadedCap, i);
  var type = vehicles[i][0];
  var cap = vehicles[i][1];
  var veh = vehicles[i][2];

  var newLoadedVol = loadedVol + type;
  var newLoadedCap = loadedCap + cap;
  var newLoadedVeh = loadedVeh.slice();
  newLoadedVeh.push(veh);

  if (newLoadedVol <= truckVolume && newLoadedCap > maxCap) {
    maxCap = newLoadedCap;
    maxCapVeh = newLoadedVeh;
  }

  if (i < vehicles.length - 1) {
    // including
    if (newLoadedVol < truckVolume) {
      checkCapacity(newLoadedVeh, newLoadedVol, newLoadedCap, i + 1);
    }

    // not including
    if (loadedVol < truckVolume) {
      checkCapacity(loadedVeh, loadedVol, loadedCap, i + 1);
    }
  }
}


You are given a rectangular matrix of size $$$n \times m$$$ consisting of integers from $$$1$$$ to $$$2 \cdot 10^5$$$.In one move, you can:  choose any element of the matrix and change its value to any integer between $$$1$$$ and $$$n \cdot m$$$, inclusive;  take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some $$$j$$$ ($$$1 \le j \le m$$$) and set $$$a_{1, j} := a_{2, j}, a_{2, j} := a_{3, j}, \dots, a_{n, j} := a_{1, j}$$$ simultaneously.  Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this:  In other words, the goal is to obtain the matrix, where $$$a_{1, 1} = 1, a_{1, 2} = 2, \dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \dots, a_{n, m} = n \cdot m$$$ (i.e. $$$a_{i, j} = (i - 1) \cdot m + j$$$) with the minimum number of moves performed.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5, n \cdot m \le 2 \cdot 10^5$$$) — the size of the matrix. The next $$$n$$$ lines contain $$$m$$$ integers each. The number at the line $$$i$$$ and position $$$j$$$ is $$$a_{i, j}$$$ ($$$1 \le a_{i, j} \le 2 \cdot 10^5$$$).

Print one integer — the minimum number of moves required to obtain the matrix, where $$$a_{1, 1} = 1, a_{1, 2} = 2, \dots, a_{1, m} = m, a_{2, 1} = m + 1, a_{2, 2} = m + 2, \dots, a_{n, m} = n \cdot m$$$ ($$$a_{i, j} = (i - 1)m + j$$$).

NoteIn the first example, you can set $$$a_{1, 1} := 7, a_{1, 2} := 8$$$ and $$$a_{1, 3} := 9$$$ then shift the first, the second and the third columns cyclically, so the answer is $$$6$$$. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is $$$0$$$.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is $$$2$$$.

'use strict'

const nm = readline().split(' ').map(i => +i);
const n = nm[0];
const m = nm[1];
const l = n * m;

const t = Array.from({ length: m }, () => []);
for (let i = 0; i < n; i++) readline().split(' ').forEach((v, j) => t[j][i] = (x => (x >= l || x % m) ? -1 : (x / m))(+v - j - 1));

const test = (r, n) => {
    const p = Array.from({ length: n }, (_, i) => n + i);
    r.forEach((i, j) => i >= 0 && p[(j - i + n) % n]--);
    return Math.min(...p);
}

print(t.reduce((r, i) => r + test(i, n), 0));


There are n incoming messages for Vasya. The i-th message is going to be received after ti minutes. Each message has a cost, which equals to A initially. After being received, the cost of a message decreases by B each minute (it can become negative). Vasya can read any message after receiving it at any moment of time. After reading the message, Vasya's bank account receives the current cost of this message. Initially, Vasya's bank account is at 0.Also, each minute Vasya's bank account receives C·k, where k is the amount of received but unread messages.Vasya's messages are very important to him, and because of that he wants to have all messages read after T minutes.Determine the maximum amount of money Vasya's bank account can hold after T minutes.

The first line contains five integers n, A, B, C and T (1 ≤ n, A, B, C, T ≤ 1000). The second string contains n integers ti (1 ≤ ti ≤ T).

Output one integer  — the answer to the problem.

NoteIn the first sample the messages must be read immediately after receiving, Vasya receives A points for each message, n·A = 20 in total.In the second sample the messages can be read at any integer moment.In the third sample messages must be read at the moment T. This way Vasya has 1, 2, 3, 4 and 0 unread messages at the corresponding minutes, he gets 40 points for them. When reading messages, he receives (5 - 4·3) + (5 - 3·3) + (5 - 2·3) + (5 - 1·3) + 5 =  - 5 points. This is 35 in total.

var s = readline().split(" ");
var sum = 0;

var inputArray = readline().split(" "),
  n = parseInt(s[0]),
  a = parseInt(s[1]),
  b = parseInt(s[2]),
  c = parseInt(s[3]),
  t = parseInt(s[4]);

if (c <= b)
  print(a * n);
else {
  for (var i = 0; i < inputArray.length; i++) {
    sum += (c - b) * (t - parseInt(inputArray[i])) + a;
  }
  print(sum);
}

var s = readline().split(" ")
var inputArray = readline().split(" ")
n = parseInt(s[0]), a = parseInt(s[1]), b = parseInt(s[2]), c =parseInt( s[3]),
  t = parseInt(s[4])
if (c <= b)
  print(a * n)
else {
  var sum = 0
  for (var i = 0; i < inputArray.length; i++) {
    sum += (c - b) * (t - parseInt(inputArray[i]))+a
  }
  print(sum)
}

var num = readline().split(" ").map(function(x) { return parseInt(x); });
var n=num[0];
var A=num[1];
var B=num[2];
var C=num[3];
var T=num[4];
var Tis = readline().split(" ").map(function(x) { return parseInt(x); });
var read=B>C;
var money=0;
for(var i=0;i<Tis.length;i++){
    var tm=Tis[i];
    money+=A;
    if(!read){
        money+=(T-tm)*(C-B);
    }
}
write(money);

const s = readline().split(" "),
  sum = 0

const inputArray = readline().split(" "),
  n = parseInt(s[0]),
  a = parseInt(s[1]),
  b = parseInt(s[2]),
  c = parseInt(s[3]),
  t = parseInt(s[4])

if (c <= b)
  print(a * n)
else {
  for (var i = 0; i < inputArray.length; i++) {
    sum += (c - b) * (t - parseInt(inputArray[i])) + a
  }
  print(sum)
}

var i = readline(),
  s = Math.floor(i / 2) + 1
print(s)

var i = readline();
var s = Math.floor(i / 2) + 1;
print(s);

var s = readline().split(" ")
var inputArray = readline().split(" ")
n = s[0], a = s[1], b = s[2], c = s[3], t = s[4]
if (c <= b)
  print(a * n)
else {
  var sum = 0
  for (var i = 0; i < s.length; i++) {
    sum += (c - b) * (t - inputArray[i])
  }
}
print(sum)

var s = readline().split(" ")
var inputArray = readline().split(" ")
n = parseInt(s[0]), a = parseInt(s[1]), b = parseInt(s[2]), c =parseInt( s[3]),
t = parseInt(s[4])
if (c <= b)
  print(a * n)
else {
  var sum = 0
  for (var i = 0; i < s.length; i++) {
    sum += (c - b) * (t - parseInt(inputArray[i]))+a
  }

print(sum)
}

var s = readline().split(" ")
var inputArray = readline().split(" ")
n = parseInt(s[0]), a = parseInt(s[1]), b = parseInt(s[2]), c =parseInt( s[3]),
t = parseInt(s[4])
if (c <= b)
  print(a * n)
else {
  var sum = 0
  for (var i = 0; i < s.length; i++) {
    sum += (c - b) * (t - inputArray[i])+a
  }

print(sum)
}

var s = readline().split(" ")
var inputArray = readline().split(" ")
n = s[0], a = s[1], b = s[2], c = s[3], t = s[4]
if (c <= b)
  print(a * n)
else {
  var sum = 0
  for (var i = 0; i < s.length; i++) {
    sum += (c - b) * (t - inputArray[i])
  }

print(sum)
}

var s = readline().split(" ")
var inputArray = readline().split(" ")
n = s[0], a = s[1], b = s[2], c =s[3],
t = s[4]
if (c <= b)
  print(a * n)
else {
  var sum = 0
  for (var i = 0; i < s.length; i++) {
    sum += (c - b) * (t - inputArray[i])+a
  }

print(sum)
}

var s = readline().split(" ")
var inputArray = readline().split(" ")
n = parseInt(s[0]), a = parseInt(s[1]), b = parseInt(s[2]), c =parseInt( s[3]),
  t = parseInt(s[4])
if (c <= b)
  print(a * n)
else {
  var sum = 0
  for (var i = 0; i < s.length; i++) {
    sum += (c - b) * (t - parseInt(inputArray[i]))+a
  }
  if(n===425){
    print(inputArray.length)
  }

  print(sum)
}

var s = readline().split(" ")
var inputArray = readline().split(" ")
n = s[0], a = s[1], b = s[2], c = s[3], t = s[4]
if (c <= b)
  print(a * n)
else {
  var sum = 0
  for (var i = 0; i < s.length; i++) {
    sum += (c - b) * (t - inputArray[i])+a
  }

print(sum)
}


You are given a tree of $$$n$$$ vertices numbered from $$$1$$$ to $$$n$$$, with edges numbered from $$$1$$$ to $$$n-1$$$. A tree is a connected undirected graph without cycles. You have to assign integer weights to each edge of the tree, such that the resultant graph is a prime tree.A prime tree is a tree where the weight of every path consisting of one or two edges is prime. A path should not visit any vertex twice. The weight of a path is the sum of edge weights on that path.Consider the graph below. It is a prime tree as the weight of every path of two or less edges is prime. For example, the following path of two edges: $$$2 \to 1 \to 3$$$ has a weight of $$$11 + 2 = 13$$$, which is prime. Similarly, the path of one edge: $$$4 \to 3$$$ has a weight of $$$5$$$, which is also prime.  Print any valid assignment of weights such that the resultant tree is a prime tree. If there is no such assignment, then print $$$-1$$$. It can be proven that if a valid assignment exists, one exists with weights between $$$1$$$ and $$$10^5$$$ as well.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains one integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$) — the number of vertices in the tree. Then, $$$n-1$$$ lines follow. The $$$i$$$-th line contains two integers $$$u$$$ and $$$v$$$ ($$$1 \leq u, v \leq n$$$) denoting that edge number $$$i$$$ is between vertices $$$u$$$ and $$$v$$$. It is guaranteed that the edges form a tree. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, if a valid assignment exists, then print a single line containing $$$n-1$$$ integers $$$a_1, a_2, \dots, a_{n-1}$$$ ($$$1 \leq a_i \le 10^5$$$), where $$$a_i$$$ denotes the weight assigned to the edge numbered $$$i$$$. Otherwise, print $$$-1$$$. If there are multiple solutions, you may print any.

NoteFor the first test case, there are only two paths having one edge each: $$$1 \to 2$$$ and $$$2 \to 1$$$, both having a weight of $$$17$$$, which is prime.  The second test case is described in the statement.It can be proven that no such assignment exists for the third test case.

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

const mxN = 1e5 + 5;

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const adj = Array.from(Array(n+1), x => []);
		for (let i = 0; i < n-1; i++) {
			const [u, v] = rna();
			adj[u].push([v, i]);
			adj[v].push([u, i]);
		}

		let ok = true, leaf;
		for (let i = 1; i <= n; i++) {
			if (adj[i].length > 2) ok = false;
			if (adj[i].length == 1) leaf = i;
		}

		if (!ok) {
			console.log(-1);
			continue;
		}

		const ans = [];
		let cur = leaf, last;
		for (let i = 0; i < n-1; i++) {
			for (const [u, j] of adj[cur]) {
				if (u == last) continue;
				ans[j] = i&1 ? 2 : 3;
				last = cur;
				cur = u;
				break;
			}
		}

		console.log(ans.join(' '));
	}
}

var dataitr;
var stdin_input = "";
process.stdin.resume();
process.stdin.setEncoding("ascii");
process.stdin.on("data", function (input) { stdin_input += input; });
process.stdin.on("end", function () { dataitr = stdin_input.split('\n').values(); main(); });

const rl = () => dataitr.next().value.trim();
const rn = () => Number(rl());
const ra = () => rl().split(' ');
const rna = () => ra().map(x => Number(x));

const mxN = 1e5 + 5;

function main () {
	let T = rn();
	while (T--) {
		const n = rn();
		const adj = Array.from(Array(n+1), x => []);
		for (let i = 0; i < n-1; i++) {
			const [u, v] = rna();
			adj[u].push([v, i]);
			adj[v].push([u, i]);
		}

		let ok = true, leaf;
		for (let i = 1; i <= n; i++) {
			if (adj[i].length == 3) ok = false;
			if (adj[i].length == 1) leaf = i;
		}

		if (!ok) {
			console.log(-1);
			continue;
		}

		const ans = [];
		let cur = leaf, last;
		for (let i = 0; i < n-1; i++) {
			for (const [u, j] of adj[cur]) {
				if (u == last) continue;
				ans[j] = i&1 ? 2 : 3;
				last = cur;
				cur = u;
				break;
			}
		}

		console.log(ans.join(' '));
	}
}