exec_outcome stringclasses 1 value | code_uid stringlengths 32 32 | file_name stringclasses 111 values | prob_desc_created_at stringlengths 10 10 | prob_desc_description stringlengths 63 3.8k | prob_desc_memory_limit stringclasses 18 values | source_code stringlengths 117 65.5k | lang_cluster stringclasses 1 value | prob_desc_sample_inputs stringlengths 2 802 | prob_desc_time_limit stringclasses 27 values | prob_desc_sample_outputs stringlengths 2 796 | prob_desc_notes stringlengths 4 3k β | lang stringclasses 5 values | prob_desc_input_from stringclasses 3 values | tags listlengths 0 11 | src_uid stringlengths 32 32 | prob_desc_input_spec stringlengths 28 2.37k β | difficulty int64 -1 3.5k β | prob_desc_output_spec stringlengths 17 1.47k β | prob_desc_output_to stringclasses 3 values | hidden_unit_tests stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | 324ebad86fd42af2c526a6e008082ef2 | train_003.jsonl | 1597415700 | You are given an array $$$a_1, a_2, \dots , a_n$$$, which is sorted in non-decreasing order ($$$a_i \le a_{i + 1})$$$. Find three indices $$$i$$$, $$$j$$$, $$$k$$$ such that $$$1 \le i < j < k \le n$$$ and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to $$$a_i$$$, $$$a_j$$$ and $$$a_k$$$ (for example it is possible to construct a non-degenerate triangle with sides $$$3$$$, $$$4$$$ and $$$5$$$ but impossible with sides $$$3$$$, $$$4$$$ and $$$7$$$). If it is impossible to find such triple, report it. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;
public class Temp {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solution sol = new Solution();
int t = in.nextInt();
for (int i = 0; i < t; ++i)
sol.aSolve(in, out);
// sol.bSolve(in, out);
// sol.cSolve(in, out);
out.close();
}
private static class Solution {
private void aSolve(InputReader in, PrintWriter out) {
int n = in.nextInt();
long[] a = new long[n];
for (int i = 0; i < n; ++i)
a[i] = in.nextInt();
if (a[0] + a[1] <= a[n - 1]) {
out.println("1 2 " + n);
return;
}
out.println(-1);
}
private void bSolve(InputReader in, PrintWriter out) {
char[] s = in.next().toCharArray();
ArrayList<Integer> cons = new ArrayList<>();
int n = s.length;
for (int i = 0; i < n; ++i) {
int r = 0;
if (s[i] == '1') {
for (int j = i; j<n; ++j) {
if (s[j] == '1') {
r++;
if (j + 1 == n) {
cons.add(r);
i = j;
}
}
else if (s[j] == '0') {
cons.add(r);
i = j;
break;
}
}
}
}
Collections.sort(cons);
Collections.reverse(cons);
int ans = 0;
boolean alice = true;
for (int i = 0; i < cons.size(); ++i) {
if (alice) {
ans += cons.get(i);
alice = false;
} else {
alice = true;
}
}
out.println(ans);
}
private void cSolve(InputReader in, PrintWriter out) {
int n = in.nextInt();
char[] dum = in.next().toCharArray();
int[] a = new int[n];
for (int i = 0; i < n; ++i)
a[i] = dum[i] - '0';
int ans = 0;
for (int i = 0; i < n; ++i) {
int pref = a[i];
for (int j = 0; j < n; ++j) {
if (pref == j - i + 1) {
++ans;
break;
}
if (i == j) continue;
pref += a[j];
// out.println(pref + " " + (j - i));
}
}
out.println(ans);
}
}
private static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
private InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 9000000);
tokenizer = null;
}
private String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
private int nextInt() {
return Integer.parseInt(next());
}
private long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["3\n7\n4 6 11 11 15 18 20\n4\n10 10 10 11\n3\n1 1 1000000000"] | 1 second | ["2 3 6\n-1\n1 2 3"] | NoteIn the first test case it is impossible with sides $$$6$$$, $$$11$$$ and $$$18$$$. Note, that this is not the only correct answer.In the second test case you always can construct a non-degenerate triangle. | Java 8 | standard input | [
"geometry",
"math"
] | 341555349b0c1387334a0541730159ac | The first line contains one integer $$$t$$$ ($$$1 \le t \le 1000$$$)Β β the number of test cases. The first line of each test case contains one integer $$$n$$$ ($$$3 \le n \le 5 \cdot 10^4$$$)Β β the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots , a_n$$$ ($$$1 \le a_i \le 10^9$$$; $$$a_{i - 1} \le a_i$$$)Β β the array $$$a$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$. | 800 | For each test case print the answer to it in one line. If there is a triple of indices $$$i$$$, $$$j$$$, $$$k$$$ ($$$i < j < k$$$) such that it is impossible to construct a non-degenerate triangle having sides equal to $$$a_i$$$, $$$a_j$$$ and $$$a_k$$$, print that three indices in ascending order. If there are multiple answers, print any of them. Otherwise, print -1. | standard output | |
PASSED | 6ed5b12ebc221b1dcdd4163286b2cc1d | train_003.jsonl | 1308582000 | A newspaper is published in Walrusland. Its heading is s1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new word s2. It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.For example, the heading is "abc". If we take two such headings and glue them one to the other one, we get "abcabc". If we erase the letters on positions 1 and 5, we get a word "bcac".Which least number of newspaper headings s1 will Fangy need to glue them, erase several letters and get word s2? | 256 megabytes | import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
char[] s1=sc.nextLine().toCharArray();
char[] s2=sc.nextLine().toCharArray();
int len=s1.length;
int[][] visit = new int[26][len+1];
for(int i=0;i<26;i++) visit[i][len]=-1;
for(int i=len-1;i>=0;i--){
for(int j=0;j<26;j++) visit[j][i]=visit[j][i+1];
visit[s1[i]-'a'][i]=i;
}
int res=1;
int count=0;
for(int i=0;i<s2.length;i++){
if(visit[s2[i]-'a'][0]==-1) {
res=-1;
break;
}
int pos=visit[s2[i]-'a'][count];
if(pos!=-1){
count=pos+1;
}
else{
res++;
count=visit[s2[i]-'a'][0]+1;
}
}
System.out.println(res);
}
}
}
| Java | ["abc\nxyz", "abcd\ndabc"] | 2 seconds | ["-1", "2"] | null | Java 8 | standard input | [
"greedy",
"strings"
] | 1b83529ea4057c76ae8483f8aa506c56 | The input data contain two lines. The first line contain the heading s1, the second line contains the word s2. The lines only consist of lowercase Latin letters (1ββ€β|s1|ββ€β104,β1ββ€β|s2|ββ€β106). | 1,500 | If it is impossible to get the word s2 in the above-described manner, print "-1" (without the quotes). Otherwise, print the least number of newspaper headings s1, which Fangy will need to receive the word s2. | standard output | |
PASSED | c604656d1f52c408650406ed8da30e58 | train_003.jsonl | 1308582000 | A newspaper is published in Walrusland. Its heading is s1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new word s2. It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.For example, the heading is "abc". If we take two such headings and glue them one to the other one, we get "abcabc". If we erase the letters on positions 1 and 5, we get a word "bcac".Which least number of newspaper headings s1 will Fangy need to glue them, erase several letters and get word s2? | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
char[] s1 = sc.next().toCharArray();
char[] s2 = sc.next().toCharArray();
int len = s1.length;
int[][] find = new int[26][len+1];
for (int j = 0; j < 26; j ++) find[j][len] = -1;
for (int i = len - 1; i >= 0; i --) {
for (int j = 0; j < 26; j ++) find[j][i] = find[j][i+1];
find[s1[i]-'a'][i] = i;
}
int res = 1;
int index = 0;
for (char cur: s2) {
int first = find[cur-'a'][0];
if (first == -1) { res = -1; break; }
int seek = find[cur-'a'][index];
if (seek != -1) {
index = seek + 1;
} else {
res ++;
index = first + 1;
}
}
System.out.println(res);
}
}
}
| Java | ["abc\nxyz", "abcd\ndabc"] | 2 seconds | ["-1", "2"] | null | Java 8 | standard input | [
"greedy",
"strings"
] | 1b83529ea4057c76ae8483f8aa506c56 | The input data contain two lines. The first line contain the heading s1, the second line contains the word s2. The lines only consist of lowercase Latin letters (1ββ€β|s1|ββ€β104,β1ββ€β|s2|ββ€β106). | 1,500 | If it is impossible to get the word s2 in the above-described manner, print "-1" (without the quotes). Otherwise, print the least number of newspaper headings s1, which Fangy will need to receive the word s2. | standard output | |
PASSED | a579139f069cb4353f32c634bd8c7197 | train_003.jsonl | 1308582000 | A newspaper is published in Walrusland. Its heading is s1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new word s2. It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.For example, the heading is "abc". If we take two such headings and glue them one to the other one, we get "abcabc". If we erase the letters on positions 1 and 5, we get a word "bcac".Which least number of newspaper headings s1 will Fangy need to glue them, erase several letters and get word s2? | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
char[] s1 = sc.next().toCharArray();
char[] s2 = sc.next().toCharArray();
int len = s1.length;
int[][] find = new int[26][len+1];
for (int j = 0; j < 26; j ++) find[j][len] = -1;
for (int i = len - 1; i >= 0; i --) {
for (int j = 0; j < 26; j ++) find[j][i] = find[j][i+1];
find[s1[i]-'a'][i] = i;
}
int res = 1;
int index = 0;
for (char cur: s2) {
int first = find[cur-'a'][0];
if (first == -1) { res = -1; break; }
int seek = find[cur-'a'][index];
if (seek != -1) {
index = seek + 1;
} else {
res ++;
index = first + 1;
}
}
System.out.println(res);
}
}
}
| Java | ["abc\nxyz", "abcd\ndabc"] | 2 seconds | ["-1", "2"] | null | Java 8 | standard input | [
"greedy",
"strings"
] | 1b83529ea4057c76ae8483f8aa506c56 | The input data contain two lines. The first line contain the heading s1, the second line contains the word s2. The lines only consist of lowercase Latin letters (1ββ€β|s1|ββ€β104,β1ββ€β|s2|ββ€β106). | 1,500 | If it is impossible to get the word s2 in the above-described manner, print "-1" (without the quotes). Otherwise, print the least number of newspaper headings s1, which Fangy will need to receive the word s2. | standard output | |
PASSED | 7651dd8caede49063d90cb9e362f1028 | train_003.jsonl | 1308582000 | A newspaper is published in Walrusland. Its heading is s1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new word s2. It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.For example, the heading is "abc". If we take two such headings and glue them one to the other one, we get "abcabc". If we erase the letters on positions 1 and 5, we get a word "bcac".Which least number of newspaper headings s1 will Fangy need to glue them, erase several letters and get word s2? | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
char[] s1 = sc.next().toCharArray();
char[] s2 = sc.next().toCharArray();
int len = s1.length;
int[][] find = new int[26][len+1];
for (int j = 0; j < 26; j ++) find[j][len] = -1;
for (int i = len - 1; i >= 0; i --) {
for (int j = 0; j < 26; j ++) find[j][i] = find[j][i+1];
find[s1[i]-'a'][i] = i;
}
int res = 1;
int index = 0;
for (char cur: s2) {
int first = find[cur-'a'][0];
if (first == -1) { res = -1; break; }
int seek = find[cur-'a'][index];
if (seek != -1) {
index = seek + 1;
} else {
res ++;
index = first + 1;
}
}
System.out.println(res);
}
}
}
| Java | ["abc\nxyz", "abcd\ndabc"] | 2 seconds | ["-1", "2"] | null | Java 8 | standard input | [
"greedy",
"strings"
] | 1b83529ea4057c76ae8483f8aa506c56 | The input data contain two lines. The first line contain the heading s1, the second line contains the word s2. The lines only consist of lowercase Latin letters (1ββ€β|s1|ββ€β104,β1ββ€β|s2|ββ€β106). | 1,500 | If it is impossible to get the word s2 in the above-described manner, print "-1" (without the quotes). Otherwise, print the least number of newspaper headings s1, which Fangy will need to receive the word s2. | standard output | |
PASSED | 888ea3a8a6262a0699bfc0618accf203 | train_003.jsonl | 1308582000 | A newspaper is published in Walrusland. Its heading is s1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new word s2. It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.For example, the heading is "abc". If we take two such headings and glue them one to the other one, we get "abcabc". If we erase the letters on positions 1 and 5, we get a word "bcac".Which least number of newspaper headings s1 will Fangy need to glue them, erase several letters and get word s2? | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
char[] s1 = sc.next().toCharArray();
char[] s2 = sc.next().toCharArray();
int len = s1.length;
int[][] find = new int[26][len + 1];
for (int j = 0; j < 26; j++)
find[j][len] = -1;
for (int i = len - 1; i >= 0; i--) {
for (int j = 0; j < 26; j++)
find[j][i] = find[j][i + 1];
find[s1[i] - 'a'][i] = i;
}
int res = 1;
int index = 0;
for (char cur : s2) {
int first = find[cur - 'a'][0];
if (first == -1) {
res = -1;
break;
}
int seek = find[cur - 'a'][index];
if (seek != -1) {
index = seek + 1;
} else {
res++;
index = first + 1;
}
}
System.out.println(res);
}
}
}
| Java | ["abc\nxyz", "abcd\ndabc"] | 2 seconds | ["-1", "2"] | null | Java 8 | standard input | [
"greedy",
"strings"
] | 1b83529ea4057c76ae8483f8aa506c56 | The input data contain two lines. The first line contain the heading s1, the second line contains the word s2. The lines only consist of lowercase Latin letters (1ββ€β|s1|ββ€β104,β1ββ€β|s2|ββ€β106). | 1,500 | If it is impossible to get the word s2 in the above-described manner, print "-1" (without the quotes). Otherwise, print the least number of newspaper headings s1, which Fangy will need to receive the word s2. | standard output | |
PASSED | ba6cd3f36ca75c7c2eec22ad9c9a9c82 | train_003.jsonl | 1308582000 | A newspaper is published in Walrusland. Its heading is s1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a new word s2. It is considered that when Fangy erases some letter, there's no whitespace formed instead of the letter. That is, the string remains unbroken and it still only consists of lowercase Latin letters.For example, the heading is "abc". If we take two such headings and glue them one to the other one, we get "abcabc". If we erase the letters on positions 1 and 5, we get a word "bcac".Which least number of newspaper headings s1 will Fangy need to glue them, erase several letters and get word s2? | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
char[] s1 = sc.next().toCharArray();
char[] s2 = sc.next().toCharArray();
int len = s1.length;
int[][] find = new int[26][len+1];
for (int j = 0; j < 26; j ++) find[j][len] = -1;
for (int i = len - 1; i >= 0; i --) {
for (int j = 0; j < 26; j ++) find[j][i] = find[j][i+1];
find[s1[i]-'a'][i] = i;
}
int res = 1;
int index = 0;
for (char cur: s2) {
int first = find[cur-'a'][0];
if (first == -1) { res = -1; break; }
int seek = find[cur-'a'][index];
if (seek != -1) {
index = seek + 1;
} else {
res ++;
index = first + 1;
}
}
System.out.println(res);
}
}
}
| Java | ["abc\nxyz", "abcd\ndabc"] | 2 seconds | ["-1", "2"] | null | Java 8 | standard input | [
"greedy",
"strings"
] | 1b83529ea4057c76ae8483f8aa506c56 | The input data contain two lines. The first line contain the heading s1, the second line contains the word s2. The lines only consist of lowercase Latin letters (1ββ€β|s1|ββ€β104,β1ββ€β|s2|ββ€β106). | 1,500 | If it is impossible to get the word s2 in the above-described manner, print "-1" (without the quotes). Otherwise, print the least number of newspaper headings s1, which Fangy will need to receive the word s2. | standard output | |
PASSED | fea1a3a9411aed17c7f47ae7b2c1a036 | train_003.jsonl | 1514392500 | Given an integer N, find two permutations: Permutation p of numbers from 1 to N such that piββ βi and piβ&βiβ=β0 for all iβ=β1,β2,β...,βN. Permutation q of numbers from 1 to N such that qiββ βi and qiβ&βiββ β0 for all iβ=β1,β2,β...,βN. & is the bitwise AND operation. | 256 megabytes | //package practice.pset1;
import java.io.*;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class R455F {
static int[] arr6 = {3, 6, 1, 5, 4, 2};
static int[] arr7 = {7, 6, 1, 5, 4, 3, 2};
static int[] arr9 = {3, 6, 1, 5, 4, 7, 2, 9, 8};
static int[] arr10 = {3, 6, 1, 5, 4, 2, 9, 10, 7, 8};
static int[] arr11 = {3, 6, 1, 5, 4, 2, 9, 10, 7, 11, 8};
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
int[] p = findP(n);
Pair[] arr = new Pair[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = new Pair(i+1, i+1);
}
q = new int[n+1];
boolean b = findQ(arr);
if(p == null)
pw.println("NO");
else
{
pw.println("YES");
for (int i = 1; i <= n; i++) {
if(i != 1)
pw.print(" ");
pw.print(p[i]);
}
pw.println();
}
if(!b)
pw.println("NO");
else
{
// if(!check(q))
// throw new RuntimeException();
pw.println("YES");
for (int i = 1; i <= n; i++) {
if(i != 1)
pw.print(" ");
pw.print(q[i]);
}
pw.println();
}
pw.flush();
pw.close();
}
static boolean check(int[] arr){
int cnt = 0;
int n = arr.length;
for (int i = 1; i < n; i++) {
if((i == arr[i]) || ((i) & arr[i]) == 0)
cnt++;
}
return cnt == 0;
}
static int[] findP(int n){
if(n%2 == 1)
return null;
int[] ret = new int[n+1];
for (int x = n; x >= 0; x--) {
if(ret[x] == 0){
int y = findComplement(x, bits(x));
ret[y] = x;
ret[x] = y;
}
}
return ret;
}
static int findComplement(int x, int bits){
int ret = 0;
for (int i = 0; i < bits; i++) {
int lb = (1<<i) & x;
if(lb == 0)
ret += 1<<i;
}
if((ret & x) != 0)
System.err.println("BUG in findComplement");
return ret;
}
static int bits(int x){
int cnt = 0;
while(x > 0){
cnt++;
x/=2;
}
return cnt;
}
static int[] q;
static boolean findQ(Pair[] arr){
int n = arr.length;
if(n <= 5)
return false;
if(Integer.bitCount(n) == 1)
return false;
// base cases 6 7 9 10 11
if(n == 6){
for (int i = 0; i < arr6.length; i++) {
int pos = arr[i].orig;
int val = arr[arr6[i]-1].orig;
q[pos] = val;
}
return true;
}
if(n == 7){
for (int i = 0; i < arr7.length; i++) {
int pos = arr[i].orig;
int val = arr[arr7[i]-1].orig;
q[pos] = val;
}
return true;
}
if(n == 9){
for (int i = 0; i < arr9.length; i++) {
int pos = arr[i].orig;
int val = arr[arr9[i]-1].orig;
q[pos] = val;
}
return true;
}
if(n == 10){
for (int i = 0; i < arr10.length; i++) {
int pos = arr[i].orig;
int val = arr[arr10[i]-1].orig;
q[pos] = val;
}
return true;
}
if(n == 11){
for (int i = 0; i < arr11.length; i++) {
int pos = arr[i].orig;
int val = arr[arr11[i]-1].orig;
q[pos] = val;
}
return true;
}
// end of base cases
if(Integer.bitCount(n-1) == 1){
int i = n-1;
int j = n-2;
q[arr[i].orig] = arr[j].orig;
q[arr[j].orig] = arr[i].orig;
findQ(Arrays.copyOf(arr, n-2));
}else{
ArrayList<Pair> even = new ArrayList<>();
ArrayList<Pair> odd = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
Pair add = new Pair(arr[i].orig, arr[i].cur/2);
if(arr[i].cur % 2 == 1){
odd.add(add);
}else{
even.add(add);
}
}
odd.add(odd.get(0));
for (int i = 0; i < odd.size() - 1; i++) {
Pair x = odd.get(i);
Pair y = odd.get(i+1);
q[x.orig] = y.orig;
}
Pair[] arr2 = new Pair[even.size()];
for (int i = 0; i < arr2.length; i++) {
arr2[i] = even.get(i);
}
findQ(arr2);
}
return true;
}
static class Pair{
int orig, cur;
public Pair(int orig, int cur) {
this.orig = orig;
this.cur = cur;
}
}
static class Scanner
{
StringTokenizer st; BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s)));}
public String next() throws IOException {while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());return st.nextToken();}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public boolean ready() throws IOException {return br.ready();}
}
}
| Java | ["3", "6"] | 2 seconds | ["NO\nNO", "YES\n6 5 4 3 2 1 \nYES\n3 6 2 5 1 4"] | null | Java 8 | standard input | [
"constructive algorithms"
] | 581d08af78dc960f3212bdf01bc57167 | The input consists of one line containing a single integer N (1ββ€βNββ€β105). | 2,500 | For each subtask, if the required permutation doesn't exist, output a single line containing the word "NO"; otherwise output the word "YES" in the first line and N elements of the permutation, separated by spaces, in the second line. If there are several possible permutations in a subtask, output any of them. | standard output | |
PASSED | 5d2f380dd33b812f8a47a58dfdefe2df | train_003.jsonl | 1514392500 | Given an integer N, find two permutations: Permutation p of numbers from 1 to N such that piββ βi and piβ&βiβ=β0 for all iβ=β1,β2,β...,βN. Permutation q of numbers from 1 to N such that qiββ βi and qiβ&βiββ β0 for all iβ=β1,β2,β...,βN. & is the bitwise AND operation. | 256 megabytes | //package practice.pset1;
import java.io.*;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class R455F_ {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
int[] p = findP(n);
int[] q = findQ(n);
if(p == null)
pw.println("NO");
else
{
pw.println("YES");
for (int i = 1; i <= n; i++) {
if(i != 1)
pw.print(" ");
pw.print(p[i]);
}
pw.println();
}
if(q == null)
pw.println("NO");
else
{
pw.println("YES");
for (int i = 1; i <= n; i++) {
if(i != 1)
pw.print(" ");
pw.print(q[i]);
}
pw.println();
}
pw.flush();
pw.close();
}
static int[] findP(int n){
if(n%2 == 1)
return null;
int[] ret = new int[n+1];
for (int x = n; x >= 0; x--) {
if(ret[x] == 0){
int y = findComplement(x, bits(x));
ret[y] = x;
ret[x] = y;
}
}
return ret;
}
static int findComplement(int x, int bits){
int ret = 0;
for (int i = 0; i < bits; i++) {
int lb = (1<<i) & x;
if(lb == 0)
ret += 1<<i;
}
if((ret & x) != 0)
System.err.println("BUG in findComplement");
return ret;
}
static int bits(int x){
int cnt = 0;
while(x > 0){
cnt++;
x/=2;
}
return cnt;
}
static int[] findQ(int n){
if (n <= 5 || Integer.bitCount(n) == 1)
return null;
if(n == 6)
return new int[]{0, 3, 6, 1, 5, 4, 2};
if(n == 7)
return new int[]{0, 7, 6, 1, 5, 4, 3, 2};
int[] q = new int[n+1];
int[] arr7 =new int[]{0, 7, 6, 1, 5, 4, 3, 2};
for (int i = 1; i <= 7; i++)
q[i] = arr7[i];
for (int i = 8; i <= n;) {
ArrayList<Integer> tmp = new ArrayList<>();
tmp.add(i);
i++;
while(i <= n && Integer.bitCount(i) != 1) {
tmp.add(i);
i++;
}
tmp.add(tmp.get(0));
for (int j = 0; j < tmp.size()-1; j++) {
q[tmp.get(j)] = tmp.get(j+1);
}
}
return q;
}
static class Scanner
{
StringTokenizer st; BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s)));}
public String next() throws IOException {while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());return st.nextToken();}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public boolean ready() throws IOException {return br.ready();}
}
}
| Java | ["3", "6"] | 2 seconds | ["NO\nNO", "YES\n6 5 4 3 2 1 \nYES\n3 6 2 5 1 4"] | null | Java 8 | standard input | [
"constructive algorithms"
] | 581d08af78dc960f3212bdf01bc57167 | The input consists of one line containing a single integer N (1ββ€βNββ€β105). | 2,500 | For each subtask, if the required permutation doesn't exist, output a single line containing the word "NO"; otherwise output the word "YES" in the first line and N elements of the permutation, separated by spaces, in the second line. If there are several possible permutations in a subtask, output any of them. | standard output | |
PASSED | b5ca23f5a120d3bf93c14566dd95c5fb | train_003.jsonl | 1514392500 | Given an integer N, find two permutations: Permutation p of numbers from 1 to N such that piββ βi and piβ&βiβ=β0 for all iβ=β1,β2,β...,βN. Permutation q of numbers from 1 to N such that qiββ βi and qiβ&βiββ β0 for all iβ=β1,β2,β...,βN. & is the bitwise AND operation. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class ProblemE
{
static int mod = (int) (1e9+7);
static InputReader in;
static PrintWriter out;
static int[] get(int n){
int[] a = new int[n + 1];
int x = 0;
int l = Integer.toBinaryString(n).length();
for(int i = 0; i < l; i++)
x |= 1 << i;
for(int i = 1; i <= n; i++)
a[i] = x ^ i;
return a;
}
public static void main(String[] args)
{
in = new InputReader(System.in);
out = new PrintWriter(System.out);
int n = in.nextInt();
int y = Integer.highestOneBit(n);
if(n % 2 != 0){
out.println("NO");
if(n < 6)
out.println("NO");
else{
int[] b = new int[n + 1];
b[1] = 3;
b[2] = 7;
b[3] = 2;
b[4] = 5;
b[5] = 1;
b[6] = 4;
b[7] = 6;
for(int i = 8; i <= n; i += 2){
b[i] = i + 1;
b[i + 1] = i;
}
out.println("YES");
for(int i = 1; i <= n; i++)
out.print(b[i] + " ");
out.println();
}
out.close();
return;
}
int[] a = new int[n + 1];
int m = n;
while(m > 0){
int[] x = get(m);
int j = 1;
for(j = 1; j <= m; j++){
a[j] = x[j];
}
j = 1;
for(j = 1; j <= m; j++){
if(a[j] <= m)
break;
}
m = j - 1;
}
out.println("YES");
for(int i = 1; i <= n; i++)
out.print(a[i] + " ");
out.println();
if(y == n){
out.println("NO");
out.close();
return;
}
int[] b = new int[n + 1];
b[1] = 3;
b[2] = 6;
b[3] = 2;
b[4] = 5;
b[5] = 1;
b[6] = 4;
int last = 7;
for(int i = 8; i < n; i += 2){
int cy = Integer.highestOneBit(i + 2);
if(cy == i + 2){
b[last] = i;
b[i] = last;
last = i + 1;
}
else{
b[i] = i + 1;
b[i + 1] = i;
}
}
if(n > 6 && b[last] == 0){
b[last] = n;
b[n] = last;
}
out.println("YES");
for(int i = 1; i <= n; i++)
out.print(b[i] + " ");
out.println();
out.close();
}
static class Pair implements Comparable<Pair>
{
int x,y;
int i;
Pair (int x,int y)
{
this.x = x;
this.y = y;
}
Pair (int x,int y, int i)
{
this.x = x;
this.y = y;
this.i = i;
}
public int compareTo(Pair o)
{
return Long.compare(this.i,o.i);
//return 0;
}
public boolean equals(Object o)
{
if (o instanceof Pair)
{
Pair p = (Pair)o;
return p.x == x && p.y==y;
}
return false;
}
@Override
public String toString()
{
return x + " "+ y + " "+i;
}
/*public int hashCode()
{
return new Long(x).hashCode() * 31 + new Long(y).hashCode();
}*/
}
static long gcd(long x,long y)
{
if(y==0)
return x;
else
return gcd(y,x%y);
}
static int gcd(int x,int y)
{
if(y==0)
return x;
else
return gcd(y,x%y);
}
static long pow(long n,long p,long m)
{
long result = 1;
if(p==0){
return 1;
}
while(p!=0)
{
if(p%2==1)
result *= n;
if(result >= m)
result %= m;
p >>=1;
n*=n;
if(n >= m)
n%=m;
}
return result;
}
static long pow(long n,long p)
{
long result = 1;
if(p==0)
return 1;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
static void debug(Object... o)
{
System.out.println(Arrays.deepToString(o));
}
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n)
{
long a[] = new long[n];
for (int i = 0; i < n; i++)
{
a[i] = nextLong();
}
return a;
}
public String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["3", "6"] | 2 seconds | ["NO\nNO", "YES\n6 5 4 3 2 1 \nYES\n3 6 2 5 1 4"] | null | Java 8 | standard input | [
"constructive algorithms"
] | 581d08af78dc960f3212bdf01bc57167 | The input consists of one line containing a single integer N (1ββ€βNββ€β105). | 2,500 | For each subtask, if the required permutation doesn't exist, output a single line containing the word "NO"; otherwise output the word "YES" in the first line and N elements of the permutation, separated by spaces, in the second line. If there are several possible permutations in a subtask, output any of them. | standard output | |
PASSED | 5a2c2d1467753625555c0a9314497c51 | train_003.jsonl | 1514392500 | Given an integer N, find two permutations: Permutation p of numbers from 1 to N such that piββ βi and piβ&βiβ=β0 for all iβ=β1,β2,β...,βN. Permutation q of numbers from 1 to N such that qiββ βi and qiβ&βiββ β0 for all iβ=β1,β2,β...,βN. & is the bitwise AND operation. | 256 megabytes | import java.io.IOException;
import java.util.*;
public class Test {
int readInt() {
int ans = 0;
boolean neg = false;
try {
boolean start = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (c == '-') {
start = true;
neg = true;
continue;
} else if (c >= '0' && c <= '9') {
start = true;
ans = ans * 10 + c - '0';
} else if (start) break;
}
} catch (IOException e) {
}
return neg ? -ans : ans;
}
int[] ns;
void swap(int i, int j) {
int t = ns[i];
ns[i] = ns[j];
ns[j] = t;
}
void start() {
int n = readInt();
ns = new int[n+1];
if (n % 2 == 1) System.out.println("NO");
else {
System.out.println("YES");
for (int i = n; i >= 1; i--) {
if (ns[i] != 0) continue;
int one = Integer.highestOneBit(i);
int k = ~i & (one - 1);
ns[i] = k;
ns[k] = i;
}
for (int i = 1; i <= n; i++) {
System.out.print(ns[i] + " ");
}
System.out.println();
}
Arrays.fill(ns, 0);
if (n < 6 || (n & (n - 1)) == 0) System.out.println("NO");
else {
System.out.println("YES");
for (int i = 1; i <= Math.min(7, n); i++) ns[i] = i;
swap(5, 1);
swap(2, 3);
swap(4, 6);
if (n >= 7) {
swap(7, 1);
}
for (int i = 8; i <= n;) {
int ni = i << 1;
int j = 0;
for (j = i + 1; j < ni && j <= n; j++) ns[j] = j - 1;
ns[i] = j - 1;
i = j;
}
for (int i = 1; i <= n; i++) System.out.print(ns[i] + " ");
System.out.println();
}
}
public static void main(String[] args) {
new Test().start();
}
}
| Java | ["3", "6"] | 2 seconds | ["NO\nNO", "YES\n6 5 4 3 2 1 \nYES\n3 6 2 5 1 4"] | null | Java 8 | standard input | [
"constructive algorithms"
] | 581d08af78dc960f3212bdf01bc57167 | The input consists of one line containing a single integer N (1ββ€βNββ€β105). | 2,500 | For each subtask, if the required permutation doesn't exist, output a single line containing the word "NO"; otherwise output the word "YES" in the first line and N elements of the permutation, separated by spaces, in the second line. If there are several possible permutations in a subtask, output any of them. | standard output | |
PASSED | fc79b7340fecce9020feb2832ec08734 | train_003.jsonl | 1514392500 | Given an integer N, find two permutations: Permutation p of numbers from 1 to N such that piββ βi and piβ&βiβ=β0 for all iβ=β1,β2,β...,βN. Permutation q of numbers from 1 to N such that qiββ βi and qiβ&βiββ β0 for all iβ=β1,β2,β...,βN. & is the bitwise AND operation. | 256 megabytes | import java.io.IOException;
import java.util.*;
public class Test {
int readInt() {
int ans = 0;
boolean neg = false;
try {
boolean start = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (c == '-') {
start = true;
neg = true;
continue;
} else if (c >= '0' && c <= '9') {
start = true;
ans = ans * 10 + c - '0';
} else if (start) break;
}
} catch (IOException e) {
}
return neg ? -ans : ans;
}
void start() {
int n = readInt();
int[] ns = new int[n+1];
if (n % 2 == 1) System.out.println("NO");
else {
System.out.println("YES");
for (int i = n; i >= 1; i--) {
if (ns[i] != 0) continue;
int one = Integer.highestOneBit(i);
int k = ~i & (one - 1);
ns[i] = k;
ns[k] = i;
}
for (int i = 1; i <= n; i++) {
System.out.print(ns[i] + " ");
}
System.out.println();
}
Arrays.fill(ns, 0);
if (n < 6 || (n & (n - 1)) == 0) System.out.println("NO");
else {
System.out.println("YES");
int m = n;
if (((n - 1) & ( n - 2)) == 0) {
ns[n] = n - 1;
ns[n - 1] = n;
n -= 3;
} else if (n % 2 == 1) n--;
int one = Integer.lowestOneBit(n);
ns[one] = n;
ns[n] = one;
if (one != 1) {
int k = (one << 1) - 1;
ns[1] = k;
ns[k] = 1;
}
for (int i = 1; i <= n; i++) {
if (ns[i] != 0) continue;
ns[i] = i + 1;
ns[i + 1] = i;
}
if (((m - 1) & (m - 2)) == 0) {
int t = ns[1];
ns[1] = m - 2;
ns[m - 2] = t;
} else if (m % 2 == 1) {
int t = ns[1];
ns[1] = m;
ns[m] = t;
}
for (int i = 1; i <= m; i++) {
System.out.print(ns[i] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
new Test().start();
}
}
| Java | ["3", "6"] | 2 seconds | ["NO\nNO", "YES\n6 5 4 3 2 1 \nYES\n3 6 2 5 1 4"] | null | Java 8 | standard input | [
"constructive algorithms"
] | 581d08af78dc960f3212bdf01bc57167 | The input consists of one line containing a single integer N (1ββ€βNββ€β105). | 2,500 | For each subtask, if the required permutation doesn't exist, output a single line containing the word "NO"; otherwise output the word "YES" in the first line and N elements of the permutation, separated by spaces, in the second line. If there are several possible permutations in a subtask, output any of them. | standard output | |
PASSED | d2455649d64a34fb023b2f3acf994341 | train_003.jsonl | 1514392500 | Given an integer N, find two permutations: Permutation p of numbers from 1 to N such that piββ βi and piβ&βiβ=β0 for all iβ=β1,β2,β...,βN. Permutation q of numbers from 1 to N such that qiββ βi and qiβ&βiββ β0 for all iβ=β1,β2,β...,βN. & is the bitwise AND operation. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* @author Don Li
*/
public class ANDPermutations {
void solve() {
int n = in.nextInt();
findP(n);
findQ(n);
}
void findP(int n) {
if ((n & 1) > 0) {
out.println("NO");
return;
}
int[] res = new int[n + 1];
while (n > 0) {
int x = Integer.highestOneBit(n);
for (int i = 0; i <= n - x; i++) {
res[x + i] = x - i - 1;
res[x - i - 1] = x + i;
}
n = x * 2 - n - 2;
}
out.println("YES");
for (int i = 1; i < res.length; i++) {
if (i > 1) out.print(' ');
out.print(res[i]);
}
out.println();
}
void findQ(int n) {
if (Integer.bitCount(n) == 1) {
out.println("NO");
return;
}
if (n <= 5) {
out.println("NO");
return;
}
if (n == 6) {
out.println("YES");
out.println("3 6 2 5 1 4");
return;
}
if (n == 7) {
out.println("YES");
out.println("7 3 6 5 1 2 4");
return;
}
out.println("YES");
out.print("7 3 6 5 1 2 4 ");
for (int x = 8; x <= n; x <<= 1) {
int lim = Math.min((x << 1) - 1, n);
out.print(lim + " ");
for (int i = x; i < lim; i++) out.print(i + " ");
}
out.println();
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new ANDPermutations().solve();
out.close();
}
static FastScanner in;
static PrintWriter out;
static class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
| Java | ["3", "6"] | 2 seconds | ["NO\nNO", "YES\n6 5 4 3 2 1 \nYES\n3 6 2 5 1 4"] | null | Java 8 | standard input | [
"constructive algorithms"
] | 581d08af78dc960f3212bdf01bc57167 | The input consists of one line containing a single integer N (1ββ€βNββ€β105). | 2,500 | For each subtask, if the required permutation doesn't exist, output a single line containing the word "NO"; otherwise output the word "YES" in the first line and N elements of the permutation, separated by spaces, in the second line. If there are several possible permutations in a subtask, output any of them. | standard output | |
PASSED | fcaa51cdc68e8896dce318c4c801e8d1 | train_003.jsonl | 1514392500 | Given an integer N, find two permutations: Permutation p of numbers from 1 to N such that piββ βi and piβ&βiβ=β0 for all iβ=β1,β2,β...,βN. Permutation q of numbers from 1 to N such that qiββ βi and qiβ&βiββ β0 for all iβ=β1,β2,β...,βN. & is the bitwise AND operation. | 256 megabytes | import java.util.Scanner;
public class F455 {
@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
if (n % 2 ==1){
System.out.println("NO");
}else{
System.out.println("YES");
int[] p = new int[n + 1];
int max = n;
while (max > 0){
int i = gpt(max);
int j = i - 1;
while (i <= max){
p[i] = j;
p[j] = i;
i++;
j--;
}
max = j;
}
for (int i = 1; i <= n; i++){
System.out.print(p[i] + " ");
}
System.out.println();
}
//other half
if (n < 6 || gpt(n) == n){
System.out.println("NO");
}else{
System.out.println("YES");
if (n == 6){
System.out.println("5 3 2 6 1 4");
}else if (n == 7){
System.out.println("5 3 2 7 1 4 6");
}else{
System.out.print("5 3 2 7 1 4 6 ");
int i = 8;
int max = i * 2;
while (max < n){
while (i < max - 1){
System.out.print(i + 1 + " ");
i++;
}
System.out.print(max / 2 + " ");
i = max;
max = i * 2;
}
System.out.print(n + " ");
i++;
for (; i <= n; i++){
System.out.print(i - 1 + " ");
}
}
}
}
public static int gpt(int n){
int i = 1;
while (i * 2 <= n){
i *= 2;
}
return i;
}
} | Java | ["3", "6"] | 2 seconds | ["NO\nNO", "YES\n6 5 4 3 2 1 \nYES\n3 6 2 5 1 4"] | null | Java 8 | standard input | [
"constructive algorithms"
] | 581d08af78dc960f3212bdf01bc57167 | The input consists of one line containing a single integer N (1ββ€βNββ€β105). | 2,500 | For each subtask, if the required permutation doesn't exist, output a single line containing the word "NO"; otherwise output the word "YES" in the first line and N elements of the permutation, separated by spaces, in the second line. If there are several possible permutations in a subtask, output any of them. | standard output | |
PASSED | 5405dde530f9ae636f2121d706f4b7c8 | train_003.jsonl | 1514392500 | Given an integer N, find two permutations: Permutation p of numbers from 1 to N such that piββ βi and piβ&βiβ=β0 for all iβ=β1,β2,β...,βN. Permutation q of numbers from 1 to N such that qiββ βi and qiβ&βiββ β0 for all iβ=β1,β2,β...,βN. & is the bitwise AND operation. | 256 megabytes | import java.util.* ;
import java.io.* ;
public class AndPermutations2
{
static int[] andZero(int n)
{
if(n%2!=0)
return null ;
else
{
int[] ans = new int[n+1] ;
Arrays.fill(ans,-1) ;
int maxLog = binlog(n) ;
boolean allDone = false ;
while(!allDone)
{
int maxTwo = (1<<maxLog) ;
while(ans[maxTwo]!=-1)
maxTwo = maxTwo>>1 ;
ans[maxTwo] = maxTwo -1 ;
ans[maxTwo-1] = maxTwo ;
if(maxTwo==2)
break ;
int temp = maxTwo -1 ;
for(int i=maxTwo+1 ; i<=n;i++)
{
if(ans[i]!=-1)
break ;
ans[i] = --temp ;
ans[temp] = i ;
if(temp==1)
allDone = true ;
}
maxLog-- ;
}
return ans ;
}
}
public static void main(String args[])
{
InputReader in = new InputReader(System.in) ;
int n = in.readInt() ;
int[] ans1 = andZero(n) ;
if(ans1==null)
System.out.println("NO") ;
else
{
System.out.println("YES") ;
for(int i=1;i<ans1.length;i++)
{
System.out.print(ans1[i]+" ") ;
}
System.out.println() ;
}
int[] ans2 = nonZeroAnd(n) ;
if(ans2==null)
System.out.println("NO") ;
else
{
System.out.println("YES") ;
for(int i=1;i<ans2.length;i++)
{
System.out.print(ans2[i]+" ") ;
}
System.out.println() ;
}
}
public static int binlog( int bits ) // returns 0 for bits=0
{
int log = 0;
if( ( bits & 0xffff0000 ) != 0 ) { bits >>>= 16; log = 16; }
if( bits >= 256 ) { bits >>>= 8; log += 8; }
if( bits >= 16 ) { bits >>>= 4; log += 4; }
if( bits >= 4 ) { bits >>>= 2; log += 2; }
return log + ( bits >>> 1 );
}
static int[] nonZeroAnd(int n)
{
int maxLog = binlog(n) ;
if((1<<maxLog) == n || n<6)
return null ;
else
{
int[] ans ;
if(n==6)
{
ans = new int[]{-1,3,6,2,5,1,4} ;
}
else
{
ans = new int[n+1] ;
ans[1] = 7 ;
ans[2] = 3 ;
ans[3] = 6 ;
ans[4] = 5 ;
ans[5] = 1 ;
ans[6] = 2 ;
ans[7] = 4 ;
if(n>7)
{
for(int i=3;i<maxLog;i++)
{
int initial = (1<<i) ;
int max = (initial<<1) ;
for(int j=initial;j<max-1;j++)
{
ans[j] = j+1 ;
}
ans[max-1] = initial ;
}
int maxTwo = (1<<maxLog) ;
for(int i=maxTwo;i<n;i++)
{
ans[i] = i+1 ;
}
ans[n] = maxTwo ;
}
}
return ans ;
}
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public void readInt(int[] A) {
for (int i = 0; i < A.length; i++)
A[i] = readInt();
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public void readLong(long[] A) {
for (int i = 0; i < A.length; i++)
A[i] = readLong();
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public char[] readCharA() {
return readString().toCharArray();
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
| Java | ["3", "6"] | 2 seconds | ["NO\nNO", "YES\n6 5 4 3 2 1 \nYES\n3 6 2 5 1 4"] | null | Java 8 | standard input | [
"constructive algorithms"
] | 581d08af78dc960f3212bdf01bc57167 | The input consists of one line containing a single integer N (1ββ€βNββ€β105). | 2,500 | For each subtask, if the required permutation doesn't exist, output a single line containing the word "NO"; otherwise output the word "YES" in the first line and N elements of the permutation, separated by spaces, in the second line. If there are several possible permutations in a subtask, output any of them. | standard output | |
PASSED | 030bb83cc04423a4955d974eb247e214 | train_003.jsonl | 1514392500 | Given an integer N, find two permutations: Permutation p of numbers from 1 to N such that piββ βi and piβ&βiβ=β0 for all iβ=β1,β2,β...,βN. Permutation q of numbers from 1 to N such that qiββ βi and qiβ&βiββ β0 for all iβ=β1,β2,β...,βN. & is the bitwise AND operation. | 256 megabytes | import java.util.* ;
public class AndPermutations
{
static int[] andZero(int n)
{
if(n%2!=0)
return null ;
else
{
int[] ans = new int[n+1] ;
Arrays.fill(ans,-1) ;
int maxLog = binlog(n) ;
boolean allDone = false ;
while(!allDone)
{
// System.out.println("maxLog :"+maxLog) ;
int maxTwo = (1<<maxLog) ;
while(ans[maxTwo]!=-1)
maxTwo = maxTwo>>1 ;
ans[maxTwo] = maxTwo -1 ;
ans[maxTwo-1] = maxTwo ;
if(maxTwo==2)
{
// System.out.println("maxTwo was equal to 2") ;
break ;
}
int temp = maxTwo -1 ;
for(int i=maxTwo+1 ; i<=n;i++)
{
if(ans[i]!=-1)
{
// System.out.println((i)+" --> "+ans[i]) ;
break ;//has reached a point where things are full.
}
ans[i] = --temp ;
ans[temp] = i ;
if(temp==1)
allDone = true ;
// if(i==n)
// System.out.println((i)+" ---> "+ans[i]) ;
}
maxLog-- ;
}
// System.out.println(1+" ---> "+ans[1]) ;
return ans ;
}
}
static boolean uniques(int[] a)
{
int[] b = new int[a.length] ;
// System.out.println("Length :"+a.length) ;
for(int i=1;i<a.length;i++)
{
// System.out.println("a["+i+"] is :"+a[i]) ;
if(b[a[i]]==0)
b[a[i]] = i ;
else
{
System.out.println("Positions "+i+" and "+b[a[i]]+" have the same value :"+a[i]) ;
return false ;
}
}
return true ;
}
public static void main(String args[])
{
Scanner in = new Scanner(System.in) ;
int n = in.nextInt() ;
int[] ans1 = andZero(n) ;
// System.out.println(uniques(ans1)) ;
if(ans1==null)
System.out.println("NO") ;
else
{
System.out.println("YES") ;
for(int i=1;i<ans1.length;i++)
{
System.out.print(ans1[i]+" ") ;
}
System.out.println() ;
}
int[] ans2 = nonZeroAnd(n) ;
if(ans2==null)
System.out.println("NO") ;
else
{
System.out.println("YES") ;
for(int i=1;i<ans2.length;i++)
{
System.out.print(ans2[i]+" ") ;
}
System.out.println() ;
}
}
public static int binlog( int bits ) // returns 0 for bits=0
{
int log = 0;
if( ( bits & 0xffff0000 ) != 0 ) { bits >>>= 16; log = 16; }
if( bits >= 256 ) { bits >>>= 8; log += 8; }
if( bits >= 16 ) { bits >>>= 4; log += 4; }
if( bits >= 4 ) { bits >>>= 2; log += 2; }
return log + ( bits >>> 1 );
}
static int[] nonZeroAnd(int n)
{
int maxLog = binlog(n) ;
if((1<<maxLog) == n || n<6)
return null ;
else
{
int[] ans ;
if(n==6)
{
ans = new int[]{-1,3,6,2,5,1,4} ;
}
else
{
ans = new int[n+1] ;
ans[1] = 7 ;
ans[2] = 3 ;
ans[3] = 6 ;
ans[4] = 5 ;
ans[5] = 1 ;
ans[6] = 2 ;
ans[7] = 4 ;
if(n>7)
{
for(int i=3;i<maxLog;i++)
{
int initial = (1<<i) ;
int max = (initial<<1) ;
for(int j=initial;j<max-1;j++)
{
ans[j] = j+1 ;
}
ans[max-1] = initial ;
}
int maxTwo = (1<<maxLog) ;
for(int i=maxTwo;i<n;i++)
{
ans[i] = i+1 ;
}
ans[n] = maxTwo ;
}
}
return ans ;
}
}
} | Java | ["3", "6"] | 2 seconds | ["NO\nNO", "YES\n6 5 4 3 2 1 \nYES\n3 6 2 5 1 4"] | null | Java 8 | standard input | [
"constructive algorithms"
] | 581d08af78dc960f3212bdf01bc57167 | The input consists of one line containing a single integer N (1ββ€βNββ€β105). | 2,500 | For each subtask, if the required permutation doesn't exist, output a single line containing the word "NO"; otherwise output the word "YES" in the first line and N elements of the permutation, separated by spaces, in the second line. If there are several possible permutations in a subtask, output any of them. | standard output | |
PASSED | 86ab01c37a98636a0c0fc42623797eeb | train_003.jsonl | 1514392500 | Given an integer N, find two permutations: Permutation p of numbers from 1 to N such that piββ βi and piβ&βiβ=β0 for all iβ=β1,β2,β...,βN. Permutation q of numbers from 1 to N such that qiββ βi and qiβ&βiββ β0 for all iβ=β1,β2,β...,βN. & is the bitwise AND operation. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;
public class F_455
{
public static final long[] POWER2 = generatePOWER2();
public static final IteratorBuffer<Long> ITERATOR_BUFFER_PRIME = new IteratorBuffer<>(streamPrime(1000000).iterator());
private static BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
private static StringTokenizer stringTokenizer = null;
private static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static class Array<Type> implements Iterable<Type>
{
private final Object[] array;
public Array(int size)
{
this.array = new Object[size];
}
public Array(int size, Type element)
{
this(size);
Arrays.fill(this.array, element);
}
public Array(Array<Type> array, Type element)
{
this(array.size() + 1);
for (int index = 0; index < array.size(); index++)
{
set(index, array.get(index));
}
set(size() - 1, element);
}
public Array(List<Type> list)
{
this(list.size());
int index = 0;
for (Type element : list)
{
set(index, element);
index += 1;
}
}
public Type get(int index)
{
return (Type) this.array[index];
}
@Override
public Iterator<Type> iterator()
{
return new Iterator<Type>()
{
int index = 0;
@Override
public boolean hasNext()
{
return this.index < size();
}
@Override
public Type next()
{
Type result = Array.this.get(index);
index += 1;
return result;
}
};
}
public Array set(int index, Type value)
{
this.array[index] = value;
return this;
}
public int size()
{
return this.array.length;
}
public List<Type> toList()
{
List<Type> result = new ArrayList<>();
for (Type element : this)
{
result.add(element);
}
return result;
}
@Override
public String toString()
{
return "[" + F_455.toString(this, ", ") + "]";
}
}
static class BIT
{
private static int lastBit(int index)
{
return index & -index;
}
private final long[] tree;
public BIT(int size)
{
this.tree = new long[size];
}
public void add(int index, long delta)
{
index += 1;
while (index <= this.tree.length)
{
tree[index - 1] += delta;
index += lastBit(index);
}
}
public long prefix(int end)
{
long result = 0;
while (end > 0)
{
result += this.tree[end - 1];
end -= lastBit(end);
}
return result;
}
public int size()
{
return this.tree.length;
}
public long sum(int start, int end)
{
return prefix(end) - prefix(start);
}
}
static abstract class Edge<TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>>
{
public final TypeVertex vertex0;
public final TypeVertex vertex1;
public final boolean bidirectional;
public Edge(TypeVertex vertex0, TypeVertex vertex1, boolean bidirectional)
{
this.vertex0 = vertex0;
this.vertex1 = vertex1;
this.bidirectional = bidirectional;
this.vertex0.edges.add(getThis());
if (this.bidirectional)
{
this.vertex1.edges.add(getThis());
}
}
public abstract TypeEdge getThis();
public TypeVertex other(Vertex<TypeVertex, TypeEdge> vertex)
{
TypeVertex result;
if (vertex0 == vertex)
{
result = vertex1;
}
else
{
result = vertex0;
}
return result;
}
public void remove()
{
this.vertex0.edges.remove(getThis());
if (this.bidirectional)
{
this.vertex1.edges.remove(getThis());
}
}
@Override
public String toString()
{
return this.vertex0 + "->" + this.vertex1;
}
}
public static class EdgeDefault<TypeVertex extends Vertex<TypeVertex, EdgeDefault<TypeVertex>>> extends Edge<TypeVertex, EdgeDefault<TypeVertex>>
{
public EdgeDefault(TypeVertex vertex0, TypeVertex vertex1, boolean bidirectional)
{
super(vertex0, vertex1, bidirectional);
}
@Override
public EdgeDefault<TypeVertex> getThis()
{
return this;
}
}
public static class EdgeDefaultDefault extends Edge<VertexDefaultDefault, EdgeDefaultDefault>
{
public EdgeDefaultDefault(VertexDefaultDefault vertex0, VertexDefaultDefault vertex1, boolean bidirectional)
{
super(vertex0, vertex1, bidirectional);
}
@Override
public EdgeDefaultDefault getThis()
{
return this;
}
}
public static class FIFO<Type>
{
public SingleLinkedList<Type> start;
public SingleLinkedList<Type> end;
public FIFO()
{
this.start = null;
this.end = null;
}
public boolean isEmpty()
{
return this.start == null;
}
public Type peek()
{
return this.start.element;
}
public Type pop()
{
Type result = this.start.element;
this.start = this.start.next;
return result;
}
public void push(Type element)
{
SingleLinkedList<Type> list = new SingleLinkedList<>(element, null);
if (this.start == null)
{
this.start = list;
this.end = list;
}
else
{
this.end.next = list;
this.end = list;
}
}
}
static class Fraction implements Comparable<Fraction>
{
public static final Fraction ZERO = new Fraction(0, 1);
public static Fraction fraction(long whole)
{
return fraction(whole, 1);
}
public static Fraction fraction(long numerator, long denominator)
{
Fraction result;
if (denominator == 0)
{
throw new ArithmeticException();
}
if (numerator == 0)
{
result = Fraction.ZERO;
}
else
{
int sign;
if (numerator < 0 ^ denominator < 0)
{
sign = -1;
numerator = Math.abs(numerator);
denominator = Math.abs(denominator);
}
else
{
sign = 1;
}
long gcd = gcd(numerator, denominator);
result = new Fraction(sign * numerator / gcd, denominator / gcd);
}
return result;
}
public final long numerator;
public final long denominator;
private Fraction(long numerator, long denominator)
{
this.numerator = numerator;
this.denominator = denominator;
}
public Fraction add(Fraction fraction)
{
return fraction(this.numerator * fraction.denominator + fraction.numerator * this.denominator, this.denominator * fraction.denominator);
}
@Override
public int compareTo(Fraction that)
{
return Long.compare(this.numerator * that.denominator, that.numerator * this.denominator);
}
public Fraction divide(Fraction fraction)
{
return multiply(fraction.inverse());
}
public boolean equals(Fraction that)
{
return this.compareTo(that) == 0;
}
public boolean equals(Object that)
{
return this.compareTo((Fraction) that) == 0;
}
public Fraction getRemainder()
{
return fraction(this.numerator - getWholePart() * denominator, denominator);
}
public long getWholePart()
{
return this.numerator / this.denominator;
}
public Fraction inverse()
{
return fraction(this.denominator, this.numerator);
}
public Fraction multiply(Fraction fraction)
{
return fraction(this.numerator * fraction.numerator, this.denominator * fraction.denominator);
}
public Fraction neg()
{
return fraction(-this.numerator, this.denominator);
}
public Fraction sub(Fraction fraction)
{
return add(fraction.neg());
}
@Override
public String toString()
{
String result;
if (getRemainder().equals(Fraction.ZERO))
{
result = "" + this.numerator;
}
else
{
result = this.numerator + "/" + this.denominator;
}
return result;
}
}
static class IteratorBuffer<Type>
{
private Iterator<Type> iterator;
private List<Type> list;
public IteratorBuffer(Iterator<Type> iterator)
{
this.iterator = iterator;
this.list = new ArrayList<Type>();
}
public Iterator<Type> iterator()
{
return new Iterator<Type>()
{
int index = 0;
@Override
public boolean hasNext()
{
return this.index < list.size() || IteratorBuffer.this.iterator.hasNext();
}
@Override
public Type next()
{
if (list.size() <= this.index)
{
list.add(iterator.next());
}
Type result = list.get(index);
index += 1;
return result;
}
};
}
}
public static class MapCount<Type> extends SortedMapAVL<Type, Long>
{
private int count;
public MapCount(Comparator<? super Type> comparator)
{
super(comparator);
this.count = 0;
}
public long add(Type key, Long delta)
{
long result;
if (delta > 0)
{
Long value = get(key);
if (value == null)
{
value = delta;
}
else
{
value += delta;
}
put(key, value);
result = delta;
}
else
{
result = 0;
}
this.count += result;
return result;
}
public int count()
{
return this.count;
}
public List<Type> flatten()
{
List<Type> result = new ArrayList<>();
for (Entry<Type, Long> entry : entrySet())
{
for (long index = 0; index < entry.getValue(); index++)
{
result.add(entry.getKey());
}
}
return result;
}
@Override
public SortedMapAVL<Type, Long> headMap(Type keyEnd)
{
throw new UnsupportedOperationException();
}
@Override
public void putAll(Map<? extends Type, ? extends Long> map)
{
throw new UnsupportedOperationException();
}
public long remove(Type key, Long delta)
{
long result;
if (delta > 0)
{
Long value = get(key) - delta;
if (value <= 0)
{
result = delta + value;
remove(key);
}
else
{
result = delta;
put(key, value);
}
}
else
{
result = 0;
}
this.count -= result;
return result;
}
@Override
public Long remove(Object key)
{
Long result = super.remove(key);
this.count -= result;
return result;
}
@Override
public SortedMapAVL<Type, Long> subMap(Type keyStart, Type keyEnd)
{
throw new UnsupportedOperationException();
}
@Override
public SortedMapAVL<Type, Long> tailMap(Type keyStart)
{
throw new UnsupportedOperationException();
}
}
public static class MapSet<TypeKey, TypeValue> extends SortedMapAVL<TypeKey, SortedSetAVL<TypeValue>> implements Iterable<TypeValue>
{
private Comparator<? super TypeValue> comparatorValue;
public MapSet(Comparator<? super TypeKey> comparatorKey, Comparator<? super TypeValue> comparatorValue)
{
super(comparatorKey);
this.comparatorValue = comparatorValue;
}
public MapSet(Comparator<? super TypeKey> comparatorKey, SortedSetAVL<Entry<TypeKey, SortedSetAVL<TypeValue>>> entrySet, Comparator<? super TypeValue> comparatorValue)
{
super(comparatorKey, entrySet);
this.comparatorValue = comparatorValue;
}
public boolean add(TypeKey key, TypeValue value)
{
SortedSetAVL<TypeValue> set = computeIfAbsent(key, k -> new SortedSetAVL<>(comparatorValue));
return set.add(value);
}
public TypeValue firstValue()
{
TypeValue result;
Entry<TypeKey, SortedSetAVL<TypeValue>> firstEntry = firstEntry();
if (firstEntry == null)
{
result = null;
}
else
{
result = firstEntry.getValue().first();
}
return result;
}
@Override
public MapSet<TypeKey, TypeValue> headMap(TypeKey keyEnd)
{
return new MapSet<>(this.comparator, this.entrySet.headSet(new AbstractMap.SimpleEntry<>(keyEnd, null)), this.comparatorValue);
}
public Iterator<TypeValue> iterator()
{
return new Iterator<TypeValue>()
{
Iterator<SortedSetAVL<TypeValue>> iteratorValues = values().iterator();
Iterator<TypeValue> iteratorValue = null;
@Override
public boolean hasNext()
{
return iteratorValues.hasNext() || (iteratorValue != null && iteratorValue.hasNext());
}
@Override
public TypeValue next()
{
if (iteratorValue == null || !iteratorValue.hasNext())
{
iteratorValue = iteratorValues.next().iterator();
}
return iteratorValue.next();
}
};
}
public TypeValue lastValue()
{
TypeValue result;
Entry<TypeKey, SortedSetAVL<TypeValue>> lastEntry = lastEntry();
if (lastEntry == null)
{
result = null;
}
else
{
result = lastEntry.getValue().last();
}
return result;
}
public boolean removeSet(TypeKey key, TypeValue value)
{
boolean result;
SortedSetAVL<TypeValue> set = get(key);
if (set == null)
{
result = false;
}
else
{
result = set.remove(value);
if (set.size() == 0)
{
remove(key);
}
}
return result;
}
@Override
public MapSet<TypeKey, TypeValue> tailMap(TypeKey keyStart)
{
return new MapSet<>(this.comparator, this.entrySet.tailSet(new AbstractMap.SimpleEntry<>(keyStart, null)), this.comparatorValue);
}
}
public static class Matrix
{
public final int rows;
public final int columns;
public final Fraction[][] cells;
public Matrix(int rows, int columns)
{
this.rows = rows;
this.columns = columns;
this.cells = new Fraction[rows][columns];
for (int row = 0; row < rows; row++)
{
for (int column = 0; column < columns; column++)
{
set(row, column, Fraction.ZERO);
}
}
}
public void add(int rowSource, int rowTarget, Fraction fraction)
{
for (int column = 0; column < columns; column++)
{
this.cells[rowTarget][column] = this.cells[rowTarget][column].add(this.cells[rowSource][column].multiply(fraction));
}
}
private int columnPivot(int row)
{
int result = this.columns;
for (int column = this.columns - 1; 0 <= column; column--)
{
if (this.cells[row][column].compareTo(Fraction.ZERO) != 0)
{
result = column;
}
}
return result;
}
public void reduce()
{
for (int rowMinimum = 0; rowMinimum < this.rows; rowMinimum++)
{
int rowPivot = rowPivot(rowMinimum);
if (rowPivot != -1)
{
int columnPivot = columnPivot(rowPivot);
Fraction current = this.cells[rowMinimum][columnPivot];
Fraction pivot = this.cells[rowPivot][columnPivot];
Fraction fraction = pivot.inverse().sub(current.divide(pivot));
add(rowPivot, rowMinimum, fraction);
for (int row = rowMinimum + 1; row < this.rows; row++)
{
if (columnPivot(row) == columnPivot)
{
add(rowMinimum, row, this.cells[row][columnPivot(row)].neg());
}
}
}
}
}
private int rowPivot(int rowMinimum)
{
int result = -1;
int pivotColumnMinimum = this.columns;
for (int row = rowMinimum; row < this.rows; row++)
{
int pivotColumn = columnPivot(row);
if (pivotColumn < pivotColumnMinimum)
{
result = row;
pivotColumnMinimum = pivotColumn;
}
}
return result;
}
public void set(int row, int column, Fraction value)
{
this.cells[row][column] = value;
}
public String toString()
{
String result = "";
for (int row = 0; row < rows; row++)
{
for (int column = 0; column < columns; column++)
{
result += this.cells[row][column] + "\t";
}
result += "\n";
}
return result;
}
}
public static class Node<Type>
{
public static <Type> Node<Type> balance(Node<Type> result)
{
while (result != null && 1 < Math.abs(height(result.left) - height(result.right)))
{
if (height(result.left) < height(result.right))
{
Node<Type> right = result.right;
if (height(right.right) < height(right.left))
{
result = new Node<>(result.value, result.left, right.rotateRight());
}
result = result.rotateLeft();
}
else
{
Node<Type> left = result.left;
if (height(left.left) < height(left.right))
{
result = new Node<>(result.value, left.rotateLeft(), result.right);
}
result = result.rotateRight();
}
}
return result;
}
public static <Type> Node<Type> clone(Node<Type> result)
{
if (result != null)
{
result = new Node<>(result.value, clone(result.left), clone(result.right));
}
return result;
}
public static <Type> Node<Type> delete(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = null;
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
if (node.left == null)
{
result = node.right;
}
else
{
if (node.right == null)
{
result = node.left;
}
else
{
Node<Type> first = first(node.right);
result = new Node<>(first.value, node.left, delete(node.right, first.value, comparator));
}
}
}
else
{
if (compare < 0)
{
result = new Node<>(node.value, delete(node.left, value, comparator), node.right);
}
else
{
result = new Node<>(node.value, node.left, delete(node.right, value, comparator));
}
}
result = balance(result);
}
return result;
}
public static <Type> Node<Type> first(Node<Type> result)
{
while (result.left != null)
{
result = result.left;
}
return result;
}
public static <Type> Node<Type> get(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = null;
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
result = node;
}
else
{
if (compare < 0)
{
result = get(node.left, value, comparator);
}
else
{
result = get(node.right, value, comparator);
}
}
}
return result;
}
public static <Type> Node<Type> head(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = null;
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
result = node.left;
}
else
{
if (compare < 0)
{
result = head(node.left, value, comparator);
}
else
{
result = new Node<>(node.value, node.left, head(node.right, value, comparator));
}
}
result = balance(result);
}
return result;
}
public static int height(Node node)
{
return node == null ? 0 : node.height;
}
public static <Type> Node<Type> insert(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = new Node<>(value, null, null);
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
result = new Node<>(value, node.left, node.right);
;
}
else
{
if (compare < 0)
{
result = new Node<>(node.value, insert(node.left, value, comparator), node.right);
}
else
{
result = new Node<>(node.value, node.left, insert(node.right, value, comparator));
}
}
result = balance(result);
}
return result;
}
public static <Type> Node<Type> last(Node<Type> result)
{
while (result.right != null)
{
result = result.right;
}
return result;
}
public static int size(Node node)
{
return node == null ? 0 : node.size;
}
public static <Type> Node<Type> tail(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = null;
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
result = new Node<>(node.value, null, node.right);
}
else
{
if (compare < 0)
{
result = new Node<>(node.value, tail(node.left, value, comparator), node.right);
}
else
{
result = tail(node.right, value, comparator);
}
}
result = balance(result);
}
return result;
}
public static <Type> void traverseOrderIn(Node<Type> node, Consumer<Type> consumer)
{
if (node != null)
{
traverseOrderIn(node.left, consumer);
consumer.accept(node.value);
traverseOrderIn(node.right, consumer);
}
}
public final Type value;
public final Node<Type> left;
public final Node<Type> right;
public final int size;
private final int height;
public Node(Type value, Node<Type> left, Node<Type> right)
{
this.value = value;
this.left = left;
this.right = right;
this.size = 1 + size(left) + size(right);
this.height = 1 + Math.max(height(left), height(right));
}
public Node<Type> rotateLeft()
{
Node<Type> left = new Node<>(this.value, this.left, this.right.left);
return new Node<>(this.right.value, left, this.right.right);
}
public Node<Type> rotateRight()
{
Node<Type> right = new Node<>(this.value, this.left.right, this.right);
return new Node<>(this.left.value, this.left.left, right);
}
}
public static class SingleLinkedList<Type>
{
public final Type element;
public SingleLinkedList<Type> next;
public SingleLinkedList(Type element, SingleLinkedList<Type> next)
{
this.element = element;
this.next = next;
}
public void toCollection(Collection<Type> collection)
{
if (this.next != null)
{
this.next.toCollection(collection);
}
collection.add(this.element);
}
}
public static class SmallSetIntegers
{
public static final int SIZE = 20;
public static final int[] SET = generateSet();
public static final int[] COUNT = generateCount();
public static final int[] INTEGER = generateInteger();
private static int count(int set)
{
int result = 0;
for (int integer = 0; integer < SIZE; integer++)
{
if (0 < (set & set(integer)))
{
result += 1;
}
}
return result;
}
private static final int[] generateCount()
{
int[] result = new int[1 << SIZE];
for (int set = 0; set < result.length; set++)
{
result[set] = count(set);
}
return result;
}
private static final int[] generateInteger()
{
int[] result = new int[1 << SIZE];
Arrays.fill(result, -1);
for (int integer = 0; integer < SIZE; integer++)
{
result[SET[integer]] = integer;
}
return result;
}
private static final int[] generateSet()
{
int[] result = new int[SIZE];
for (int integer = 0; integer < result.length; integer++)
{
result[integer] = set(integer);
}
return result;
}
private static int set(int integer)
{
return 1 << integer;
}
}
public static class SortedMapAVL<TypeKey, TypeValue> implements SortedMap<TypeKey, TypeValue>
{
public final Comparator<? super TypeKey> comparator;
public final SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet;
public SortedMapAVL(Comparator<? super TypeKey> comparator)
{
this(comparator, new SortedSetAVL<>((entry0, entry1) -> comparator.compare(entry0.getKey(), entry1.getKey())));
}
private SortedMapAVL(Comparator<? super TypeKey> comparator, SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet)
{
this.comparator = comparator;
this.entrySet = entrySet;
}
@Override
public void clear()
{
this.entrySet.clear();
}
@Override
public Comparator<? super TypeKey> comparator()
{
return this.comparator;
}
@Override
public boolean containsKey(Object key)
{
return this.entrySet().contains(new AbstractMap.SimpleEntry<>((TypeKey) key, null));
}
@Override
public boolean containsValue(Object value)
{
throw new UnsupportedOperationException();
}
@Override
public SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet()
{
return this.entrySet;
}
public Entry<TypeKey, TypeValue> firstEntry()
{
return this.entrySet.first();
}
@Override
public TypeKey firstKey()
{
return firstEntry().getKey();
}
@Override
public TypeValue get(Object key)
{
Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>((TypeKey) key, null);
entry = this.entrySet.get(entry);
return entry == null ? null : entry.getValue();
}
@Override
public SortedMapAVL<TypeKey, TypeValue> headMap(TypeKey keyEnd)
{
return new SortedMapAVL<>(this.comparator, this.entrySet.headSet(new AbstractMap.SimpleEntry<>(keyEnd, null)));
}
@Override
public boolean isEmpty()
{
return this.entrySet.isEmpty();
}
@Override
public Set<TypeKey> keySet()
{
return new SortedSet<TypeKey>()
{
@Override
public boolean add(TypeKey typeKey)
{
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends TypeKey> collection)
{
throw new UnsupportedOperationException();
}
@Override
public void clear()
{
throw new UnsupportedOperationException();
}
@Override
public Comparator<? super TypeKey> comparator()
{
throw new UnsupportedOperationException();
}
@Override
public boolean contains(Object o)
{
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public TypeKey first()
{
throw new UnsupportedOperationException();
}
@Override
public SortedSet<TypeKey> headSet(TypeKey typeKey)
{
throw new UnsupportedOperationException();
}
@Override
public boolean isEmpty()
{
return size() == 0;
}
@Override
public Iterator<TypeKey> iterator()
{
final Iterator<Entry<TypeKey, TypeValue>> iterator = SortedMapAVL.this.entrySet.iterator();
return new Iterator<TypeKey>()
{
@Override
public boolean hasNext()
{
return iterator.hasNext();
}
@Override
public TypeKey next()
{
return iterator.next().getKey();
}
};
}
@Override
public TypeKey last()
{
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o)
{
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public int size()
{
return SortedMapAVL.this.entrySet.size();
}
@Override
public SortedSet<TypeKey> subSet(TypeKey typeKey, TypeKey e1)
{
throw new UnsupportedOperationException();
}
@Override
public SortedSet<TypeKey> tailSet(TypeKey typeKey)
{
throw new UnsupportedOperationException();
}
@Override
public Object[] toArray()
{
throw new UnsupportedOperationException();
}
@Override
public <T> T[] toArray(T[] ts)
{
throw new UnsupportedOperationException();
}
};
}
public Entry<TypeKey, TypeValue> lastEntry()
{
return this.entrySet.last();
}
@Override
public TypeKey lastKey()
{
return lastEntry().getKey();
}
@Override
public TypeValue put(TypeKey key, TypeValue value)
{
TypeValue result = get(key);
Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>(key, value);
this.entrySet().add(entry);
return result;
}
@Override
public void putAll(Map<? extends TypeKey, ? extends TypeValue> map)
{
map.entrySet()
.forEach(entry -> put(entry.getKey(), entry.getValue()));
}
@Override
public TypeValue remove(Object key)
{
TypeValue result = get(key);
Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>((TypeKey) key, null);
this.entrySet.remove(entry);
return result;
}
@Override
public int size()
{
return this.entrySet().size();
}
@Override
public SortedMapAVL<TypeKey, TypeValue> subMap(TypeKey keyStart, TypeKey keyEnd)
{
return new SortedMapAVL<>(this.comparator, this.entrySet.subSet(new AbstractMap.SimpleEntry<>(keyStart, null), new AbstractMap.SimpleEntry<>(keyEnd, null)));
}
@Override
public SortedMapAVL<TypeKey, TypeValue> tailMap(TypeKey keyStart)
{
return new SortedMapAVL<>(this.comparator, this.entrySet.tailSet(new AbstractMap.SimpleEntry<>(keyStart, null)));
}
@Override
public String toString()
{
return this.entrySet().toString();
}
@Override
public Collection<TypeValue> values()
{
return new Collection<TypeValue>()
{
@Override
public boolean add(TypeValue typeValue)
{
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends TypeValue> collection)
{
throw new UnsupportedOperationException();
}
@Override
public void clear()
{
throw new UnsupportedOperationException();
}
@Override
public boolean contains(Object value)
{
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public boolean isEmpty()
{
return SortedMapAVL.this.entrySet.isEmpty();
}
@Override
public Iterator<TypeValue> iterator()
{
return new Iterator<TypeValue>()
{
Iterator<Entry<TypeKey, TypeValue>> iterator = SortedMapAVL.this.entrySet.iterator();
@Override
public boolean hasNext()
{
return this.iterator.hasNext();
}
@Override
public TypeValue next()
{
return this.iterator.next().getValue();
}
};
}
@Override
public boolean remove(Object o)
{
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public int size()
{
return SortedMapAVL.this.entrySet.size();
}
@Override
public Object[] toArray()
{
throw new UnsupportedOperationException();
}
@Override
public <T> T[] toArray(T[] ts)
{
throw new UnsupportedOperationException();
}
};
}
}
public static class SortedSetAVL<Type> implements SortedSet<Type>
{
public Comparator<? super Type> comparator;
public Node<Type> root;
private SortedSetAVL(Comparator<? super Type> comparator, Node<Type> root)
{
this.comparator = comparator;
this.root = root;
}
public SortedSetAVL(Comparator<? super Type> comparator)
{
this(comparator, null);
}
public SortedSetAVL(Collection<? extends Type> collection, Comparator<? super Type> comparator)
{
this(comparator, null);
this.addAll(collection);
}
public SortedSetAVL(SortedSetAVL<Type> sortedSetAVL)
{
this(sortedSetAVL.comparator, Node.clone(sortedSetAVL.root));
}
@Override
public boolean add(Type value)
{
int sizeBefore = size();
this.root = Node.insert(this.root, value, this.comparator);
return sizeBefore != size();
}
@Override
public boolean addAll(Collection<? extends Type> collection)
{
return collection.stream()
.map(this::add)
.reduce(true, (x, y) -> x | y);
}
@Override
public void clear()
{
this.root = null;
}
@Override
public Comparator<? super Type> comparator()
{
return this.comparator;
}
@Override
public boolean contains(Object value)
{
return Node.get(this.root, (Type) value, this.comparator) != null;
}
@Override
public boolean containsAll(Collection<?> collection)
{
return collection.stream()
.allMatch(this::contains);
}
@Override
public Type first()
{
return Node.first(this.root).value;
}
public Type get(Type value)
{
Node<Type> node = Node.get(this.root, value, this.comparator);
return node == null ? null : node.value;
}
@Override
public SortedSetAVL<Type> headSet(Type valueEnd)
{
return new SortedSetAVL<>(this.comparator, Node.head(this.root, valueEnd, this.comparator));
}
@Override
public boolean isEmpty()
{
return this.root == null;
}
@Override
public Iterator<Type> iterator()
{
Stack<Node<Type>> path = new Stack<>();
return new Iterator<Type>()
{
{
push(SortedSetAVL.this.root);
}
@Override
public boolean hasNext()
{
return !path.isEmpty();
}
@Override
public Type next()
{
if (path.isEmpty())
{
throw new NoSuchElementException();
}
else
{
Node<Type> node = path.peek();
Type result = node.value;
if (node.right != null)
{
push(node.right);
}
else
{
do
{
node = path.pop();
}
while (!path.isEmpty() && path.peek().right == node);
}
return result;
}
}
public void push(Node<Type> node)
{
while (node != null)
{
path.push(node);
node = node.left;
}
}
};
}
@Override
public Type last()
{
return Node.last(this.root).value;
}
@Override
public boolean remove(Object value)
{
int sizeBefore = size();
this.root = Node.delete(this.root, (Type) value, this.comparator);
return sizeBefore != size();
}
@Override
public boolean removeAll(Collection<?> collection)
{
return collection.stream()
.map(this::remove)
.reduce(true, (x, y) -> x | y);
}
@Override
public boolean retainAll(Collection<?> collection)
{
SortedSetAVL<Type> set = new SortedSetAVL<>(this.comparator);
collection.stream()
.map(element -> (Type) element)
.filter(this::contains)
.forEach(set::add);
boolean result = size() != set.size();
this.root = set.root;
return result;
}
@Override
public int size()
{
return this.root == null ? 0 : this.root.size;
}
@Override
public SortedSetAVL<Type> subSet(Type valueStart, Type valueEnd)
{
return tailSet(valueStart).headSet(valueEnd);
}
@Override
public SortedSetAVL<Type> tailSet(Type valueStart)
{
return new SortedSetAVL<>(this.comparator, Node.tail(this.root, valueStart, this.comparator));
}
@Override
public Object[] toArray()
{
return toArray(new Object[0]);
}
@Override
public <T> T[] toArray(T[] ts)
{
List<Object> list = new ArrayList<>();
Node.traverseOrderIn(this.root, list::add);
return list.toArray(ts);
}
@Override
public String toString()
{
return "{" + F_455.toString(this, ", ") + "}";
}
}
public static class Tree2D
{
public static final int SIZE = 1 << 30;
public static final Tree2D[] TREES_NULL = new Tree2D[] { null, null, null, null };
public static boolean contains(int x, int y, int left, int bottom, int size)
{
return left <= x && x < left + size && bottom <= y && y < bottom + size;
}
public static int count(Tree2D[] trees)
{
int result = 0;
for (int index = 0; index < 4; index++)
{
if (trees[index] != null)
{
result += trees[index].count;
}
}
return result;
}
public static int count
(
int rectangleLeft,
int rectangleBottom,
int rectangleRight,
int rectangleTop,
Tree2D tree,
int left,
int bottom,
int size
)
{
int result;
if (tree == null)
{
result = 0;
}
else
{
int right = left + size;
int top = bottom + size;
int intersectionLeft = Math.max(rectangleLeft, left);
int intersectionBottom = Math.max(rectangleBottom, bottom);
int intersectionRight = Math.min(rectangleRight, right);
int intersectionTop = Math.min(rectangleTop, top);
if (intersectionRight <= intersectionLeft || intersectionTop <= intersectionBottom)
{
result = 0;
}
else
{
if (intersectionLeft == left && intersectionBottom == bottom && intersectionRight == right && intersectionTop == top)
{
result = tree.count;
}
else
{
size = size >> 1;
result = 0;
for (int index = 0; index < 4; index++)
{
result += count
(
rectangleLeft,
rectangleBottom,
rectangleRight,
rectangleTop,
tree.trees[index],
quadrantLeft(left, size, index),
quadrantBottom(bottom, size, index),
size
);
}
}
}
}
return result;
}
public static int quadrantBottom(int bottom, int size, int index)
{
return bottom + (index >> 1) * size;
}
public static int quadrantLeft(int left, int size, int index)
{
return left + (index & 1) * size;
}
public final Tree2D[] trees;
public final int count;
private Tree2D(Tree2D[] trees, int count)
{
this.trees = trees;
this.count = count;
}
public Tree2D(Tree2D[] trees)
{
this(trees, count(trees));
}
public Tree2D()
{
this(TREES_NULL);
}
public int count(int rectangleLeft, int rectangleBottom, int rectangleRight, int rectangleTop)
{
return count
(
rectangleLeft,
rectangleBottom,
rectangleRight,
rectangleTop,
this,
0,
0,
SIZE
);
}
public Tree2D setPoint
(
int x,
int y,
Tree2D tree,
int left,
int bottom,
int size
)
{
Tree2D result;
if (contains(x, y, left, bottom, size))
{
if (size == 1)
{
result = new Tree2D(TREES_NULL, 1);
}
else
{
size = size >> 1;
Tree2D[] trees = new Tree2D[4];
for (int index = 0; index < 4; index++)
{
trees[index] = setPoint
(
x,
y,
tree == null ? null : tree.trees[index],
quadrantLeft(left, size, index),
quadrantBottom(bottom, size, index),
size
);
}
result = new Tree2D(trees);
}
}
else
{
result = tree;
}
return result;
}
public Tree2D setPoint(int x, int y)
{
return setPoint
(
x,
y,
this,
0,
0,
SIZE
);
}
}
public static class Tuple2<Type0, Type1>
{
public final Type0 v0;
public final Type1 v1;
public Tuple2(Type0 v0, Type1 v1)
{
this.v0 = v0;
this.v1 = v1;
}
@Override
public String toString()
{
return "(" + this.v0 + ", " + this.v1 + ")";
}
}
public static class Tuple2Comparable<Type0 extends Comparable<? super Type0>, Type1 extends Comparable<? super Type1>> extends Tuple2<Type0, Type1> implements Comparable<Tuple2Comparable<Type0, Type1>>
{
public Tuple2Comparable(Type0 v0, Type1 v1)
{
super(v0, v1);
}
@Override
public int compareTo(Tuple2Comparable<Type0, Type1> that)
{
int result = this.v0.compareTo(that.v0);
if (result == 0)
{
result = this.v1.compareTo(that.v1);
}
return result;
}
}
public static class Tuple3<Type0, Type1, Type2>
{
public final Type0 v0;
public final Type1 v1;
public final Type2 v2;
public Tuple3(Type0 v0, Type1 v1, Type2 v2)
{
this.v0 = v0;
this.v1 = v1;
this.v2 = v2;
}
@Override
public String toString()
{
return "(" + this.v0 + ", " + this.v1 + ", " + this.v2 + ")";
}
}
public static class Vertex
<
TypeVertex extends Vertex<TypeVertex, TypeEdge>,
TypeEdge extends Edge<TypeVertex, TypeEdge>
>
implements Comparable<Vertex<? super TypeVertex, ? super TypeEdge>>
{
public static <
TypeVertex extends Vertex<TypeVertex, TypeEdge>,
TypeEdge extends Edge<TypeVertex, TypeEdge>,
TypeResult
> TypeResult breadthFirstSearch
(
TypeVertex vertex,
TypeEdge edge,
BiFunctionResult<TypeVertex, TypeEdge, TypeResult> function,
Array<Boolean> visited,
FIFO<TypeVertex> verticesNext,
FIFO<TypeEdge> edgesNext,
TypeResult result
)
{
if (!visited.get(vertex.index))
{
visited.set(vertex.index, true);
result = function.apply(vertex, edge, result);
for (TypeEdge edgeNext : vertex.edges)
{
TypeVertex vertexNext = edgeNext.other(vertex);
if (!visited.get(vertexNext.index))
{
verticesNext.push(vertexNext);
edgesNext.push(edgeNext);
}
}
}
return result;
}
public static <
TypeVertex extends Vertex<TypeVertex, TypeEdge>,
TypeEdge extends Edge<TypeVertex, TypeEdge>,
TypeResult
>
TypeResult breadthFirstSearch
(
Array<TypeVertex> vertices,
int indexVertexStart,
BiFunctionResult<TypeVertex, TypeEdge, TypeResult> function,
TypeResult result
)
{
Array<Boolean> visited = new Array<>(vertices.size(), false);
FIFO<TypeVertex> verticesNext = new FIFO<>();
verticesNext.push(vertices.get(indexVertexStart));
FIFO<TypeEdge> edgesNext = new FIFO<>();
edgesNext.push(null);
while (!verticesNext.isEmpty())
{
result = breadthFirstSearch(verticesNext.pop(), edgesNext.pop(), function, visited, verticesNext, edgesNext, result);
}
return result;
}
public static <
TypeVertex extends Vertex<TypeVertex, TypeEdge>,
TypeEdge extends Edge<TypeVertex, TypeEdge>
>
boolean
cycle
(
TypeVertex start,
SortedSet<TypeVertex> result
)
{
boolean cycle = false;
Stack<TypeVertex> stackVertex = new Stack<>();
Stack<TypeEdge> stackEdge = new Stack<>();
stackVertex.push(start);
stackEdge.push(null);
while (!stackVertex.isEmpty())
{
TypeVertex vertex = stackVertex.pop();
TypeEdge edge = stackEdge.pop();
if (!result.contains(vertex))
{
result.add(vertex);
for (TypeEdge otherEdge : vertex.edges)
{
if (otherEdge != edge)
{
TypeVertex otherVertex = otherEdge.other(vertex);
if (result.contains(otherVertex))
{
cycle = true;
}
else
{
stackVertex.push(otherVertex);
stackEdge.push(otherEdge);
}
}
}
}
}
return cycle;
}
public static <
TypeVertex extends Vertex<TypeVertex, TypeEdge>,
TypeEdge extends Edge<TypeVertex, TypeEdge>
>
SortedSet<TypeVertex>
depthFirstSearch
(
TypeVertex start,
BiConsumer<TypeVertex, TypeEdge> functionVisitPre,
BiConsumer<TypeVertex, TypeEdge> functionVisitPost
)
{
SortedSet<TypeVertex> result = new SortedSetAVL<>(Comparator.naturalOrder());
Stack<TypeVertex> stackVertex = new Stack<>();
Stack<TypeEdge> stackEdge = new Stack<>();
stackVertex.push(start);
stackEdge.push(null);
while (!stackVertex.isEmpty())
{
TypeVertex vertex = stackVertex.pop();
TypeEdge edge = stackEdge.pop();
if (result.contains(vertex))
{
functionVisitPost.accept(vertex, edge);
}
else
{
result.add(vertex);
stackVertex.push(vertex);
stackEdge.push(edge);
functionVisitPre.accept(vertex, edge);
for (TypeEdge otherEdge : vertex.edges)
{
TypeVertex otherVertex = otherEdge.other(vertex);
if (!result.contains(otherVertex))
{
stackVertex.push(otherVertex);
stackEdge.push(otherEdge);
}
}
}
}
return result;
}
public static <
TypeVertex extends Vertex<TypeVertex, TypeEdge>,
TypeEdge extends Edge<TypeVertex, TypeEdge>
>
SortedSet<TypeVertex>
depthFirstSearch
(
TypeVertex start,
Consumer<TypeVertex> functionVisitPreVertex,
Consumer<TypeVertex> functionVisitPostVertex
)
{
BiConsumer<TypeVertex, TypeEdge> functionVisitPreVertexEdge = (vertex, edge) ->
{
functionVisitPreVertex.accept(vertex);
};
BiConsumer<TypeVertex, TypeEdge> functionVisitPostVertexEdge = (vertex, edge) ->
{
functionVisitPostVertex.accept(vertex);
};
return depthFirstSearch(start, functionVisitPreVertexEdge, functionVisitPostVertexEdge);
}
public final int index;
public final List<TypeEdge> edges;
public Vertex(int index)
{
this.index = index;
this.edges = new ArrayList<>();
}
@Override
public int compareTo(Vertex<? super TypeVertex, ? super TypeEdge> that)
{
return Integer.compare(this.index, that.index);
}
@Override
public String toString()
{
return "" + this.index;
}
}
public static class VertexDefault<TypeEdge extends Edge<VertexDefault<TypeEdge>, TypeEdge>> extends Vertex<VertexDefault<TypeEdge>, TypeEdge>
{
public VertexDefault(int index)
{
super(index);
}
}
public static class VertexDefaultDefault extends Vertex<VertexDefaultDefault, EdgeDefaultDefault>
{
public static Array<VertexDefaultDefault> vertices(int n)
{
Array<VertexDefaultDefault> result = new Array<>(n);
for (int index = 0; index < n; index++)
{
result.set(index, new VertexDefaultDefault(index));
}
return result;
}
public VertexDefaultDefault(int index)
{
super(index);
}
}
public static class Wrapper<Type>
{
public Type value;
public Wrapper(Type value)
{
this.value = value;
}
public Type get()
{
return this.value;
}
public void set(Type value)
{
this.value = value;
}
@Override
public String toString()
{
return this.value.toString();
}
}
public static void add(int delta, int[] result)
{
for (int index = 0; index < result.length; index++)
{
result[index] += delta;
}
}
public static void add(int delta, int[]... result)
{
for (int index = 0; index < result.length; index++)
{
add(delta, result[index]);
}
}
public static int binarySearchMaximum(Function<Integer, Boolean> filter, int start, int end)
{
return -binarySearchMinimum(x -> filter.apply(-x), -end, -start);
}
public static int binarySearchMinimum(Function<Integer, Boolean> filter, int start, int end)
{
int result;
if (start == end)
{
result = end;
}
else
{
int middle = start + (end - start) / 2;
if (filter.apply(middle))
{
result = binarySearchMinimum(filter, start, middle);
}
else
{
result = binarySearchMinimum(filter, middle + 1, end);
}
}
return result;
}
public static void close()
{
out.close();
}
public static List<List<Integer>> combinations(int n, int k)
{
List<List<Integer>> result = new ArrayList<>();
if (k == 0)
{
}
else
{
if (k == 1)
{
List<Integer> combination = new ArrayList<>();
combination.add(n);
result.add(combination);
}
else
{
for (int index = 0; index <= n; index++)
{
for (List<Integer> combination : combinations(n - index, k - 1))
{
combination.add(index);
result.add(combination);
}
}
}
}
return result;
}
public static <Type> int compare(Iterator<Type> iterator0, Iterator<Type> iterator1, Comparator<Type> comparator)
{
int result = 0;
while (result == 0 && iterator0.hasNext() && iterator1.hasNext())
{
result = comparator.compare(iterator0.next(), iterator1.next());
}
if (result == 0)
{
if (iterator1.hasNext())
{
result = -1;
}
else
{
if (iterator0.hasNext())
{
result = 1;
}
}
}
return result;
}
public static <Type> int compare(Iterable<Type> iterable0, Iterable<Type> iterable1, Comparator<Type> comparator)
{
return compare(iterable0.iterator(), iterable1.iterator(), comparator);
}
public static long divideCeil(long x, long y)
{
return (x + y - 1) / y;
}
public static Set<Long> divisors(long n)
{
SortedSetAVL<Long> result = new SortedSetAVL<>(Comparator.naturalOrder());
result.add(1L);
for (Long factor : factors(n))
{
SortedSetAVL<Long> divisors = new SortedSetAVL<>(result);
for (Long divisor : result)
{
divisors.add(divisor * factor);
}
result = divisors;
}
return result;
}
public static LinkedList<Long> factors(long n)
{
LinkedList<Long> result = new LinkedList<>();
Iterator<Long> primes = ITERATOR_BUFFER_PRIME.iterator();
Long prime;
while (n > 1 && (prime = primes.next()) * prime <= n)
{
while (n % prime == 0)
{
result.add(prime);
n /= prime;
}
}
if (n > 1)
{
result.add(n);
}
return result;
}
public static long faculty(int n)
{
long result = 1;
for (int index = 2; index <= n; index++)
{
result *= index;
}
return result;
}
public static long gcd(long a, long b)
{
while (a != 0 && b != 0)
{
if (a > b)
{
a %= b;
}
else
{
b %= a;
}
}
return a + b;
}
public static long[] generatePOWER2()
{
long[] result = new long[63];
for (int x = 0; x < result.length; x++)
{
result[x] = 1L << x;
}
return result;
}
public static boolean isPrime(long x)
{
boolean result = x > 1;
Iterator<Long> iterator = ITERATOR_BUFFER_PRIME.iterator();
Long prime;
while ((prime = iterator.next()) * prime <= x)
{
result &= x % prime > 0;
}
return result;
}
public static long knapsack(List<Tuple3<Long, Integer, Integer>> itemsValueWeightCount, int weightMaximum)
{
long[] valuesMaximum = new long[weightMaximum + 1];
for (Tuple3<Long, Integer, Integer> itemValueWeightCount : itemsValueWeightCount)
{
long itemValue = itemValueWeightCount.v0;
int itemWeight = itemValueWeightCount.v1;
int itemCount = itemValueWeightCount.v2;
for (int weight = weightMaximum; 0 <= weight; weight--)
{
for (int index = 1; index <= itemCount && 0 <= weight - index * itemWeight; index++)
{
valuesMaximum[weight] = Math.max(valuesMaximum[weight], valuesMaximum[weight - index * itemWeight] + index * itemValue);
}
}
}
long result = 0;
for (long valueMaximum : valuesMaximum)
{
result = Math.max(result, valueMaximum);
}
return result;
}
public static boolean knapsackPossible(List<Tuple2<Integer, Integer>> itemsWeightCount, int weightMaximum)
{
boolean[] weightPossible = new boolean[weightMaximum + 1];
weightPossible[0] = true;
int weightLargest = 0;
for (Tuple2<Integer, Integer> itemWeightCount : itemsWeightCount)
{
int itemWeight = itemWeightCount.v0;
int itemCount = itemWeightCount.v1;
for (int weightStart = 0; weightStart < itemWeight; weightStart++)
{
int count = 0;
for (int weight = weightStart; weight <= weightMaximum && (0 < count || weight <= weightLargest); weight += itemWeight)
{
if (weightPossible[weight])
{
count = itemCount;
}
else
{
if (0 < count)
{
weightPossible[weight] = true;
weightLargest = weight;
count -= 1;
}
}
}
}
}
return weightPossible[weightMaximum];
}
public static long lcm(int a, int b)
{
return a * b / gcd(a, b);
}
public static void main(String[] args)
{
try
{
solve();
}
catch (IOException exception)
{
exception.printStackTrace();
}
close();
}
public static double nextDouble() throws IOException
{
return Double.parseDouble(nextString());
}
public static int nextInt() throws IOException
{
return Integer.parseInt(nextString());
}
public static void nextInts(int n, int[]... result) throws IOException
{
for (int index = 0; index < n; index++)
{
for (int value = 0; value < result.length; value++)
{
result[value][index] = nextInt();
}
}
}
public static int[] nextInts(int n) throws IOException
{
int[] result = new int[n];
nextInts(n, result);
return result;
}
public static String nextLine() throws IOException
{
return bufferedReader.readLine();
}
public static long nextLong() throws IOException
{
return Long.parseLong(nextString());
}
public static void nextLongs(int n, long[]... result) throws IOException
{
for (int index = 0; index < n; index++)
{
for (int value = 0; value < result.length; value++)
{
result[value][index] = nextLong();
}
}
}
public static long[] nextLongs(int n) throws IOException
{
long[] result = new long[n];
nextLongs(n, result);
return result;
}
public static String nextString() throws IOException
{
while ((stringTokenizer == null) || (!stringTokenizer.hasMoreTokens()))
{
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
}
return stringTokenizer.nextToken();
}
public static String[] nextStrings(int n) throws IOException
{
String[] result = new String[n];
{
for (int index = 0; index < n; index++)
{
result[index] = nextString();
}
}
return result;
}
public static <T> List<T> permutation(long p, List<T> x)
{
List<T> copy = new ArrayList<>();
for (int index = 0; index < x.size(); index++)
{
copy.add(x.get(index));
}
List<T> result = new ArrayList<>();
for (int indexTo = 0; indexTo < x.size(); indexTo++)
{
int indexFrom = (int) p % copy.size();
p = p / copy.size();
result.add(copy.remove(indexFrom));
}
return result;
}
public static <Type> List<List<Type>> permutations(List<Type> list)
{
List<List<Type>> result = new ArrayList<>();
result.add(new ArrayList<>());
for (Type element : list)
{
List<List<Type>> permutations = result;
result = new ArrayList<>();
for (List<Type> permutation : permutations)
{
for (int index = 0; index <= permutation.size(); index++)
{
List<Type> permutationNew = new ArrayList<>(permutation);
permutationNew.add(index, element);
result.add(permutationNew);
}
}
}
return result;
}
public static Stream<BigInteger> streamFibonacci()
{
return Stream.generate(new Supplier<BigInteger>()
{
private BigInteger n0 = BigInteger.ZERO;
private BigInteger n1 = BigInteger.ONE;
@Override
public BigInteger get()
{
BigInteger result = n0;
n0 = n1;
n1 = result.add(n0);
return result;
}
});
}
public static Stream<Long> streamPrime(int sieveSize)
{
return Stream.generate(new Supplier<Long>()
{
private boolean[] isPrime = new boolean[sieveSize];
private long sieveOffset = 2;
private List<Long> primes = new ArrayList<>();
private int index = 0;
public void filter(long prime, boolean[] result)
{
if (prime * prime < this.sieveOffset + sieveSize)
{
long remainingStart = this.sieveOffset % prime;
long start = remainingStart == 0 ? 0 : prime - remainingStart;
for (long index = start; index < sieveSize; index += prime)
{
result[(int) index] = false;
}
}
}
public void generatePrimes()
{
Arrays.fill(this.isPrime, true);
this.primes.forEach(prime -> filter(prime, isPrime));
for (int index = 0; index < sieveSize; index++)
{
if (isPrime[index])
{
this.primes.add(this.sieveOffset + index);
filter(this.sieveOffset + index, isPrime);
}
}
this.sieveOffset += sieveSize;
}
@Override
public Long get()
{
while (this.primes.size() <= this.index)
{
generatePrimes();
}
Long result = this.primes.get(this.index);
this.index += 1;
return result;
}
});
}
public static <Type> String toString(Iterator<Type> iterator, String separator)
{
StringBuilder stringBuilder = new StringBuilder();
if (iterator.hasNext())
{
stringBuilder.append(iterator.next());
}
while (iterator.hasNext())
{
stringBuilder.append(separator);
stringBuilder.append(iterator.next());
}
return stringBuilder.toString();
}
public static <Type> String toString(Iterator<Type> iterator)
{
return toString(iterator, " ");
}
public static <Type> String toString(Iterable<Type> iterable, String separator)
{
return toString(iterable.iterator(), separator);
}
public static <Type> String toString(Iterable<Type> iterable)
{
return toString(iterable, " ");
}
public static long totient(long n)
{
Set<Long> factors = new SortedSetAVL<>(factors(n), Comparator.naturalOrder());
long result = n;
for (long p : factors)
{
result -= result / p;
}
return result;
}
interface BiFunctionResult<Type0, Type1, TypeResult>
{
TypeResult apply(Type0 x0, Type1 x1, TypeResult x2);
}
public static int msb(int x)
{
int result;
if (x == 1)
{
result = 0;
}
else
{
result = 1 + msb(x >> 1);
}
return result;
}
public static List<Integer> range(int start, int end)
{
List<Integer> result = new ArrayList<>();
for (int index = start; index < end; index++)
{
result.add(index);
}
return result;
}
public static List<Integer> solveZero(final int N)
{
List<Integer> result;
boolean[] numbersUsed = new boolean[N + 1];
if (N % 2 == 0)
{
Integer[] permutation = new Integer[N];
for (int number = N; 0 < number; number--)
{
if (!numbersUsed[number])
{
int msb = msb(number);
int ones = (1 << (msb + 1)) - 1;
int otherNumber = ones ^ number;
permutation[number - 1] = otherNumber;
numbersUsed[number] = true;
permutation[otherNumber - 1] = number;
numbersUsed[otherNumber] = true;
}
}
result = Arrays.asList(permutation);
}
else
{
result = null;
}
return result;
}
public static int[] bits(int x)
{
List<Integer> bits = new ArrayList<>();
int bit = 0;
while (0 < x)
{
if (x % 2 == 1)
{
bits.add(bit);
}
x = x >> 1;
bit += 1;
}
int[] result = new int[bits.size()];
for (int index = 0; index < bits.size(); index++)
{
result[index] = bits.get(index);
}
return result;
}
public static final int[][] NUMBER2BITS = generateNUMBER2BITS(100000);
public static int[][] generateNUMBER2BITS(final int N)
{
int[][] result = new int[N + 1][];
for (int number = 0; number <= N; number++)
{
result[number] = bits(number);
}
return result;
}
public static boolean findIndexOther
(
Integer[] numbers,
int index,
SortedSet<Integer> indicesFree,
Integer start,
Integer[] permutation,
Stack<Integer> indicesOther
)
{
boolean result = false;
int number = numbers[index];
Iterator<Integer> iterator;
if (start == null)
{
iterator = indicesFree.iterator();
}
else
{
iterator = indicesFree.tailSet(start).iterator();
iterator.next();
}
while (!result && iterator.hasNext())
{
int indexOther = iterator.next();
int numberOther = numbers[indexOther];
if ((number != numberOther) && (0 < (number & numberOther)))
{
indicesFree.remove(indexOther);
permutation[number - 1] = numberOther;
indicesOther.add(indexOther);
result = true;
}
}
return result;
}
public static List<Integer> solveZeroNot(final int N)
{
Integer[] numbers = range(1, N + 1).toArray(new Integer[0]);
Comparator<Integer> comparator = new Comparator<Integer>()
{
@Override
public int compare(Integer x, Integer y)
{
int result = Integer.compare(NUMBER2BITS[x].length, NUMBER2BITS[y].length);
if (result == 0)
{
result = Integer.compare(y, x);
}
return result;
}
};
Arrays.sort(numbers, comparator);
List<Integer> result = null;
Integer[] permutation = new Integer[N];
Stack<Integer> indicesOther = new Stack<>();
SortedSet<Integer> indicesFree = new SortedSetAVL<>(comparator);
indicesFree.addAll(range(0, N));
do
{
int index = indicesOther.size();
if (index == numbers.length)
{
result = Arrays.asList(permutation);
}
else
{
if (!findIndexOther
(
numbers,
index,
indicesFree,
null,
permutation,
indicesOther
))
{
boolean next = false;
while (!indicesOther.isEmpty() && !next)
{
int indexOther = indicesOther.pop();
index = indicesOther.size();
indicesFree.add(indexOther);
next = findIndexOther
(
numbers,
index,
indicesFree,
indexOther,
permutation,
indicesOther
);
}
}
}
}
while (result == null && !indicesOther.isEmpty());
return result;
}
public static void print(List<Integer> solution)
{
if (solution == null)
{
out.println("NO");
}
else
{
out.println("YES");
out.println(toString(solution));
}
}
public static void solve() throws IOException
{
final int N = nextInt();
print(solveZero(N));
print(solveZeroNot(N));
}
} | Java | ["3", "6"] | 2 seconds | ["NO\nNO", "YES\n6 5 4 3 2 1 \nYES\n3 6 2 5 1 4"] | null | Java 8 | standard input | [
"constructive algorithms"
] | 581d08af78dc960f3212bdf01bc57167 | The input consists of one line containing a single integer N (1ββ€βNββ€β105). | 2,500 | For each subtask, if the required permutation doesn't exist, output a single line containing the word "NO"; otherwise output the word "YES" in the first line and N elements of the permutation, separated by spaces, in the second line. If there are several possible permutations in a subtask, output any of them. | standard output | |
PASSED | f5101bb487cb4199033d2e5e00a62a64 | train_003.jsonl | 1514392500 | Given an integer N, find two permutations: Permutation p of numbers from 1 to N such that piββ βi and piβ&βiβ=β0 for all iβ=β1,β2,β...,βN. Permutation q of numbers from 1 to N such that qiββ βi and qiβ&βiββ β0 for all iβ=β1,β2,β...,βN. & is the bitwise AND operation. | 256 megabytes | import java.util.Scanner;
public class F {
private static final int[] Q6 = {3, 6, 2, 5, 1, 4};
private static int N;
public static void main(String[] args) {
N = new Scanner(System.in).nextInt();
if (N % 2 == 0) {
int[] p = new int[N + 1];
int max = N;
int pow = Integer.highestOneBit(N);
while (max > 0) {
for (int i = 1; pow + i - 1 <= max; i++) {
int tmp1 = pow - i;
int tmp2 = pow + i - 1;
p[tmp1] = tmp2;
p[tmp2] = tmp1;
}
max = pow - (max - pow + 1) - 1;
pow = Integer.highestOneBit(max);
}
yes(p);
} else
System.out.println("NO");
if (N >= 6 && (N & (-N)) != N) {
int[] q = new int[N + 1];
for (int i = 1; i <= N; i++)
q[i] = i <= 6 ? Q6[i-1] : i;
for (int i = 7; i <= N; i++) {
int j = Integer.highestOneBit(i);
q[i] = q[j];
q[j] = i;
}
yes(q);
} else
System.out.println("NO");
}
private static void yes(int[] perm) {
System.out.println("YES");
for (int i = 1; i <= N; i++)
System.out.print(perm[i] + " ");
System.out.println();
}
}
| Java | ["3", "6"] | 2 seconds | ["NO\nNO", "YES\n6 5 4 3 2 1 \nYES\n3 6 2 5 1 4"] | null | Java 8 | standard input | [
"constructive algorithms"
] | 581d08af78dc960f3212bdf01bc57167 | The input consists of one line containing a single integer N (1ββ€βNββ€β105). | 2,500 | For each subtask, if the required permutation doesn't exist, output a single line containing the word "NO"; otherwise output the word "YES" in the first line and N elements of the permutation, separated by spaces, in the second line. If there are several possible permutations in a subtask, output any of them. | standard output | |
PASSED | 943e75e3b7e5e920f16b2abcb0400855 | train_003.jsonl | 1514392500 | Given an integer N, find two permutations: Permutation p of numbers from 1 to N such that piββ βi and piβ&βiβ=β0 for all iβ=β1,β2,β...,βN. Permutation q of numbers from 1 to N such that qiββ βi and qiβ&βiββ β0 for all iβ=β1,β2,β...,βN. & is the bitwise AND operation. | 256 megabytes | //package round455;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.BitSet;
import java.util.InputMismatchException;
public class F {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
if(n % 2 == 1){
out.println("NO");
}else{
out.println("YES");
int t = n;
int[] a = new int[n];
int p = n-1;
while(p >= 0){
int h = Integer.highestOneBit(t)*2;
for(int i = 0;h-t+i-1 <= t;i++){
a[p--] = h-t+i-1;
}
t = p+1;
}
for(int v : a){
out.print(v + " ");
}
out.println();
// check(a);
}
if(Integer.bitCount(n) == 1 || n < 6){
out.println("NO");
}else if(n == 6){
out.println("YES");
out.println("3 6 2 5 1 4");
}else if(n == 7){
out.println("YES");
out.println("3 6 2 5 1 7 4");
}else{
out.println("YES");
out.print("3 6 2 5 1 7 4 ");
for(int d = 8;;d*=2){
int max = Math.min(d*2-1, n);
out.print(max + " ");
for(int e = d;e < max;e++){
out.print(e + " ");
}
if(max == n)break;
}
out.println();
}
}
void check(int[] a)
{
BitSet bs = new BitSet();
for(int i = 0;i < a.length;i++){
if((a[i]&(i+1)) != 0)throw new RuntimeException();
bs.set(a[i]);
if(a[i] < 1)throw new RuntimeException();
if(a[i] > a.length)throw new RuntimeException();
}
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new F().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| Java | ["3", "6"] | 2 seconds | ["NO\nNO", "YES\n6 5 4 3 2 1 \nYES\n3 6 2 5 1 4"] | null | Java 8 | standard input | [
"constructive algorithms"
] | 581d08af78dc960f3212bdf01bc57167 | The input consists of one line containing a single integer N (1ββ€βNββ€β105). | 2,500 | For each subtask, if the required permutation doesn't exist, output a single line containing the word "NO"; otherwise output the word "YES" in the first line and N elements of the permutation, separated by spaces, in the second line. If there are several possible permutations in a subtask, output any of them. | standard output | |
PASSED | db7c10080aca216590a7fa27dc26b591 | train_003.jsonl | 1514392500 | Given an integer N, find two permutations: Permutation p of numbers from 1 to N such that piββ βi and piβ&βiβ=β0 for all iβ=β1,β2,β...,βN. Permutation q of numbers from 1 to N such that qiββ βi and qiβ&βiββ β0 for all iβ=β1,β2,β...,βN. & is the bitwise AND operation. | 256 megabytes | /*
Keep solving problems.
*/
import java.util.*;
import java.io.*;
public class CFA {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
private static final long MOD = 1000 * 1000 * 1000 + 7;
private static final int[] dx = {0, -1, 0, 1};
private static final int[] dy = {1, 0, -1, 0};
private static final String yes = "YES";
private static final String no = "NO";
void solve() throws IOException {
int n = nextInt();
solve1(n);
solve2(n);
}
void solve1(int n) {
if (n % 2 == 1) {
outln(no);
return;
}
int[] res = new int[n];
while (n > 0) {
int start = 1;
while (start <= n) {
start = 2 * start;
}
start = start / 2;
int i = 0;
while (i + start <= n) {
int left = start - 1 - i;
int right = start + i;
res[left - 1] = right;
res[right - 1] = left;
i++;
}
n = start - 1 - i;
}
outln(yes);
for (int i = 0; i < res.length; i++) {
out(res[i] + " ");
}
outln("");
}
void solve2(int n) {
if (n <= 5) {
outln(no);
return;
}
int[] res6 = {3, 6, 2, 5, 1, 4};
int[] res7 = {7, 3, 6, 5, 1, 2, 4};
if (n == 6) {
outln(yes);
for (int i = 0; i < n; i++) {
out(res6[i] + " ");
}
return;
}
else if (n == 7) {
outln(yes);
for (int i = 0; i < n; i++) {
out(res7[i] + " ");
}
return;
}
int start = 1;
while (start <= n) {
start = 2 * start;
}
start = start / 2;
if (start == n) {
out(no);
return;
}
int[] res = new int[n];
for (int i = 0; i < 7; i++) {
res[i] = res7[i];
}
start = 8;
while (start <= n) {
int left = start;
int right = start * 2 - 1;
right = Math.min(right, n);
for (int i = left; i < right; i++) {
res[i - 1] = i + 1;
}
res[right - 1] = left;
start = right + 1;
}
outln(yes);
for (int i = 0; i < n; i++) {
out(res[i] + " ");
}
}
void shuffle(int[] a) {
int n = a.length;
for(int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
int gcd(int a, int b) {
while(a != 0 && b != 0) {
int c = b;
b = a % b;
a = c;
}
return a + b;
}
private void outln(Object o) {
out.println(o);
}
private void out(Object o) {
out.print(o);
}
public CFA() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new CFA();
}
public long[] nextLongArr(int n) throws IOException{
long[] res = new long[n];
for(int i = 0; i < n; i++)
res[i] = nextLong();
return res;
}
public int[] nextIntArr(int n) throws IOException {
int[] res = new int[n];
for(int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
public String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
| Java | ["3", "6"] | 2 seconds | ["NO\nNO", "YES\n6 5 4 3 2 1 \nYES\n3 6 2 5 1 4"] | null | Java 8 | standard input | [
"constructive algorithms"
] | 581d08af78dc960f3212bdf01bc57167 | The input consists of one line containing a single integer N (1ββ€βNββ€β105). | 2,500 | For each subtask, if the required permutation doesn't exist, output a single line containing the word "NO"; otherwise output the word "YES" in the first line and N elements of the permutation, separated by spaces, in the second line. If there are several possible permutations in a subtask, output any of them. | standard output | |
PASSED | cca7508fee202ce63d29572725607c73 | train_003.jsonl | 1514392500 | Given an integer N, find two permutations: Permutation p of numbers from 1 to N such that piββ βi and piβ&βiβ=β0 for all iβ=β1,β2,β...,βN. Permutation q of numbers from 1 to N such that qiββ βi and qiβ&βiββ β0 for all iβ=β1,β2,β...,βN. & is the bitwise AND operation. | 256 megabytes | import java.io.*;
import java.util.*;
public class utkarsh{
BufferedReader br;
PrintWriter out;
void solve(){
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
int n = ni();
if(n%2 == 1){
out.println("NO");
}else{
out.println("YES");
int a[] = new int[n+1];
int l, r, m = n;
while(m > 0){
//System.out.println(m);
r = 1;
while(r <= m) r <<= 1;
r >>= 1;
l = r-1;
while(r <= m){
a[l] = r;
a[r] = l;
r++;
l--;
}
m = l;
}
for(int i = 1; i <= n; i++) out.print(a[i] + " ");
out.println();
}
if(n <= 5 || (n & (n-1)) == 0){
out.println("NO");
}else if(n == 6){
out.println("YES\n3 6 2 5 1 4");
}else if(n == 7){
out.println("YES\n7 3 6 5 1 2 4");
}else{
out.println("YES\n7 3 6 5 1 2 4 ");
int x = 8;
while(true){
int m = Math.min(n, x - 1 + x);
out.print(m + " ");
for(int i = x; i < m; i++) out.print(i + " ");
if(m == n) break;
x <<= 1;
}
out.println();
}
out.flush();
}
int ni(){
return Integer.parseInt(ns());
}
String ip[];
int len, sz;
String ns(){
if(len >= sz){
try{
ip = br.readLine().split(" ");
len = 0;
sz = ip.length;
}catch(IOException e){
throw new InputMismatchException();
}
if(sz <= 0) return "-1";
}
return ip[len++];
}
public static void main(String[] args){ new utkarsh().solve(); }
} | Java | ["3", "6"] | 2 seconds | ["NO\nNO", "YES\n6 5 4 3 2 1 \nYES\n3 6 2 5 1 4"] | null | Java 8 | standard input | [
"constructive algorithms"
] | 581d08af78dc960f3212bdf01bc57167 | The input consists of one line containing a single integer N (1ββ€βNββ€β105). | 2,500 | For each subtask, if the required permutation doesn't exist, output a single line containing the word "NO"; otherwise output the word "YES" in the first line and N elements of the permutation, separated by spaces, in the second line. If there are several possible permutations in a subtask, output any of them. | standard output | |
PASSED | 5345090651a4b6b0f3d640acc1e44bde | train_003.jsonl | 1433595600 | There are n cities in Westeros. The i-th city is inhabited by ai people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly k cities left.The prophecy says that if the total number of surviving residents is even, then Daenerys wins: Stannis gets beheaded, and Daenerys rises on the Iron Throne. If the total number of surviving residents is odd, Stannis wins and everything goes in the completely opposite way.Lord Petyr Baelish wants to know which candidates to the throne he should support, and therefore he wonders, which one of them has a winning strategy. Answer to this question of Lord Baelish and maybe you will become the next Lord of Harrenholl. | 256 megabytes |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* #
* @author pttrung
*/
public class C_LC_2015 {
public static long MOD = 1000000007;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
int k = in.nextInt();
int odd = 0;
int even = 0;
for (int i = 0; i < n; i++) {
if (in.nextInt() % 2 == 0) {
even++;
} else {
odd++;
}
}
int turn = n - k;
int d = turn / 2;
int s = turn - d;
if (n == k) {
if (odd % 2 != 0) {
out.println("Stannis");
} else {
out.println("Daenerys");
}
} else if (d >= odd) {
out.println("Daenerys");
} else {
if (s > d) {
if (d >= even && (odd - (turn - even)) % 2 == 0) {
out.println("Daenerys");
} else {
out.println("Stannis");
}
} else {
if (s >= even && (odd - (turn - even)) % 2 != 0) {
out.println("Stannis");
} else {
out.println("Daenerys");
}
}
}
out.close();
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point implements Comparable<Point> {
int x, y;
public Point(int start, int end) {
this.x = start;
this.y = end;
}
@Override
public int hashCode() {
int hash = 5;
hash = 47 * hash + this.x;
hash = 47 * hash + this.y;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Point other = (Point) obj;
if (this.x != other.x) {
return false;
}
if (this.y != other.y) {
return false;
}
return true;
}
@Override
public int compareTo(Point o) {
return x - o.x;
}
}
public static class FT {
long[] data;
FT(int n) {
data = new long[n];
}
public void update(int index, long value) {
while (index < data.length) {
data[index] += value;
index += (index & (-index));
}
}
public long get(int index) {
long result = 0;
while (index > 0) {
result += data[index];
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, long b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2);
if (b % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * a % MOD) % MOD;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
| Java | ["3 1\n1 2 1", "3 1\n2 2 1", "6 3\n5 20 12 7 14 101"] | 1 second | ["Stannis", "Daenerys", "Stannis"] | NoteIn the first sample Stannis will use his move to burn a city with two people and Daenerys will be forced to burn a city with one resident. The only survivor city will have one resident left, that is, the total sum is odd, and thus Stannis wins.In the second sample, if Stannis burns a city with two people, Daenerys burns the city with one resident, or vice versa. In any case, the last remaining city will be inhabited by two people, that is, the total sum is even, and hence Daenerys wins. | Java 7 | standard input | [
"games"
] | 67e51db4d96b9f7996aea73cbdba3584 | The first line contains two positive space-separated integers, n and k (1ββ€βkββ€βnββ€β2Β·105) β the initial number of cities in Westeros and the number of cities at which the game ends. The second line contains n space-separated positive integers ai (1ββ€βaiββ€β106), which represent the population of each city in Westeros. | 2,200 | Print string "Daenerys" (without the quotes), if Daenerys wins and "Stannis" (without the quotes), if Stannis wins. | standard output | |
PASSED | f3f3ff2fb4b90e720e147e524899dc4c | train_003.jsonl | 1433595600 | There are n cities in Westeros. The i-th city is inhabited by ai people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly k cities left.The prophecy says that if the total number of surviving residents is even, then Daenerys wins: Stannis gets beheaded, and Daenerys rises on the Iron Throne. If the total number of surviving residents is odd, Stannis wins and everything goes in the completely opposite way.Lord Petyr Baelish wants to know which candidates to the throne he should support, and therefore he wonders, which one of them has a winning strategy. Answer to this question of Lord Baelish and maybe you will become the next Lord of Harrenholl. | 256 megabytes | import java.util.*;
import java.io.*;
public class Codeforces {
public static void main(String[] args) throws IOException {
Reader.init(System.in);
int n = Reader.nextInt(), k = Reader.nextInt();
int odd = 0, even = 0;
for(int i = 0; i < n; i++){
if(Reader.nextInt() % 2 == 0)
even++;
else
odd++;
}
if(k == n){
if(odd % 2 == 0)
System.out.println("Daenerys");
else
System.out.println("Stannis");
return;
}
if((n-k) % 2 == 0){
if(even <= (n-k)/2){
if((k+1) % 2 == 0)
System.out.println("Stannis");
else
System.out.println("Daenerys");
}
else
System.out.println("Daenerys");
}
else{
if(odd <= (n-k)/2){
System.out.println("Daenerys");
}
else {
if(even <= (n-k)/2){
if((k+1) % 2 == 0)
System.out.println("Stannis");
else
System.out.println("Daenerys");
}
else{
System.out.println("Stannis");
}
}
}
}
}
class Pair implements Comparable<Pair>{
int x;
int index;
Pair(int a, int b){
x = a;
index = b;
}
@Override
public int compareTo(Pair t) {
return x - t.x;
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
public static int pars(String x) {
int num = 0;
int i = 0;
if (x.charAt(0) == '-') {
i = 1;
}
for (; i < x.length(); i++) {
num = num * 10 + (x.charAt(i) - '0');
}
if (x.charAt(0) == '-') {
return -num;
}
return num;
}
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
static void init(FileReader input) {
reader = new BufferedReader(input);
tokenizer = new StringTokenizer("");
}
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(
reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return pars(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
} | Java | ["3 1\n1 2 1", "3 1\n2 2 1", "6 3\n5 20 12 7 14 101"] | 1 second | ["Stannis", "Daenerys", "Stannis"] | NoteIn the first sample Stannis will use his move to burn a city with two people and Daenerys will be forced to burn a city with one resident. The only survivor city will have one resident left, that is, the total sum is odd, and thus Stannis wins.In the second sample, if Stannis burns a city with two people, Daenerys burns the city with one resident, or vice versa. In any case, the last remaining city will be inhabited by two people, that is, the total sum is even, and hence Daenerys wins. | Java 7 | standard input | [
"games"
] | 67e51db4d96b9f7996aea73cbdba3584 | The first line contains two positive space-separated integers, n and k (1ββ€βkββ€βnββ€β2Β·105) β the initial number of cities in Westeros and the number of cities at which the game ends. The second line contains n space-separated positive integers ai (1ββ€βaiββ€β106), which represent the population of each city in Westeros. | 2,200 | Print string "Daenerys" (without the quotes), if Daenerys wins and "Stannis" (without the quotes), if Stannis wins. | standard output | |
PASSED | a8a78b591b938fa187f9b552ea29850b | train_003.jsonl | 1433595600 | There are n cities in Westeros. The i-th city is inhabited by ai people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly k cities left.The prophecy says that if the total number of surviving residents is even, then Daenerys wins: Stannis gets beheaded, and Daenerys rises on the Iron Throne. If the total number of surviving residents is odd, Stannis wins and everything goes in the completely opposite way.Lord Petyr Baelish wants to know which candidates to the throne he should support, and therefore he wonders, which one of them has a winning strategy. Answer to this question of Lord Baelish and maybe you will become the next Lord of Harrenholl. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
public class C {
public static void main(String[] args) throws IOException {
InputReader reader = new InputReader(System.in);
int N = reader.readInt();
int K = reader.readInt();
long sum = 0;
int odd = 0;
int even = 0;
for (int n=0; n<N; n++) {
int a = reader.readInt();
sum += a;
if ((a&1) == 0) {
even++;
} else {
odd++;
}
}
int turns = N-K;
if (turns == 0) {
System.out.println(sum%2 == 0 ? "Daenerys" : "Stannis");
return;
}
boolean stannis;
if (turns%2 == 0) {
// Daenerys ends
int sTurns = turns/2;
stannis = (sTurns >= even && K%2 == 1);
} else {
// Stannis ends
int dTurns = turns/2;
stannis = !((dTurns >= even && K%2 == 0) || (dTurns >= odd));
}
System.out.println(stannis ? "Stannis" : "Daenerys");
}
static final class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() throws IOException {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read(buf);
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public final int readInt() throws IOException {
return (int)readLong();
}
public final long readLong() throws IOException {
int c = read();
while (isSpaceChar(c)) {
c = read();
if (c == -1) throw new IOException();
}
boolean negative = false;
if (c == '-') {
negative = true;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return negative ? -res : res;
}
public final int[] readIntArray(int size) throws IOException {
int[] array = new int[size];
for (int i=0; i<size; i++) {
array[i] = readInt();
}
return array;
}
public final long[] readLongArray(int size) throws IOException {
long[] array = new long[size];
for (int i=0; i<size; i++) {
array[i] = readLong();
}
return array;
}
public final String readString() throws IOException {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.append((char)c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
| Java | ["3 1\n1 2 1", "3 1\n2 2 1", "6 3\n5 20 12 7 14 101"] | 1 second | ["Stannis", "Daenerys", "Stannis"] | NoteIn the first sample Stannis will use his move to burn a city with two people and Daenerys will be forced to burn a city with one resident. The only survivor city will have one resident left, that is, the total sum is odd, and thus Stannis wins.In the second sample, if Stannis burns a city with two people, Daenerys burns the city with one resident, or vice versa. In any case, the last remaining city will be inhabited by two people, that is, the total sum is even, and hence Daenerys wins. | Java 7 | standard input | [
"games"
] | 67e51db4d96b9f7996aea73cbdba3584 | The first line contains two positive space-separated integers, n and k (1ββ€βkββ€βnββ€β2Β·105) β the initial number of cities in Westeros and the number of cities at which the game ends. The second line contains n space-separated positive integers ai (1ββ€βaiββ€β106), which represent the population of each city in Westeros. | 2,200 | Print string "Daenerys" (without the quotes), if Daenerys wins and "Stannis" (without the quotes), if Stannis wins. | standard output | |
PASSED | 75de1eccb5b4a4a56cecfae4d76453b8 | train_003.jsonl | 1433595600 | There are n cities in Westeros. The i-th city is inhabited by ai people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly k cities left.The prophecy says that if the total number of surviving residents is even, then Daenerys wins: Stannis gets beheaded, and Daenerys rises on the Iron Throne. If the total number of surviving residents is odd, Stannis wins and everything goes in the completely opposite way.Lord Petyr Baelish wants to know which candidates to the throne he should support, and therefore he wonders, which one of them has a winning strategy. Answer to this question of Lord Baelish and maybe you will become the next Lord of Harrenholl. | 256 megabytes | import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner;
public class Main { public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt(); int k = in.nextInt(); int cnt1 = 0; for(int i = 0; i < n; i++) { if (in.nextInt() % 2 == 1) ++cnt1; }
out.println(even(cnt1, k, n) ? "Daenerys" : "Stannis"); out.flush(); }
static boolean even(int cnt1, int k, int n) { if (k == n) return cnt1 % 2 == 0; int moves = n - k; int oddMoves = (moves + 1) / 2;
int evenMoves = moves - oddMoves; int cnt0 = n - cnt1; boolean lastEven = oddMoves == evenMoves;
if (cnt0 == 0) return k % 2 == 0; if (cnt1 == 0) return true;
if (moves < cnt0 && moves < cnt1) { return lastEven; }
if (evenMoves >= cnt1) { return true; }
if (evenMoves >= cnt0 && (cnt1 - (moves - cnt0)) % 2 == 0) { return true; }
if (oddMoves >= cnt0 && (cnt1 - (moves - cnt0)) % 2 == 1) { return false; }
return lastEven;
}
static int[][] wins;
static boolean canWin(int cnt0, int cnt1, int k, boolean evenMoves) { if (cnt0 + cnt1 == k) return cnt1 % 2 == 0 == evenMoves; if (wins[cnt0][cnt1] != 0) { return wins[cnt0][cnt1] == 1; } int ans = 0; if (cnt0 >= 1 && !canWin(cnt0 - 1, cnt1, k, !evenMoves) || cnt1 >= 1 && !canWin(cnt0, cnt1 - 1, k, !evenMoves)) { ans = 1; } else ans = 2; wins[cnt0][cnt1] = ans; return ans == 1; } }
| Java | ["3 1\n1 2 1", "3 1\n2 2 1", "6 3\n5 20 12 7 14 101"] | 1 second | ["Stannis", "Daenerys", "Stannis"] | NoteIn the first sample Stannis will use his move to burn a city with two people and Daenerys will be forced to burn a city with one resident. The only survivor city will have one resident left, that is, the total sum is odd, and thus Stannis wins.In the second sample, if Stannis burns a city with two people, Daenerys burns the city with one resident, or vice versa. In any case, the last remaining city will be inhabited by two people, that is, the total sum is even, and hence Daenerys wins. | Java 7 | standard input | [
"games"
] | 67e51db4d96b9f7996aea73cbdba3584 | The first line contains two positive space-separated integers, n and k (1ββ€βkββ€βnββ€β2Β·105) β the initial number of cities in Westeros and the number of cities at which the game ends. The second line contains n space-separated positive integers ai (1ββ€βaiββ€β106), which represent the population of each city in Westeros. | 2,200 | Print string "Daenerys" (without the quotes), if Daenerys wins and "Stannis" (without the quotes), if Stannis wins. | standard output | |
PASSED | 5494dd6d87c79c97b03370699d35d151 | train_003.jsonl | 1433595600 | There are n cities in Westeros. The i-th city is inhabited by ai people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly k cities left.The prophecy says that if the total number of surviving residents is even, then Daenerys wins: Stannis gets beheaded, and Daenerys rises on the Iron Throne. If the total number of surviving residents is odd, Stannis wins and everything goes in the completely opposite way.Lord Petyr Baelish wants to know which candidates to the throne he should support, and therefore he wonders, which one of them has a winning strategy. Answer to this question of Lord Baelish and maybe you will become the next Lord of Harrenholl. | 256 megabytes | //package loosery;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class C {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
String[] name = {"Stannis", "Daenerys"};
int n = ni(), K = ni();
int o = 0, e = 0;
for(int i = 0;i < n;i++){
if(ni() % 2 == 0){
e++;
}else{
o++;
}
}
if(K % 2 == 0){
if(o+e == K){
out.println(name[1-o%2]);
}else{
if(n % 2 == 0){
out.println(name[(e+o+1)%2]);
}else{
if(e-o >= K || e-o <= -K){
out.println(name[(e+o)%2]);
}else{
out.println(name[(e+o+1)%2]);
}
}
}
}else{
if(o+e == K){
out.println(name[1-o%2]);
}else{
if(n % 2 == 0){
if(e-o >= K){
out.println(name[(e+o+1)%2]);
}else{
out.println(name[(e+o)%2]);
}
}else{
if(e-o <= -K){
out.println(name[(e+o+1)%2]);
}else{
out.println(name[(e+o)%2]);
}
}
}
}
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new C().run(); }
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| Java | ["3 1\n1 2 1", "3 1\n2 2 1", "6 3\n5 20 12 7 14 101"] | 1 second | ["Stannis", "Daenerys", "Stannis"] | NoteIn the first sample Stannis will use his move to burn a city with two people and Daenerys will be forced to burn a city with one resident. The only survivor city will have one resident left, that is, the total sum is odd, and thus Stannis wins.In the second sample, if Stannis burns a city with two people, Daenerys burns the city with one resident, or vice versa. In any case, the last remaining city will be inhabited by two people, that is, the total sum is even, and hence Daenerys wins. | Java 7 | standard input | [
"games"
] | 67e51db4d96b9f7996aea73cbdba3584 | The first line contains two positive space-separated integers, n and k (1ββ€βkββ€βnββ€β2Β·105) β the initial number of cities in Westeros and the number of cities at which the game ends. The second line contains n space-separated positive integers ai (1ββ€βaiββ€β106), which represent the population of each city in Westeros. | 2,200 | Print string "Daenerys" (without the quotes), if Daenerys wins and "Stannis" (without the quotes), if Stannis wins. | standard output | |
PASSED | 66f7e988e818509f75bae6bc12753bd1 | train_003.jsonl | 1433595600 | There are n cities in Westeros. The i-th city is inhabited by ai people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly k cities left.The prophecy says that if the total number of surviving residents is even, then Daenerys wins: Stannis gets beheaded, and Daenerys rises on the Iron Throne. If the total number of surviving residents is odd, Stannis wins and everything goes in the completely opposite way.Lord Petyr Baelish wants to know which candidates to the throne he should support, and therefore he wonders, which one of them has a winning strategy. Answer to this question of Lord Baelish and maybe you will become the next Lord of Harrenholl. | 256 megabytes | import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
/**
* Created with IntelliJ IDEA.
* User: igarus
* Date: 22.05.15
* Time: 20:34
* To change this template use File | Settings | File Templates.
*/
public class LookseryCup2015C {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int k = scanner.nextInt();
int[] s = new int[2];
for (int i = 0; i < n; i++) {
s[scanner.nextInt() % 2]++;
}
if (n == k) {
if (s[1]%2 == 1)
System.out.println("Stannis");
else
System.out.println("Daenerys");
} else if (n%2 == 1 && k%2 == 0) {
if (s[0] <= (n-k)/2 || s[1] <= (n-k)/2) {
System.out.println("Daenerys");
} else
System.out.println("Stannis");
} else if (n%2 == 0 && k%2 == 0) {
System.out.println("Daenerys");
} else if (n%2 == 1 && k%2 == 1) {
if (s[0] <= (n-k)/2)
System.out.println("Stannis");
else
System.out.println("Daenerys");
} else {
if (s[1] <= (n-k)/2)
System.out.println("Daenerys");
else
System.out.println("Stannis");
}
}
} | Java | ["3 1\n1 2 1", "3 1\n2 2 1", "6 3\n5 20 12 7 14 101"] | 1 second | ["Stannis", "Daenerys", "Stannis"] | NoteIn the first sample Stannis will use his move to burn a city with two people and Daenerys will be forced to burn a city with one resident. The only survivor city will have one resident left, that is, the total sum is odd, and thus Stannis wins.In the second sample, if Stannis burns a city with two people, Daenerys burns the city with one resident, or vice versa. In any case, the last remaining city will be inhabited by two people, that is, the total sum is even, and hence Daenerys wins. | Java 7 | standard input | [
"games"
] | 67e51db4d96b9f7996aea73cbdba3584 | The first line contains two positive space-separated integers, n and k (1ββ€βkββ€βnββ€β2Β·105) β the initial number of cities in Westeros and the number of cities at which the game ends. The second line contains n space-separated positive integers ai (1ββ€βaiββ€β106), which represent the population of each city in Westeros. | 2,200 | Print string "Daenerys" (without the quotes), if Daenerys wins and "Stannis" (without the quotes), if Stannis wins. | standard output | |
PASSED | 758b2ac7551ae518cb97ed02429f79f5 | train_003.jsonl | 1433595600 | There are n cities in Westeros. The i-th city is inhabited by ai people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly k cities left.The prophecy says that if the total number of surviving residents is even, then Daenerys wins: Stannis gets beheaded, and Daenerys rises on the Iron Throne. If the total number of surviving residents is odd, Stannis wins and everything goes in the completely opposite way.Lord Petyr Baelish wants to know which candidates to the throne he should support, and therefore he wonders, which one of them has a winning strategy. Answer to this question of Lord Baelish and maybe you will become the next Lord of Harrenholl. | 256 megabytes | import java.io.IOException;
import java.util.InputMismatchException;
public class TheGameOfParity {
public static void main(String[] args) {
FasterScanner sc = new FasterScanner();
int N = sc.nextInt();
int K = sc.nextInt();
int odds = 0;
int evns = 0;
for (int i = 0; i < N; i++) {
int A = sc.nextInt();
if (A % 2 == 0) {
evns++;
} else {
odds++;
}
}
int turns = N - K;
if (turns == 0) {
System.out.println((odds % 2 == 0) ? "Daenerys" : "Stannis");
return;
}
if (turns % 2 == 0) {
if (K % 2 == 0) {
System.out.println("Daenerys");
} else {
if ((turns + 1) / 2 >= evns) {
System.out.println("Stannis");
} else {
System.out.println("Daenerys");
}
}
} else {
if (turns / 2 >= odds) {
System.out.println("Daenerys");
} else {
if (K % 2 == 1) {
System.out.println("Stannis");
} else {
if (turns / 2 >= evns) {
System.out.println("Daenerys");
} else {
System.out.println("Stannis");
}
}
}
}
}
public static boolean stannisWins(int odds, int evns, int turns) {
if (turns == 0) {
return (odds % 2 == 1);
}
if (turns == 1) {
return ((odds > 0 && odds % 2 == 0) || (odds % 2 == 1 && evns > 0));
}
if (odds == 0) {
return false;
}
return !daenerysWins(odds, evns - 1, turns - 1);
// if (evns == 0) {
// return stannisWins(odds - 2, 0, turns - 2);
// } else {
// return stannisWins(odds - 1, evns - 1, turns - 2);
// }
// if (odds % 2 == 0 && turns % 2 == 1) {
// if (odds > turns / 2) {
// return true;
// } else {
// return false;
// }
// }
// if (odds % 2 == 1 && turns % 2 == 0) {
// if (odds > turns / 2) {
// return true;
// } else {
// return false;
// }
// }
// if (odds % 2 == 0 && turns % 2 == 0) {
// if (odds == 0) {
// return false;
// } else {
// return stannisWins(odds - 1, evns - 1, turns - 2);
// }
// }
// if (odds % 2 == 1 && turns % 2 == 1) {
// if (odds == 0) {
// return false;
// } else {
// return stannisWins(odds - 1, evns - 1, turns - 2);
// }
// }
//
// // should never reach here
// return false;
}
public static boolean daenerysWins(int odds, int evns, int turns) {
if (turns == 0) {
return (odds % 2 == 0);
} else if (turns == 1) {
return (odds % 2 == 1 || evns > 0);
}
return !stannisWins(odds - 1, evns, turns - 1);
}
public static class FasterScanner {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = System.in.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
} | Java | ["3 1\n1 2 1", "3 1\n2 2 1", "6 3\n5 20 12 7 14 101"] | 1 second | ["Stannis", "Daenerys", "Stannis"] | NoteIn the first sample Stannis will use his move to burn a city with two people and Daenerys will be forced to burn a city with one resident. The only survivor city will have one resident left, that is, the total sum is odd, and thus Stannis wins.In the second sample, if Stannis burns a city with two people, Daenerys burns the city with one resident, or vice versa. In any case, the last remaining city will be inhabited by two people, that is, the total sum is even, and hence Daenerys wins. | Java 7 | standard input | [
"games"
] | 67e51db4d96b9f7996aea73cbdba3584 | The first line contains two positive space-separated integers, n and k (1ββ€βkββ€βnββ€β2Β·105) β the initial number of cities in Westeros and the number of cities at which the game ends. The second line contains n space-separated positive integers ai (1ββ€βaiββ€β106), which represent the population of each city in Westeros. | 2,200 | Print string "Daenerys" (without the quotes), if Daenerys wins and "Stannis" (without the quotes), if Stannis wins. | standard output | |
PASSED | f08a446b90cb360b401d61943d954ddb | train_003.jsonl | 1433595600 | There are n cities in Westeros. The i-th city is inhabited by ai people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly k cities left.The prophecy says that if the total number of surviving residents is even, then Daenerys wins: Stannis gets beheaded, and Daenerys rises on the Iron Throne. If the total number of surviving residents is odd, Stannis wins and everything goes in the completely opposite way.Lord Petyr Baelish wants to know which candidates to the throne he should support, and therefore he wonders, which one of them has a winning strategy. Answer to this question of Lord Baelish and maybe you will become the next Lord of Harrenholl. | 256 megabytes | import java.io.IOException;
import java.util.InputMismatchException;
public class TheGameOfParity {
public static void main(String[] args) {
FasterScanner sc = new FasterScanner();
int N = sc.nextInt();
int K = sc.nextInt();
int odds = 0;
int evns = 0;
for (int i = 0; i < N; i++) {
int A = sc.nextInt();
if (A % 2 == 0) {
evns++;
} else {
odds++;
}
}
int turns = N - K;
if (turns == 0) {
System.out.println((odds % 2 == 0) ? "Daenerys" : "Stannis");
return;
} else if (turns % 2 == 0) {
if (K % 2 == 0) {
System.out.println("Daenerys");
} else if ((turns + 1) / 2 >= evns) {
System.out.println("Stannis");
} else {
System.out.println("Daenerys");
}
} else {
if (turns / 2 >= odds) {
System.out.println("Daenerys");
} else if (K % 2 == 1) {
System.out.println("Stannis");
} else if (turns / 2 >= evns) {
System.out.println("Daenerys");
} else {
System.out.println("Stannis");
}
}
}
public static class FasterScanner {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = System.in.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
} | Java | ["3 1\n1 2 1", "3 1\n2 2 1", "6 3\n5 20 12 7 14 101"] | 1 second | ["Stannis", "Daenerys", "Stannis"] | NoteIn the first sample Stannis will use his move to burn a city with two people and Daenerys will be forced to burn a city with one resident. The only survivor city will have one resident left, that is, the total sum is odd, and thus Stannis wins.In the second sample, if Stannis burns a city with two people, Daenerys burns the city with one resident, or vice versa. In any case, the last remaining city will be inhabited by two people, that is, the total sum is even, and hence Daenerys wins. | Java 7 | standard input | [
"games"
] | 67e51db4d96b9f7996aea73cbdba3584 | The first line contains two positive space-separated integers, n and k (1ββ€βkββ€βnββ€β2Β·105) β the initial number of cities in Westeros and the number of cities at which the game ends. The second line contains n space-separated positive integers ai (1ββ€βaiββ€β106), which represent the population of each city in Westeros. | 2,200 | Print string "Daenerys" (without the quotes), if Daenerys wins and "Stannis" (without the quotes), if Stannis wins. | standard output | |
PASSED | 5661d208c2b0e665b09a12c239c500f3 | train_003.jsonl | 1433595600 | There are n cities in Westeros. The i-th city is inhabited by ai people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly k cities left.The prophecy says that if the total number of surviving residents is even, then Daenerys wins: Stannis gets beheaded, and Daenerys rises on the Iron Throne. If the total number of surviving residents is odd, Stannis wins and everything goes in the completely opposite way.Lord Petyr Baelish wants to know which candidates to the throne he should support, and therefore he wonders, which one of them has a winning strategy. Answer to this question of Lord Baelish and maybe you will become the next Lord of Harrenholl. | 256 megabytes | import java.io.IOException;
import java.util.InputMismatchException;
public class TheGameOfParity {
public static void main(String[] args) {
FasterScanner sc = new FasterScanner();
int N = sc.nextInt();
int K = sc.nextInt();
int odds = 0;
int evns = 0;
for (int i = 0; i < N; i++) {
int A = sc.nextInt();
if (A % 2 == 0) {
evns++;
} else {
odds++;
}
}
int turns = N - K;
if (turns == 0) {
System.out.println((odds % 2 == 0) ? "Daenerys" : "Stannis");
return;
} else if (turns % 2 == 0) {
if (K % 2 == 0) {
System.out.println("Daenerys");
} else if ((turns + 1) / 2 >= evns) {
System.out.println("Stannis");
} else {
System.out.println("Daenerys");
}
} else {
if (turns / 2 >= odds) {
System.out.println("Daenerys");
} else if (K % 2 == 1) {
System.out.println("Stannis");
} else if (turns / 2 >= evns) {
System.out.println("Daenerys");
} else {
System.out.println("Stannis");
}
}
}
public static boolean stannisWins(int odds, int evns, int turns) {
if (turns == 0) {
return (odds % 2 == 1);
}
if (turns == 1) {
return ((odds > 0 && odds % 2 == 0) || (odds % 2 == 1 && evns > 0));
}
if (odds == 0) {
return false;
}
return !daenerysWins(odds, evns - 1, turns - 1);
// if (evns == 0) {
// return stannisWins(odds - 2, 0, turns - 2);
// } else {
// return stannisWins(odds - 1, evns - 1, turns - 2);
// }
// if (odds % 2 == 0 && turns % 2 == 1) {
// if (odds > turns / 2) {
// return true;
// } else {
// return false;
// }
// }
// if (odds % 2 == 1 && turns % 2 == 0) {
// if (odds > turns / 2) {
// return true;
// } else {
// return false;
// }
// }
// if (odds % 2 == 0 && turns % 2 == 0) {
// if (odds == 0) {
// return false;
// } else {
// return stannisWins(odds - 1, evns - 1, turns - 2);
// }
// }
// if (odds % 2 == 1 && turns % 2 == 1) {
// if (odds == 0) {
// return false;
// } else {
// return stannisWins(odds - 1, evns - 1, turns - 2);
// }
// }
//
// // should never reach here
// return false;
}
public static boolean daenerysWins(int odds, int evns, int turns) {
if (turns == 0) {
return (odds % 2 == 0);
} else if (turns == 1) {
return (odds % 2 == 1 || evns > 0);
}
return !stannisWins(odds - 1, evns, turns - 1);
}
public static class FasterScanner {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = System.in.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
} | Java | ["3 1\n1 2 1", "3 1\n2 2 1", "6 3\n5 20 12 7 14 101"] | 1 second | ["Stannis", "Daenerys", "Stannis"] | NoteIn the first sample Stannis will use his move to burn a city with two people and Daenerys will be forced to burn a city with one resident. The only survivor city will have one resident left, that is, the total sum is odd, and thus Stannis wins.In the second sample, if Stannis burns a city with two people, Daenerys burns the city with one resident, or vice versa. In any case, the last remaining city will be inhabited by two people, that is, the total sum is even, and hence Daenerys wins. | Java 7 | standard input | [
"games"
] | 67e51db4d96b9f7996aea73cbdba3584 | The first line contains two positive space-separated integers, n and k (1ββ€βkββ€βnββ€β2Β·105) β the initial number of cities in Westeros and the number of cities at which the game ends. The second line contains n space-separated positive integers ai (1ββ€βaiββ€β106), which represent the population of each city in Westeros. | 2,200 | Print string "Daenerys" (without the quotes), if Daenerys wins and "Stannis" (without the quotes), if Stannis wins. | standard output | |
PASSED | c2f7f858bb1eabd07e5c508c4387f8ce | train_003.jsonl | 1433595600 | There are n cities in Westeros. The i-th city is inhabited by ai people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly k cities left.The prophecy says that if the total number of surviving residents is even, then Daenerys wins: Stannis gets beheaded, and Daenerys rises on the Iron Throne. If the total number of surviving residents is odd, Stannis wins and everything goes in the completely opposite way.Lord Petyr Baelish wants to know which candidates to the throne he should support, and therefore he wonders, which one of them has a winning strategy. Answer to this question of Lord Baelish and maybe you will become the next Lord of Harrenholl. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
/**
* Created by shamir0xe on 1/5/2015 AD.
*/
/*
ID: shamir0xe
PROG: gift1
LANG: JAVA
*/
public class Solution {
public static void main(String[] args) {
IOHandler IO = new IOHandler();
IO.init("std", "std", "input.txt", "output.txt");
boolean testCaseKnown = false;
Solver solver = new Solver();
if (testCaseKnown) {
int testCase = IO.getInput().nextInt();
for (int test = 0; test < testCase; test++) {
solver.solve(IO.getInput(), IO.getOutput(), test + 1);
IO.flush();
}
}
else {
int test = 1;
try {
while (true) {
solver.solve(IO.getInput(), IO.getOutput(), test++);
IO.flush();
}
} catch (UnknownError unknownError) {
IO.close();
}
}
IO.close();
}
}
class Solver {
public void solve (MyInput in, PrintWriter out, int testCase) {
int n = in.nextInt();
int k = in.nextInt();
int[] population = new int[n];
int T = 0;
for (int i = 0; i < n; i++) {
population[i] = in.nextInt();
T += population[i] % 2;
}
WINNER winner;
int B = n - k;
if (B == 0) {
if (T % 2 == 0) {
winner = WINNER.Daenerys;
}
else {
winner = WINNER.Stannis;
}
}
else {
if (B % 2 == 1) {
// Stannis ends the game
if (T <= B / 2) {
// fard haaro mizane migaad Dae
winner = WINNER.Daenerys;
} else {
if (n - T <= B / 2) {
// zoj haa ro miterkan
if ((B + n) % 2 == 1) {
winner = WINNER.Stannis;
} else {
winner = WINNER.Daenerys;
}
} else {
// yani az jofteshoon baaghi mimoone :)
winner = WINNER.Stannis;
}
}
}
else {
// Daye ends the game
if (T <= B / 2) {
winner = WINNER.Daenerys;
}
else {
if (n - T <= (B + 1) / 2) {
if ((B + n) % 2 == 1) {
winner = WINNER.Stannis;
}
else {
winner = WINNER.Daenerys;
}
}
else {
winner = WINNER.Daenerys;
}
}
}
}
out.println(winner);
}
enum WINNER {
Stannis, Daenerys};
}
class StopWatch {
long beginTime;
public StopWatch() {
beginTime = System.currentTimeMillis();
}
public void start() {
beginTime = System.currentTimeMillis();
}
public long getTimeMillis() {
return System.currentTimeMillis() - beginTime;
}
public double getTimeSecond() {
return (double)getTimeMillis() / 1000.;
}
}
class IOHandler {
private MyInput in;
private PrintWriter out;
/**
*
* @param input_type : "file" or "std"
* @param output_type : "file" or "std"
* @param input_file_name : name of the input file
* @param output_file_name : name of the output file
*/
public void init(String input_type, String output_type, String input_file_name, String output_file_name) {
if (input_type.toLowerCase().equals("std")) {
in = new MyInput(System.in);
}
else {
// file
try {
in = new MyInput(new FileInputStream(input_file_name));
}
catch (IOException e) {
throw new UnknownError();
}
}
if (output_type.toLowerCase().equals("std")) {
out = new PrintWriter(System.out);
}
else {
// file
try {
out = new PrintWriter(new FileOutputStream(output_file_name));
}
catch (IOException e) {
throw new UnknownError();
}
}
}
public MyInput getInput() {
return in;
}
public PrintWriter getOutput() {
return out;
}
public void flush() {
out.flush();
}
public void close() {
out.flush();
out.close();
}
}
class MyInput {
private BufferedReader br;
private StringTokenizer st;
MyInput (InputStream inputStream) {
br = new BufferedReader(new InputStreamReader(inputStream));
st = null;
}
public String next() {
if (st == null || !st.hasMoreElements()) {
try {
String line = br.readLine();
if (line == null) {
throw new UnknownError();
}
while (line.trim().equals("")) {
line = br.readLine();
if (line == null) {
throw new UnknownError();
}
}
st = new StringTokenizer(line);
} catch (IOException e) {
throw new UnknownError();
}
}
return st.nextToken();
}
public String nextLine() {
try {
String line = br.readLine();
if (line == null) {
throw new UnknownError();
}
return line;
}
catch (IOException e) {
throw new UnknownError();
}
}
public void readEmptyLine() {
try {
br.readLine();
}
catch (IOException e) {
throw new UnknownError();
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
public boolean hasNext() {
try {
return st != null && st.hasMoreElements() || br.ready();
} catch (IOException e) {
throw new UnknownError();
}
}
}
/**
* Created by shamir0xe on 2/28/14.
*/
class MyMath {
/**
* Sieve Of Eratosthens[O(NloglogN)]
* @param n
* @return int[] with all primes within [0, n]
*/
public static int[] sieve(int n){
int[] pr = new int[n + 1];
Arrays.fill(pr, 1);
ArrayList <Integer> prime = new ArrayList<Integer>();
pr[0] = pr[1] = 0;
for(int i = 2; i <= n; i++) {
if(pr[i] == 1) {
prime.add(i);
if((long)i * i <= n)
for(long j = (long)i * i; j <= n; j += i)
pr[(int)j] = 0;
}
}
int [] ret = new int[prime.size()];
for (int i = 0; i < ret.length; i++) {
ret[i] = prime.get(i);
}
return ret;
}
/**
* GCD[O(logMAX(a, b))]
* @param a
* @param b
* @return GCD(a, b)
*/
public static int GCD(int a, int b){return b!=0 ? GCD(b, a % b) : a;}
/**
* Fast Power [O(logB)]
* @param a
* @param b
* @param m
* @return bth power of a modolu m
*/
public static int fastPow(int a, int b, int m){
int ans = 1;
while(b != 0){
if((b & 1) == 1)
ans = mul(ans, a, m);
a = mul(a, a, m);
b >>= 1;
}
return ans%m;
}
public static void buildPascal(int[][] pas, int MOD) {
int n = pas.length;
for (int i = 0; i < n; i++) {
pas[i][0] = 0;
}
for (int i = 0; i < n; i++) {
pas[0][i] = 1;
}
for (int i = 1; i < n; i++) {
for (int j = 1; j < n; j++) {
pas[i][j] = (pas[i][j-1] + pas[i-1][j-1]) % MOD;
}
}
}
// ext. Euclidean [O(log(Max(a, b))]
// Assumes nonnegative input. Returns d such that d=a*X+b*Y
public static long GCDex (long a, long b, long[] x, long[] y) {
if (a == 0) {
x[0] = 0; y[0] = 1;
return b;
}
long[] x1 = new long[1];
long[] y1 = new long[1];
long d = GCDex(b % a, a, x1, y1);
x[0] = y1[0] - (b / a) * x1[0];
y[0] = x1[0];
return d;
}
// Return X such that A * X == 1 (mod M)
// Return -1 if it doesn't exist such an X
public static long invMod(long a, long m){
long[] x = new long[1];
long[] q = new long[1];
if(GCDex(a, m, x, q) == 1){
x[0] = x[0] % m;
if (x[0] < m) {
x[0] = (x[0] + m) % m;
}
return x[0];
}
return -1;
}
/**
* this function gives the prime factors of n
* @param n an integer that wanna it primes
* @param primes the int[] of primes
**/
public static ArrayList<int[]> getFactors(int n, int[] primes) {
ArrayList <int[]> factors = new ArrayList<int[]>();
for (int prime: primes) {
if (n % prime == 0) {
int cnt = 0;
while (n % prime == 0) {
n /= prime;
cnt++;
}
factors.add(new int[] {prime, cnt});
}
}
if (n != 1) {
factors.add(new int[] {n, 1});
}
return factors;
}
public static int add(int a, int b, int MOD) {
return ((a + b) % MOD + MOD) % MOD;
}
public static int mul(int a, int b, int MOD) {
return ((int)(((long) a * b) % MOD) + MOD) % MOD;
}
}
class Pair <P extends Comparable <? super P>, Q extends Comparable <? super Q> >
implements Comparable <Pair <P, Q> > {
P a;
Q b;
public Pair (P a, Q b) {
this.a = a;
this.b = b;
}
public Pair() {
}
public void setX(P a) {
this.a = a;
}
public void setY(Q b) {
this.b = b;
}
public P getX() {
return a;
}
public Q getY() {
return b;
}
public String toString() {
return "(" + a.toString() + ", " + b.toString() + ")";
}
@Override
public int compareTo(Pair<P, Q> o) {
int cmp = a.compareTo(o.a);
if (cmp == 0) {
return b.compareTo(o.b);
}
return cmp;
}
}
class FenwickTree {
private int[] tree;
private int maxVal;
public FenwickTree(int n) {
maxVal = n;
tree = new int[maxVal + 1];
}
/**
* update element val by adding the val to it
* O(LOG(N))
*/
public void update(int idx, int val) {
idx++;
while (idx <= maxVal) {
tree[idx] += val;
idx += (idx & (-idx));
}
}
/**
* return the sum of values of tree[] from idx to 0
* O(LOG(N))
*/
public int read(int idx) {
idx++;
int sum = 0;
while (idx > 0) {
sum += tree[idx];
idx -= (idx & -idx);
}
return sum;
}
public int getMaxVal() {
return maxVal;
}
public int rangeSum(int left, int right) {
if(left > right)
return 0;
int sumLeft = read(left - 1);
int sumRight = read(right);
return sumRight - sumLeft;
}
}
class PairInt implements Comparable <PairInt> {
public int X, Y;
public PairInt(int X, int Y){
this.X = X;
this.Y = Y;
}
public PairInt add(PairInt b) {
return new PairInt(X + b.X, Y + b.Y);
}
public PairInt sub(PairInt b) {
return new PairInt(X - b.X, Y - b.Y);
}
@Override
public int compareTo(PairInt o) {
if(X != o.X)
return X - o.X;
return Y - o.Y;
}
}
class IntArrays {
public static void reverse(int[] cur){
int[] temp = new int[cur.length];
int cnt = 0;
for(int i=cur.length-1; i>=0; i--){
temp[cnt++] = cur[i];
}
for(int i=0;i<cnt; i++)
cur[i] = temp[i];
}
public static void swap(int[] arr, int a, int b){
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
// public static void print(int[] arr, OutputWriter out){
// boolean first = true;
// for(int temp: arr){
// if(first)
// first = false;
// else
// out.print(" ");
// out.print(temp);
// }
// out.printLine();
// }
private static Integer[] selfOrder(int n) {
Integer[] self = new Integer[n];
for (int i = 0; i < n; i++) {
self[i] = i;
}
return self;
}
private static int[] convertBoxToPrimitive(Integer[] box) {
int[] primitive = new int[box.length];
for (int i = 0; i < box.length; i++) {
primitive[i] = box[i];
}
return primitive;
}
public static int[] getOrder(final int[] arr) {
Integer[] order = selfOrder(arr.length);
Arrays.sort(order, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if(arr[o1] > arr[o2])
return 1;
if(arr[o1] < arr[o2])
return -1;
return 0;
}
});
return convertBoxToPrimitive(order);
}
public static boolean next_permutation(int[] c){
// 1. finds the largest k, that c[k] < c[k+1]
int first = getFirst( c );
if ( first == -1 ) return false; // no greater permutation
// 2. findJad last index toSwap, that c[k] < c[toSwap]
int toSwap = c.length - 1;
while ( c[ first ] >= c[ toSwap ] )
--toSwap;
// 3. swap elements with indexes first and last
swap( c, first++, toSwap );
// 4. reverse sequence from k+1 to n (inclusive)
toSwap = c.length - 1;
while ( first < toSwap )
swap( c, first++, toSwap-- );
return true;
}
// finds the largest k, that c[k] < c[k+1]
// if no such k exists (there is not greater permutation), return -1
private static int getFirst( final int[] c ) {
for ( int i = c.length - 2; i >= 0; --i )
if ( c[ i ] < c[ i + 1 ] )
return i;
return -1;
}
/**
* return the minimum index i such that val[ order[ i ] ] >= need
*/
public static int lowerBound(int[] order, int[] val, int need) {
int s = 0;
int e = order.length;
while(e - s > 1) {
int mid = (e + s) / 2;
if(val[order[mid]] < need)
s = mid;
else
e = mid;
}
if(val[order[s]] >= need)
return s;
return e;
}
public static int lowerBound(int[] val, int need) {
int s = 0;
int e = val.length;
while(e - s > 1) {
int mid = (e + s) / 2;
if(val[mid] < need)
s = mid;
else
e = mid;
}
if(val[s] >= need)
return s;
return e;
}
}
| Java | ["3 1\n1 2 1", "3 1\n2 2 1", "6 3\n5 20 12 7 14 101"] | 1 second | ["Stannis", "Daenerys", "Stannis"] | NoteIn the first sample Stannis will use his move to burn a city with two people and Daenerys will be forced to burn a city with one resident. The only survivor city will have one resident left, that is, the total sum is odd, and thus Stannis wins.In the second sample, if Stannis burns a city with two people, Daenerys burns the city with one resident, or vice versa. In any case, the last remaining city will be inhabited by two people, that is, the total sum is even, and hence Daenerys wins. | Java 7 | standard input | [
"games"
] | 67e51db4d96b9f7996aea73cbdba3584 | The first line contains two positive space-separated integers, n and k (1ββ€βkββ€βnββ€β2Β·105) β the initial number of cities in Westeros and the number of cities at which the game ends. The second line contains n space-separated positive integers ai (1ββ€βaiββ€β106), which represent the population of each city in Westeros. | 2,200 | Print string "Daenerys" (without the quotes), if Daenerys wins and "Stannis" (without the quotes), if Stannis wins. | standard output | |
PASSED | 45d1a0c2eb4c69439e350ef4ec0de6a6 | train_003.jsonl | 1557930900 | This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.The jury guessed some array $$$a$$$ consisting of $$$6$$$ integers. There are $$$6$$$ special numbers β $$$4$$$, $$$8$$$, $$$15$$$, $$$16$$$, $$$23$$$, $$$42$$$ β and each of these numbers occurs in $$$a$$$ exactly once (so, $$$a$$$ is some permutation of these numbers).You don't know anything about their order, but you are allowed to ask up to $$$4$$$ queries. In each query, you may choose two indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le 6$$$, $$$i$$$ and $$$j$$$ are not necessarily distinct), and you will get the value of $$$a_i \cdot a_j$$$ in return.Can you guess the array $$$a$$$?The array $$$a$$$ is fixed beforehand in each test, the interaction program doesn't try to adapt to your queries. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.*;
import java.io.*;
public class Tree
{
static int check(long w, long b, int a[])
{
int A[] = {4,8,15,16,23,42};
int B[] = new int[100001];
for (int x=0;x<100001;x++)
B[x]=0;
B[4]=1;
B[8]=1;
B[15]=1;
B[16]=1;
B[23]=1;
B[42]=1;
int ans=0;
int i=0; int j=0;
for (int x=0;x<6;x++)
{
if (w%A[x]==0 && b%A[x]==0 && A[x]!=a[0] && A[x]!=a[1])
{
i=(int)(w/A[x]);
j=(int)(b/A[x]);
if (B[i]==1 && B[j]==1 && i!=j && i!=A[x] && j!=A[x])
{ans=A[x];break;}
}
}
return (ans);
}
public static void main (String args[]) throws Exception
{
int a[] = new int[6];
Scanner in = new Scanner(System.in);
long ans=4*8*15*16*23*42;
System.out.println ("? 1 1");
// System.out.flush();
long k=in.nextLong();
a[0]=(int)(Math.sqrt(k));
System.out.println ("? 2 2");
//System.out.flush();
k=in.nextLong();
a[1]=(int)(Math.sqrt(k));
System.out.println ("? 3 4");
//System.out.flush();
k=in.nextLong();
System.out.println ("? 3 5");
//System.out.flush();
long k1=in.nextLong();
a[2]=check(k,k1,a);
a[3]=(int)k/a[2];
a[4]=(int)k1/a[2];
System.out.print("! ");
for (int x=0;x<5;x++)
{System.out.print (a[x]+" ");ans=ans/a[x];}
a[5]=(int)ans;
System.out.println (a[5]+" ");
}
} | Java | ["16\n64\n345\n672"] | 1 second | ["? 1 1\n? 2 2\n? 3 5\n? 4 6\n! 4 8 15 16 23 42"] | NoteIf you want to submit a hack for this problem, your test should contain exactly six space-separated integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_6$$$. Each of $$$6$$$ special numbers should occur exactly once in the test. The test should be ended with a line break character. | Java 8 | standard input | [
"math",
"divide and conquer",
"brute force",
"interactive"
] | c0f79d7ebcecc4eb7d07c372ba9be802 | null | 1,400 | null | standard output | |
PASSED | 661c1475c00dfe249307a06ef7b917e2 | train_003.jsonl | 1557930900 | This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.The jury guessed some array $$$a$$$ consisting of $$$6$$$ integers. There are $$$6$$$ special numbers β $$$4$$$, $$$8$$$, $$$15$$$, $$$16$$$, $$$23$$$, $$$42$$$ β and each of these numbers occurs in $$$a$$$ exactly once (so, $$$a$$$ is some permutation of these numbers).You don't know anything about their order, but you are allowed to ask up to $$$4$$$ queries. In each query, you may choose two indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le 6$$$, $$$i$$$ and $$$j$$$ are not necessarily distinct), and you will get the value of $$$a_i \cdot a_j$$$ in return.Can you guess the array $$$a$$$?The array $$$a$$$ is fixed beforehand in each test, the interaction program doesn't try to adapt to your queries. | 256 megabytes |
import java.util.*;
public class E1167B {
static final int ALL_PRODUCTS = 7418880; // 4 * 8 * 15 * 16 * 23 * 42
static int [] a12 = new int [2];
static int [] a34 = new int [2];
static int [] a13 = new int [2];
static int get_common( int i1, int i2, int i3, int i4) {
if (i1 == i3) return i1;
if (i1 == i4) return i1;
return i2;
}
static void get_numbers (int p12, int [] a12) {
boolean has_7 = false;
boolean has_5 = false;
boolean has_23= false;
int curr_i = 0; // current index
if (p12 % 7 == 0) {
a12[curr_i ++] = 42;
p12 /=2;
has_7 = true;
}
if (p12 % 5 == 0) {
a12[curr_i ++] = 15;
has_5 = true;
}
if (p12 % 23 == 0 ) {
a12[curr_i ++ ] = 23;
has_23 = true;
}
if (curr_i >=2)
return;
if (curr_i == 1) {
if (p12 % 16 == 0)
a12[curr_i] = 16;
else {
if (p12 % 8 == 0)
a12[curr_i] = 8;
else
a12[curr_i] = 4;
}
}
else {
// curr_i == 0
if (p12 % 128 == 0 ) {
a12[0] = 8; a12[1] = 16;
}
else {
if (p12 % 64 == 0) {
a12[0] = 4; a12[1] = 16;
}
else {
a12[0] = 4; a12[1] = 8;
}
}
}
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int [] a = new int [7]; // a[1] is the answer of the first number
System.out.println("? 1 2"); System.out.flush();
int p12 = sc.nextInt();
System.out.println("? 1 3"); System.out.flush();
int p13 = sc.nextInt();
get_numbers(p12, a12);
get_numbers(p13, a13);
a[1] = get_common( a12[0], a12[1], a13[0], a13[1]);
a[2] = p12 / a[1];
a[3] = p13 / a[1];
System.out.println("? 1 4"); System.out.flush();
int p14 = sc.nextInt();
a[4] = p14 / a[1];
System.out.println("? 1 5"); System.out.flush();
int p15 = sc.nextInt();
a[5] = p15 / a[1];
a[6] = ALL_PRODUCTS / (a[1] * a[2] * a[3] * a[4] * a[5]);
// Print out answers
System.out.print("!");
for (int i=1; i< 7; i++ ) {
System.out.print(" ");
System.out.print(a[i]);
}
System.out.println();
}
}
| Java | ["16\n64\n345\n672"] | 1 second | ["? 1 1\n? 2 2\n? 3 5\n? 4 6\n! 4 8 15 16 23 42"] | NoteIf you want to submit a hack for this problem, your test should contain exactly six space-separated integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_6$$$. Each of $$$6$$$ special numbers should occur exactly once in the test. The test should be ended with a line break character. | Java 8 | standard input | [
"math",
"divide and conquer",
"brute force",
"interactive"
] | c0f79d7ebcecc4eb7d07c372ba9be802 | null | 1,400 | null | standard output | |
PASSED | e33f30707b13d24b010c2e32249e8a16 | train_003.jsonl | 1557930900 | This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307.The jury guessed some array $$$a$$$ consisting of $$$6$$$ integers. There are $$$6$$$ special numbers β $$$4$$$, $$$8$$$, $$$15$$$, $$$16$$$, $$$23$$$, $$$42$$$ β and each of these numbers occurs in $$$a$$$ exactly once (so, $$$a$$$ is some permutation of these numbers).You don't know anything about their order, but you are allowed to ask up to $$$4$$$ queries. In each query, you may choose two indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le 6$$$, $$$i$$$ and $$$j$$$ are not necessarily distinct), and you will get the value of $$$a_i \cdot a_j$$$ in return.Can you guess the array $$$a$$$?The array $$$a$$$ is fixed beforehand in each test, the interaction program doesn't try to adapt to your queries. | 256 megabytes | import java.util.Scanner;
/*
966
672
630
336
*/
/**
*
* @author Andy Phan
*/
public class p1167b {
static int[] arr = {4, 8, 15, 16, 23, 42};
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] has = new int[1000];
for(int i = 0; i < 6; i++) has[arr[i]] = i;
int[] res = new int[6];
int[] tmp = new int[4];
for(int i = 0; i < 4; i++) {
System.out.println("? 1 " + (i+2));
System.out.flush();
tmp[i] = in.nextInt();
}
boolean[] taken = new boolean[6];
for(int i = 5; i >= 0; i--) {
if(tmp[0]%arr[i] == 0 && tmp[1]%arr[i] == 0 && tmp[2]%arr[i] == 0 && tmp[3]%arr[i] == 0) {
res[0] = arr[i];
taken[i] = true;
break;
}
}
for(int i = 0; i < 4; i++) {
res[i+1] = tmp[i]/res[0];
taken[has[res[i+1]]] = true;
}
for(int i = 0; i < 6; i++) {
if(!taken[i]) res[5] = arr[i];
}
System.out.print("! ");
for(int i = 0; i < 6; i++) System.out.print(res[i] + " ");
System.out.println("");
System.out.flush();
}
} | Java | ["16\n64\n345\n672"] | 1 second | ["? 1 1\n? 2 2\n? 3 5\n? 4 6\n! 4 8 15 16 23 42"] | NoteIf you want to submit a hack for this problem, your test should contain exactly six space-separated integers $$$a_1$$$, $$$a_2$$$, ..., $$$a_6$$$. Each of $$$6$$$ special numbers should occur exactly once in the test. The test should be ended with a line break character. | Java 8 | standard input | [
"math",
"divide and conquer",
"brute force",
"interactive"
] | c0f79d7ebcecc4eb7d07c372ba9be802 | null | 1,400 | null | standard output | |
PASSED | b0484e505f8d5f810537b7b2d1e11fd6 | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.util.Collections.*;
import static java.lang.Math.*;
@SuppressWarnings("unchecked")
public class A_Boredom {
public static PrintWriter out;
public static InputReader in;
public static long[] dp;
public static int n;
public static ArrayList<Long> list;
public static ArrayList<Long> orig;
public static long calc(int i){
if(i>=list.size())
return 0l;
if(dp[i]!=-1l)
return dp[i];
if((i+1)>=orig.size() || orig.get(i+1)-1==orig.get(i)){
dp[i] = list.get(i) + max(calc(i+2),calc(i+3));
}
else
dp[i] = list.get(i) + max(calc(i+1),calc(i+2));
return dp[i];
}
public static void main(String[] args)throws IOException {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
int cases = 1;
for(int t = 0; t < cases; t++){
n = in.nextInt();
int arr[] = new int[n];
dp = new long[n]; Arrays.fill(dp,-1l);
for(int i=0;i<n;i++)
arr[i]=in.nextInt();
shuffle(arr); Arrays.sort(arr); //sort snippet, print arr snippet
// print(arr);
long ct = 0l;
list = new ArrayList<Long>(); orig = new ArrayList<Long>();
for(int i=0;i<n;i++){
if(i!=0 && arr[i]!=arr[i-1]){
list.add((((long)arr[i-1])*ct));
orig.add((long)arr[i-1]);
ct = 0l;
}
ct++;
}
orig.add((long)arr[n-1]);
list.add(((long)arr[n-1])*ct);
// out.println(list);
out.println(max(calc(0),calc(1)));
}
out.close();
}
public static void print(int arr[]){
for(int i : arr) out.print(i+" ");
out.println();
}
public static void shuffle(int arr[]){
ArrayList<Integer> list = new ArrayList<Integer>(arr.length);
for(int i=0;i<arr.length;i++) list.add(i,arr[i]);
Collections.shuffle(list);
for(int i=0;i<arr.length;i++) arr[i]=list.get(i);
}
public static void shuffle(long arr[]){
ArrayList<Long> list = new ArrayList<Long>(arr.length);
for(int i=0;i<arr.length;i++) list.add(i,arr[i]);
Collections.shuffle(list);
for(int i=0;i<arr.length;i++) arr[i]=list.get(i);
}
public static <T> void shuffle(T[] arr){
ArrayList<T> list = new ArrayList<T>(arr.length);
for(int i=0;i<arr.length;i++) list.add(i,arr[i]);
Collections.shuffle(list);
for(int i=0;i<arr.length;i++) arr[i]=list.get(i);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | b01e48a170438a51b376675b2705bd2e | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main
{
static PrintWriter out;
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
out=new PrintWriter(System.out);
}
String next(){
while(st==null || !st.hasMoreElements()){
try{
st= new StringTokenizer(br.readLine());
}
catch (IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try{
str=br.readLine();
}
catch(IOException e){
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args)
{
FastReader scn = new FastReader();
// int t = scn.nextInt() ;
//for( int m = 1; m<= t; m++){
long n = scn.nextInt() ;
long[] freq = new long[100001] ;
for(int i = 0; i <n; i++)
{
int x = scn.nextInt() ;
freq[x]++ ;
}
long[] dp= new long[100001] ;
dp[1] = freq[1] ;
dp[2] = Math.max(freq[1] , 2*freq[2] ) ;
for( int i = 3 ; i < dp.length ; i++)
{
dp[i] = Math.max(dp[i-1] , freq[i]*i + dp[i-2] ) ;
}
out.println(dp[dp.length-1]) ;
// }
out.flush();
}
} | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | e524749d723761f41ab39657f4d65408 | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main
{
static PrintWriter out;
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br=new BufferedReader(new InputStreamReader(System.in));
out=new PrintWriter(System.out);
}
String next(){
while(st==null || !st.hasMoreElements()){
try{
st= new StringTokenizer(br.readLine());
}
catch (IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
long nextLong(){
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try{
str=br.readLine();
}
catch(IOException e){
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args)
{
FastReader scn = new FastReader();
// int t = scn.nextInt() ;
//for( int m = 1; m<= t; m++){
long n = scn.nextInt() ;
long[] freq = new long[100001] ;
for(int i = 0; i <n; i++)
{
int x = scn.nextInt() ;
freq[x]++ ;
}
long[] dp= new long[100001] ;
dp[1] = freq[1] ;
dp[2] = Math.max(freq[1] , 2*freq[2] ) ;
for( int i = 3 ; i < dp.length ; i++)
{
dp[i] = Math.max(dp[i-1] , freq[i]*i + dp[i-2] ) ;
}
out.println(dp[100000]) ;
// }
out.flush();
}
} | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | e07177988c932a4835bb160dba9d7e98 | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class Boredom455A {
public static void main(String[] args) {
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
final int max = 100003;
int t = sc.nextInt();
long[] count = new long[max];
for (int i = 0; i < t; i++) {
count[sc.nextInt()]++;
}
long[] dp = new long[max];
dp[0] = 0;
dp[1] = count[1];
for (int i = 2; i < max; i++) {
dp[i] = Math.max(dp[i - 1], dp[i - 2] + count[i] * i);
}
System.out.println(dp[max - 1]);
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | d7a6ffbb28bbc43372296091aa7b14f2 | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
public class Main implements Runnable
{
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception
{
new Thread(null, new Main(),"Main",1<<27).start();
}
static class Pair{
int f;
int s;
Pair(int f,int s){
this.f=f;
this.s=s;
}
public static Comparator<Pair> wc = new Comparator<Pair>(){
public int compare(Pair e1,Pair e2){
//reverse order
if(e1.s < e2.s)
return 1; // 1 for swaping.
else if (e1.s > e2.s)
return -1;
else {
//System.out.println("* "+e1.nod+" "+e2.nod);
return 0;
}
}
};
}
public static long gcd(long a,long b){
if(b==0)return a;
else return gcd(b,a%b);
}
////recursive BFS
public static int bfsr(int s,ArrayList<Integer>[] a,boolean[] b,int[] pre){
b[s]=true;
int p = 1;
int n = pre.length -1;
int t = a[s].size();
int max = 1;
for(int i=0;i<t;i++){
int x = a[s].get(i);
if(!b[x]){
//dist[x] = dist[s] + 1;
int xz = (bfsr(x,a,b,pre));
p+=xz;
max = Math.max(xz,max);
}
}
max = Math.max(max,(n-p));
pre[s] = max;
return p;
}
//// iterative BFS
public static int bfs(int s,ArrayList<Integer>[] a,int[] dist,boolean[] b,PrintWriter w){
b[s]=true;
int siz = 0;
Queue<Integer> q = new LinkedList<>();
q.add(s);
while(q.size()!=0){
int i=q.poll();
Iterator<Integer> it = a[i].listIterator();
int z=0;
while(it.hasNext()){
z=it.next();
if(!b[z]){
b[z]=true;
dist[z] = dist[i] + 1;
siz++;
q.add(z);
}
}
}
return siz;
}
public static int lower(int key, int[] a){
int l = 0;
int r = a.length-1;
int res = 0;
while(l<=r){
int mid = (l+r)/2;
if(a[mid]<=key){
l = mid+1;
res = mid+1;
}
else{
r = mid -1;
}
}
return res;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
public void run()
{
InputReader sc = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int defaultValue=0;
// int tc = sc.nextInt();
// while(tc-->0){
int n = sc.nextInt();
int[] a = new int[n];
long[] cnt = new long[100001];
for(int i=0;i<n;i++){
a[i] = sc.nextInt();
cnt[a[i]]++;
}
long[] dp = new long[100002];
Arrays.fill(dp,Integer.MIN_VALUE);
//long ans = 0;
dp[0] = 0;
dp[1] = cnt[1];
// ans = find(1,dp, cnt);
for(int i=2;i<100001;i++){
dp[i] = (long)Math.max(dp[i-1],dp[i-2]+(cnt[i]*i));
}
w.println(dp[100000]);
//}
w.flush();
w.close();
}
// public int find(int s, int[] dp, int[] cnt){
// if(s<dp.length && dp[s]==Integer.MIN_VALUE){
// dp[s] = Math.max(find(s-1,dp,cnt),find(s+1,dp,cnt)+(cnt[s]*s));
// }
// return dp[s];
// }
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | 02f7dcb98c696237ad2a8e249c2b9c62 | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
public class ar {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static boolean[] sieve=new boolean[1000000+1];
public static void main(String[] args) throws java.lang.Exception {
FastReader scn = new FastReader();
int n=scn.nextInt();
long[] dp = new long[100001];
for(int i=1;i<=n;i++){
int num=scn.nextInt();
dp[num]+=num;
}
for (int i = 2; i <100001; i++) {
dp[i] = Math.max(dp[i] + dp[i - 2], dp[i - 1]);
}
System.out.println(dp[100000]);
}
} | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | 558ccc13f8cd316698cbcb4b0856c0b1 | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class CF455A {
static BufferedReader __in;
static PrintWriter __out;
static StringTokenizer input;
public static void main(String[] args) throws IOException {
__in = new BufferedReader(new InputStreamReader(System.in));
__out = new PrintWriter(new OutputStreamWriter(System.out));
int n = ri(), a[] = new int[100001];
r();
while(n --> 0) {
++a[ni()];
}
long[] dp = new long[100001];
dp[1] = a[1];
for(int i = 2; i <= 100000; ++i) {
dp[i] = max(dp[i - 1], (long) i * a[i] + dp[i - 2]);
}
prln(dp[100000]);
close();
}
// references
// IBIG = 1e9 + 7
// IRAND ~= 3e8
// IMAX ~= 2e10
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IRAND = 327859546;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));}
static int minstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));}
static long minstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));}
static int maxstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));}
static long maxstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));}
static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int floori(double d) {return (int)d;}
static int ceili(double d) {return (int)ceil(d);}
static long floorl(double d) {return (long)d;}
static long ceill(double d) {return (long)ceil(d);}
// input
static void r() throws IOException {input = new StringTokenizer(__in.readLine());}
static int ri() throws IOException {return Integer.parseInt(__in.readLine());}
static long rl() throws IOException {return Long.parseLong(__in.readLine());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;}
static char[] rcha() throws IOException {return __in.readLine().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());}
static int ni() {return Integer.parseInt(input.nextToken());}
static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());}
static long nl() {return Long.parseLong(input.nextToken());}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {__out.println("yes");}
static void pry() {__out.println("Yes");}
static void prY() {__out.println("YES");}
static void prno() {__out.println("no");}
static void prn() {__out.println("No");}
static void prN() {__out.println("NO");}
static void pryesno(boolean b) {__out.println(b ? "yes" : "no");};
static void pryn(boolean b) {__out.println(b ? "Yes" : "No");}
static void prYN(boolean b) {__out.println(b ? "YES" : "NO");}
static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); __out.println(iter.next());}
static void flush() {__out.flush();}
static void close() {__out.close();}} | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | f2e182d6b3b7991d809fa37cfcc3bf66 | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.InputMismatchException;
public class B {
public static int[] freq;
public static long[] dp;
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
InputReader s = new InputReader(System.in);
PrintWriter p = new PrintWriter(System.out);
freq = new int[100008];
dp = new long[1000009];
int n = s.nextInt();
for (int i = 0; i < n; i++) {
freq[s.nextInt()]++;
}
get();
p.println(dp[100002]);
p.flush();
p.close();
}
public static void get() {
for (int i = 0; i < 100008; i++) {
if (freq[i] != 0) {
long ans1 = (long) freq[i] * (i);
long ans2 = Integer.MIN_VALUE;
if (i - 2 >= 0) {
ans1 += (long) dp[i - 2];
}
if (i - 1 >= 0) {
ans2 = (long) dp[i - 1];
}
dp[i] = Math.max(ans1, ans2);
} else {
if (i > 1)
dp[i] = dp[i - 1];
}
}
}
public static boolean prime(long n) {
if (n == 1) {
return false;
}
if (n == 2) {
return true;
}
for (long i = 2; i <= (long) Math.sqrt(n); i++) {
if (n % i == 0)
return false;
}
return true;
}
public static ArrayList Divisors(long n) {
ArrayList<Long> div = new ArrayList<>();
for (long i = 1; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
div.add(i);
if (n / i != i)
div.add(n / i);
}
}
return div;
}
public static int BinarySearch(long[] a, long k) {
int n = a.length;
int i = 0, j = n - 1;
int mid = 0;
if (k < a[0])
return 0;
else if (k >= a[n - 1])
return n;
else {
while (j - i > 1) {
mid = (i + j) / 2;
if (k >= a[mid])
i = mid;
else
j = mid;
}
}
return i + 1;
}
public static long GCD(long a, long b) {
if (b == 0)
return a;
else
return GCD(b, a % b);
}
public static long LCM(long a, long b) {
return (a * b) / GCD(a, b);
}
static class pair implements Comparable<pair> {
Long x, y;
pair(long x, long y) {
this.x = x;
this.y = y;
}
public int compareTo(pair o) {
int result = x.compareTo(o.x);
if (result == 0)
result = y.compareTo(o.y);
return result;
}
public String toString() {
return x + " " + y;
}
public boolean equals(Object o) {
if (o instanceof pair) {
pair p = (pair) o;
return p.x - x == 0 && p.y - y == 0;
}
return false;
}
public int hashCode() {
return new Long(x).hashCode() * 31 + new Long(y).hashCode();
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class CodeX {
public static void sort(long arr[]) {
merge_sort(arr, 0, arr.length - 1);
}
private static void merge_sort(long A[], long start, long end) {
if (start < end) {
long mid = (start + end) / 2;
merge_sort(A, start, mid);
merge_sort(A, mid + 1, end);
merge(A, start, mid, end);
}
}
private static void merge(long A[], long start, long mid, long end) {
long p = start, q = mid + 1;
long Arr[] = new long[(int) (end - start + 1)];
long k = 0;
for (int i = (int) start; i <= end; i++) {
if (p > mid)
Arr[(int) k++] = A[(int) q++];
else if (q > end)
Arr[(int) k++] = A[(int) p++];
else if (A[(int) p] < A[(int) q])
Arr[(int) k++] = A[(int) p++];
else
Arr[(int) k++] = A[(int) q++];
}
for (int i = 0; i < k; i++) {
A[(int) start++] = Arr[i];
}
}
}
} | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | 697495916fdadf219862f6fb6528a1f1 | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.util.Scanner;
public class Boredom {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner t = new Scanner(System.in);
int n = t.nextInt();
long[] in = new long[100003];
long[] ans = new long[100003];
for (int i = 0; i < n; i++)
in[t.nextInt()]++;
ans[0] = 0;
ans[1] = in[1];
for (int i = 2; i < 100003; i++)
ans[i] = Math.max(ans[i - 1], ans[i - 2] + in[i] * i);
System.out.println(ans[100002]);
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | d764f27477f6ee9d7ec6a4bd2f47fcf1 | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
ABoredom solver = new ABoredom();
solver.solve(1, in, out);
out.close();
}
static class ABoredom {
int[] count;
long[] memo;
public void solve(int testNumber, Scanner sc, PrintWriter pw) {
int n = sc.nextInt();
count = new int[(int) 1e5 + 1];
for (int i = 0; i < n; i++)
count[sc.nextInt()]++;
memo = new long[(int) 1e5 + 1];
Arrays.fill(memo, -1);
for (int i = (int) 1e5; i >= 0; i--)
dp(i);
pw.println(dp(1));
}
private long dp(int idx) {
if (idx > (int) 1e5)
return 0;
if (memo[idx] != -1)
return memo[idx];
long take = 1l * idx * count[idx] + dp(idx + 2);
long leave = dp(idx + 1);
return memo[idx] = Math.max(take, leave);
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | 76d3bcfb1a5f14bec47d607fff12815c | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
public class test {
public static void main(String[] args) {
// int test = fs.nextInt();
int test = 1;
for (int cases = 0; cases < test; cases++) {
int n = fs.nextInt();
long a[]=new long[100001];
int max=0;
for (int i = 0; i < n; i++) {
int c = fs.nextInt();
a[c] += c;
max = Math.max(max, c);
}
long dp[]=new long[max+1];
dp[0]=0;dp[1]=a[1];
for(int i=1;i<max;i++)
{
dp[i+1]=Math.max(dp[i], a[i+1]+dp[i-1]);
}
System.out.println(dp[max]);
}
}
static int countDifferentBits(int a, int b) {
int count = 0;
for (int i = 0; i < 32; i++) {
if (((a >> i) & 1) != ((b >> i) & 1)) {
++count;
}
}
return count;
}
static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sortMyMapusingValues(HashMap<String, Integer> hm) {
List<Map.Entry<String, Integer>> capitalList = new LinkedList<>(hm.entrySet());
Collections.sort(capitalList, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
HashMap<String, Integer> result = new HashMap<>();
for (Map.Entry<String, Integer> entry : capitalList) {
result.put(entry.getKey(), entry.getValue());
}
}
static boolean ispowerof2(long num) {
if ((num & (num - 1)) == 0)
return true;
return false;
}
static boolean isPrime(int n) {
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static class Graph {
HashMap<Integer, LinkedList<Integer>> hm = new HashMap<Integer, LinkedList<Integer>>();
private void addVertex(int vertex) {
hm.put(vertex, new LinkedList<>());
}
private void addEdge(int source, int dest, boolean bi) {
if (!hm.containsKey(source))
addVertex(source);
if (!hm.containsKey(dest))
addVertex(dest);
hm.get(source).add(dest);
if (bi) {
hm.get(dest).add(source);
}
}
private boolean uniCycle(int i, HashSet<Integer> visited, int parent) {
visited.add(i);
LinkedList<Integer> list = hm.get(i);
Iterator<Integer> it = list.iterator();
while (it.hasNext()) {
Integer integer = (Integer) it.next();
if (!visited.contains(integer)) {
if (uniCycle(integer, visited, i))
return true;
} else if (integer != parent) {
return true;
}
}
return false;
}
private boolean uniCyclic() {
HashSet<Integer> visited = new HashSet<Integer>();
Set<Integer> set = hm.keySet();
for (Integer integer : set) {
if (!visited.contains(integer)) {
if (uniCycle(integer, visited, -1)) {
return true;
}
}
}
return false;
}
private boolean isbiCycle(int i, HashSet<Integer> visited, HashSet<Integer> countered) {
if (countered.contains(i))
return true;
if (visited.contains(i))
return false;
visited.add(i);
countered.add(i);
LinkedList<Integer> list = hm.get(i);
Iterator<Integer> it = list.iterator();
while (it.hasNext()) {
Integer integer = (Integer) it.next();
if (isbiCycle(integer, visited, countered)) {
return true;
}
}
countered.remove(i);
return false;
}
private boolean isbiCyclic() {
HashSet<Integer> visited = new HashSet<Integer>();
HashSet<Integer> countered = new HashSet<Integer>();
Set<Integer> set = hm.keySet();
for (Integer integer : set) {
if (isbiCycle(integer, visited, countered)) {
return true;
}
}
return false;
}
}
static class Node {
Node left, right;
int data;
public Node(int data) {
this.data = data;
}
public void insert(int val) {
if (val <= data) {
if (left == null) {
left = new Node(val);
} else {
left.insert(val);
}
} else {
if (right == null) {
right = new Node(val);
} else {
right.insert(val);
}
}
}
public boolean contains(int val) {
if (data == val) {
return true;
} else if (val < data) {
if (left == null) {
return false;
} else {
return left.contains(val);
}
} else {
if (right == null) {
return false;
} else {
return right.contains(val);
}
}
}
public void inorder() {
if (left != null) {
left.inorder();
}
System.out.print(data + " ");
if (right != null) {
right.inorder();
}
}
public int maxDepth() {
if (left == null)
return 0;
if (right == null)
return 0;
else {
int ll = left.maxDepth();
int rr = right.maxDepth();
if (ll > rr)
return (ll + 1);
else
return (rr + 1);
}
}
public int countNodes() {
if (left == null)
return 1;
if (right == null)
return 1;
else {
return left.countNodes() + right.countNodes() + 1;
}
}
public void preorder() {
System.out.print(data + " ");
if (left != null) {
left.inorder();
}
if (right != null) {
right.inorder();
}
}
public void postorder() {
if (left != null) {
left.inorder();
}
if (right != null) {
right.inorder();
}
System.out.print(data + " ");
}
public void levelorder(Node node) {
LinkedList<Node> ll = new LinkedList<Node>();
ll.add(node);
getorder(ll);
}
public void getorder(LinkedList<Node> ll) {
while (!ll.isEmpty()) {
Node node = ll.poll();
System.out.print(node.data + " ");
if (node.left != null)
ll.add(node.left);
if (node.right != null)
ll.add(node.right);
}
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static class Pair {
int first, second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
private static final Scanner sc = new Scanner(System.in);
private static final FastReader fs = new FastReader();
private static final OutputWriter op = new OutputWriter(System.out);
static int[] getintarray(int n) {
int ar[] = new int[n];
for (int i = 0; i < n; i++) {
ar[i] = fs.nextInt();
}
return ar;
}
static long[] getlongarray(int n) {
long ar[] = new long[n];
for (int i = 0; i < n; i++) {
ar[i] = fs.nextLong();
}
return ar;
}
static int[][] get2darray(int n, int m) {
int ar[][] = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
ar[i][j] = fs.nextInt();
}
}
return ar;
}
static Pair[] getpairarray(int n) {
Pair ar[] = new Pair[n];
for (int i = 0; i < n; i++) {
ar[i] = new Pair(fs.nextInt(), fs.nextInt());
}
return ar;
}
static void printarray(int ar[]) {
for (int i : ar) {
op.print(i + " ");
}
op.flush();
}
static int fact(int n) {
int fact = 1;
for (int i = 2; i <= n; i++) {
fact *= i;
}
return fact;
}
//
// function to find largest prime factor
}/*
* 1 5 -2 -3 -1 -4 -6till here
*/
// while (t > 0) {
// int a[] = getintarray(3);
// int b[] = getintarray(3);
// int ans = getans(a, b);
// System.out.println(ans);
// } | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | 0ed8ddec6bc30107aa013cf8831c9b4a | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main{
public static void main(String []args)throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));
/*int t=Integer.parseInt(br.readLine());
while(t>0){
//HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>();*/
int n=Integer.parseInt(br.readLine());
String s[]=br.readLine().split(" ");
//int a[]=new int[n];
long count[]=new long[100001];
int m=0;
for(int i=0;i<n;i++){
int a=Integer.parseInt(s[i]);
count[a]++;
m=Math.max(m,a);
}
long max=0;
long dp[]=new long[100001];
dp[0]=0;
dp[1]=count[1];
dp[2]=2*count[2];
max=Math.max(max,Math.max(dp[1],dp[2]));
for(int i=3;i<=m;i++){
dp[i]=Math.max(dp[i-2],dp[i-3])+count[i]*i;
max=Math.max(max,dp[i]);
}
bw.write(max+"\n");
/*t--;
}*/
bw.flush();
}
} | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | db7b28cc7a6ad793fadd2b6b95d549ce | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.IOException;
import java.util.Scanner;
public class Boredom {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long arr[] = new long[100001], dp[] = new long[100001];
int i = 0;
for(i = 0; i < n; i++)
{
arr[sc.nextInt()]++;
}
dp[0] = 0;
dp[1] = arr[1];
for(i = 2;i < 100001; i++)
{
dp[i] = Math.max(dp[i-1], dp[i-2]+arr[i] * (long)i);
}
System.out.println(dp[100000]);
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | 307c108fc63f37f0d5d2804af4cda5f7 | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | // import java.io.IOException;
// import java.util.Scanner;
// public class Boredom {
// public static void main(String[] args) throws IOException {
// Scanner sc = new Scanner(System.in);
// int n = sc.nextInt();
// long arr[] = new long[100001], dp[] = new long[100001];
// int i = 0;
// for(i = 0; i < n; i++)
// {
// arr[sc.nextInt()]++;
// }
// dp[0] = 0;
// dp[1] = arr[i];
// for(i = 2;i < 100001; i++)
// {
// dp[i] = Math.max(dp[i-1], dp[i-2]+arr[i] * (long)i);
// }
// System.out.println(dp[100000]);
// }
// }
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.*;
public class Boredom {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long[] a=new long[100001];
long[] dp=new long[100001];
for(int i=0;i<n;i++){
a[sc.nextInt()]++;
}
dp[0]=0;
dp[1]=a[1];
for(int i=2;i<=100000;i++){
dp[i]=Math.max(dp[i-1],dp[i-2]+a[i]*(long)i);
}
System.out.println(dp[100000]);
}
} | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | c4918941456db2a0a8d0cd314acf5e83 | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.IOException;
import java.util.Scanner;
public class Boredom {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long arr[] = new long[100001], dp[] = new long[100001];
int i = 0;
for(i = 0; i < n; i++)
{
arr[sc.nextInt()]++;
}
dp[0] = 0;
dp[1] = arr[1];
for(i = 2;i < 100001; i++)
{
dp[i] = Math.max(dp[i-1], dp[i-2]+arr[i] * (long)i);
}
System.out.println(dp[100000]);
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | 0fa5617dda328e5d50d9cf666ef8451c | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Scanner;
public class scratch_16{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n =sc.nextInt();
long arr[]= new long[100001];
for (int i = 0; i <n ; i++) {
int x= sc.nextInt();
arr[x]+=x;
}
for (int i = 2; i <100001 ; i++) {
arr[i]= Math.max(arr[i-1],arr[i]+arr[i-2]);
}
System.out.println(arr[100000]);
}} | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | aeeb1477812d60e30df8872d7aa4b2e9 | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Main {
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
// br = new BufferedReader(new FileReader("input.txt"));
// PrintWriter pw = new PrintWriter("output.txt");
int n = nextInt();
long[] a = new long[n];
long[] cnt = new long[100001];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
cnt[(int) a[i]]++;
}
long[] dp = new long[100001];
for (int i = 0; i < cnt.length; i++) {
dp[i] = cnt[i] * i;
}
for (int i = 3; i < dp.length; i++) {
dp[i] += max(dp[i - 2], dp[i - 3]);
}
pw.println(max(dp[dp.length - 1], dp[dp.length - 2]));
pw.close();
}
static StringTokenizer st = new StringTokenizer("");
static BufferedReader br;
static String next() throws IOException {
while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
} | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | e75f1a06681d4580fed687c7a2933022 | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | //package test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
public class compete {
public static void main(String[] args) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
String[] strNum = reader.readLine().split(" ");
long[] num = new long[100001];
for(int i = 0; i<strNum.length; i++){
num[Integer.parseInt(strNum[i])]++;
}
long[] sum = new long[100001];
sum[1] = num[1];
for(int i = 2; i<100001; i++){
sum[i] = Long.max(sum[i-1], i*num[i]+sum[i-2]);
}
System.out.println(sum[100000]);
}
} | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | 7216a60420b264d2515c278177602d12 | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Boredom {
int n, size;
int[] a;
public static void main(final String[] args) throws IOException {
final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
Boredom o = new Boredom();
o.n = Integer.parseInt(bufferedReader.readLine());
o.a = new int[o.n];
String[] input;
input = bufferedReader.readLine().split(" ");
o.size = 1;
for (int i = 0; i < input.length; ++i) {
o.a[i] = Integer.parseInt(input[i]);
o.size = Math.max(o.size, o.a[i]);
}
++o.size;
System.out.println(o.solve());
}
long solve() {
long[] pts;
pts = new long[size];
for (int i: a) pts[i] += i;
long[] dp;
dp = new long[size];
for (int i = 1; i < size; i++) dp[i] = pts[i];
for (int i = 2; i < size; i++) dp[i] = Math.max(Math.max(dp[i], dp[i-1]), dp[i-2]+pts[i]);
return dp[size-1];
}
} | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | 2a4b264a0d75d9e4d3e1e118676c7b39 | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes |
import java.util.*;
public class P455A
{
private final static int MOD = 1_000_000_007;
public static long mod(long a, long b) {
return ((a % b) + b ) % b;
}
public static int mod (int a, int b) {
return ((a % b) + b ) % b;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long[] a=new long[100001];
long[] dp=new long[100001];
for(int i=0;i<n;i++){
a[sc.nextInt()]++;
}
dp[0]=0;
dp[1]=a[1];
for(int i=2;i<=100000;i++){
dp[i]=Math.max(dp[i-1],dp[i-2]+a[i]*(long)i);
}
System.out.println(dp[100000]);
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | c0f83f572477a198fdb2b3df80a71e07 | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes |
import java.io.*;
import java.util.*;
public final class cf {
static long dp[];
static int n;
static HashMap<Integer,Integer>map;
public static void main(String[] args) throws Exception {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(java.io.FileDescriptor.out), "ASCII"), 512);
FastReader sc = new FastReader();
int tc = 1;
int a[];
while (tc-- > 0) {
n=sc.nextInt();
a=new int[n];
dp=new long[100000+3];
map=new HashMap<>();
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
map.put(a[i],map.getOrDefault(a[i], 0)+1);
}
go();
out.write(dp[100000]+"");
}
out.flush();
}
public static void go(){
dp[0]=0;dp[1]=0;
dp[1]=map.getOrDefault(1, 0);
long temp;
long sum;
for(int i=2;i<=100000;i++){
temp=map.getOrDefault(i, 0);
sum=temp*i;
dp[i]=dp[i-2]+sum;
dp[i]=Math.max(dp[i],dp[i-1]);
}
}
///////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//////////////////////////////////////////////////////////////////
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[1002]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
break;
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) {
return -ret;
}
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) {
buffer[0] = -1;
}
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null) {
return;
}
din.close();
}
}
public static void debug(String s) {
System.out.println(s);
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | 5faab395b5b4078105ada8cf229ced70 | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class ladders455a {
static BufferedReader __in;
static PrintWriter __out;
static StringTokenizer input;
public static void main(String[] args) throws IOException {
__in = new BufferedReader(new InputStreamReader(System.in));
__out = new PrintWriter(new OutputStreamWriter(System.out));
int n = ri(), cnt[] = new int[100001];
r();
for(int i = 0; i < n; ++i) {
++cnt[ni()];
}
long[] dp = new long[100001];
dp[1] = cnt[1];
for(int i = 2; i <= 100000; ++i) {
dp[i] = max(dp[i - 1], (long)cnt[i] * i + dp[i - 2]);
}
prln(dp[100000]);
close();
}
// references
// IMAX ~= 2e10
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IRAND = 327859546;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {assert x.length >= 2; return x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));}
static int minstarting(int offset, int... x) {assert x.length >= 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {assert x.length >= 2; return x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));}
static long minstarting(int offset, long... x) {assert x.length >= 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));}
static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int floori(double d) {return (int)d;}
static int ceili(double d) {return (int)ceil(d);}
static long floorl(double d) {return (long)d;}
static long ceill(double d) {return (long)ceil(d);}
// input
static void r() throws IOException {input = new StringTokenizer(__in.readLine());}
static int ri() throws IOException {return Integer.parseInt(__in.readLine());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;}
static char[] rcha() throws IOException {return __in.readLine().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static int ni() {return Integer.parseInt(input.nextToken());}
static long nl() {return Long.parseLong(input.nextToken());}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {__out.println("yes");}
static void pry() {__out.println("Yes");}
static void prY() {__out.println("YES");}
static void prno() {__out.println("no");}
static void prn() {__out.println("No");}
static void prN() {__out.println("NO");}
static void pryesno(boolean b) {__out.println(b ? "yes" : "no");};
static void pryn(boolean b) {__out.println(b ? "Yes" : "No");}
static void prYN(boolean b) {__out.println(b ? "YES" : "NO");}
static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), i++); __out.println(a[a.length - 1]);}
static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), i++); __out.println(a[a.length - 1]);}
static void flush() {__out.flush();}
static void close() {__out.close();}
// debug
static void debug(String desc, int... a) {System.out.print(desc); System.out.print(": "); for(int i = 0, len = a.length - 1; i < len; System.out.print(a[i]), System.out.print(", "), i++); System.out.println(a[a.length - 1]);}
static void debug(String desc, long... a) {System.out.print(desc); System.out.print(": "); for(int i = 0, len = a.length - 1; i < len; System.out.print(a[i]), System.out.print(", "), i++); System.out.println(a[a.length - 1]);}
} | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | 720cc421dbb0445c8c863f85b21fb1a6 | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
private static void solver(InputReader sc, PrintWriter out) throws Exception {
int n = sc.nextInt();
long arr[] = new long[100001];
for (int i = 0; i < n; i++) {
arr[sc.nextInt()]++;
}
long dp[] = new long[100000 + 1];
dp[0] = 0;
dp[1] = arr[1];
for (int i = 2; i <= 100000; i++) {
dp[i] = Math.max(dp[i - 1], dp[i - 2] + (arr[i] * i));
}
out.println(dp[100000]);
}
private static int gcd (int a, int b) {
if (b == 0)
return a;
else
return gcd (b, a % b);
}
private static long helper(long x){
long ans = (x * (x-1))/2;
return ans;
}
public static void main(String[] args) throws Exception {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solver(in,out);
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int[] readIntArray(int n){
int arr[] = new int[n];
for(int i=0;i<n;i++) arr[i] = nextInt();
return arr;
}
}
}
class Pair implements Comparable<Pair>{
int x;
long y;
Pair(int x, long y){
this.x =x ;
this.y =y;
}
public int compareTo(Pair p) {
return (int)(p.y - this.y);
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | 24287d593526c9c53c95d927114ac303 | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes |
import java.util.Scanner;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author GodOfWar
*/
public class Dp0 {
public static void main(String[] args) {// 1 1
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
long[] in=new long[100003];
long[] dp=new long[100003];
for(int i=0;i<n;i++){
in[sc.nextInt()]++;
}
dp[0]=0;
dp[1]=in[1];
for(int i=2;i<100003;i++){
dp[i]=Math.max((i*in[i])+dp[i-2], dp[i-1]);
}
System.out.println(dp[100002]);
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | b373b08056d8fdf7f84ddb035fe02752 | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class Main {
public static void main(String[] args) throws IOException {
// br = new BufferedReader(new FileReader(new File("input.txt")));
// out = new PrintWriter(new File("output.txt"));
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
int PUTEN = 1;
while (PUTEN-- > 0) {
int n = nextInt();
long[] a = new long[n];
long[] cnt = new long[100001];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
cnt[(int) a[i]]++;
}
long[] dp = new long[100001];
for (int i = 0; i < cnt.length; i++) {
dp[i] = cnt[i] * i;
}
for (int i = 3; i < dp.length; i++) {
dp[i] += max(dp[i - 2], dp[i - 3]);
}
out.println(max(dp[dp.length - 1], dp[dp.length - 2]));
}
out.close();
}
static BufferedReader br;
static PrintWriter out;
static StringTokenizer in = new StringTokenizer("");
static String next() throws IOException {
while (!in.hasMoreTokens()) {
in = new StringTokenizer(br.readLine());
}
return in.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | 43040f5be5f36b22438f0c68da6cd4e0 | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.*;
import java.util.*;
public class Q2 {
public static void main(String[] args)throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String[] ss=br.readLine().split(" ");
int n=Integer.parseInt(ss[0]);
ss=br.readLine().split(" ");
int[] a=new int[n+1];
int[] cnt=new int[100001];
for(int i=1;i<=n;i++)
{ a[i]=Integer.parseInt(ss[i-1]);
cnt[a[i]]++;
}
Arrays.sort(a);
ArrayList<Integer> arr=new ArrayList<>();
HashMap<Integer,Integer> map=new HashMap<>();
arr.add(0);
for(int i=1;i<=n;i++)
{
if(map.containsKey(a[i])==true)
continue;
else
{
map.put(a[i],1);
arr.add(a[i]);
}
}
n=arr.size();
long[] dp=new long[n];
dp[1]=(long)(arr.get(1))*cnt[arr.get(1)];
for(int i=2;i<n;i++)
{ if(arr.get(i)==arr.get(i-1)+1)
dp[i]=Math.max(dp[i-1],dp[i-2]+cnt[arr.get(i)]*(long)(arr.get(i)));
else
dp[i]=dp[i-1]+(long)(arr.get(i))*cnt[arr.get(i)];
}
System.out.println(dp[n-1]);
}
} | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | a0b83a2ec82e71fbb2613d02facba5a3 | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import javax.print.DocFlavor;
import java.awt.*;
import java.io.*;
import java.math.*;
import java.util.*;
public class Codeforce {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
Solver solver = new Solver();
solver.solve(in,out);
out.close();
}
static class Solver{
boolean correct;
public void solve(InputReader in, OutputWriter out){
int t = in.nextInt();
long occ[][] = new long[2][100001];
for(int i=0;i<t;i++){
occ[0][in.nextInt()]++;
}
occ[1][0]=0;
occ[1][1]=occ[0][1];
for(int i=2;i<100001;i++){
occ[1][i]= Math.max(occ[1][i-1],occ[1][i-2]+occ[0][i]*i);
}
out.printf("%d",occ[1][100000]);
}
private int bfs(){
ArrayList<Integer> queue = new ArrayList<>();
//queue.add(i);
while (!queue.isEmpty()){
int cur = queue.remove(0);
//visited[cur] = true;
for(int j=0;j<0;j++){
}
}
return 0;
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1 << 16];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (this.numChars == -1) {
throw new InputMismatchException();
} else {
if (this.curChar >= this.numChars) {
this.curChar = 0;
try {
this.numChars = this.stream.read(this.buf);
} catch (IOException var2) {
throw new InputMismatchException();
}
if (this.numChars <= 0) {
return -1;
}
}
return this.buf[this.curChar++];
}
}
public int nextInt() {
int c;
for (c = this.read(); isSpaceChar(c); c = this.read()) {
;
}
byte sgn = 1;
if (c == 45) {
sgn = -1;
c = this.read();
}
int res = 0;
while (c >= 48 && c <= 57) {
res *= 10;
res += c - 48;
c = this.read();
if (isSpaceChar(c)) {
return res * sgn;
}
}
throw new InputMismatchException();
}
public String next() {
int c;
while (isSpaceChar(c = this.read())) {
;
}
StringBuilder result = new StringBuilder();
result.appendCodePoint(c);
while (!isSpaceChar(c = this.read())) {
result.appendCodePoint(c);
}
return result.toString();
}
public static boolean isSpaceChar(int c) {
return c == 32 || c == 10 || c == 13 || c == 9 || c == -1;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void printf(String format, Object... objects) {
writer.printf(format, objects);
}
public void close() {
writer.close();
}
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | 70c55e381cfc8cffda89316f510513e8 | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.util.Scanner;
public class boredom {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
int n = s.nextInt();
long arr[] = new long[100001];
for(int i = 0;i<n;++i)
{
int k = s.nextInt();
arr[k] += k;
}
long inc = 0;
long exc = 0;
for(int i = 1;i<arr.length;++i)
{
long temp = arr[i] + exc;
exc = Math.max(inc, exc);
inc = temp;
}
System.out.print(Math.max(inc, exc));
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | 5458881f29ab8e01e277354c7f671992 | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.*;
import java.util.*;
public class A455
{
static Scanner sc;
public static void main(String args[])throws IOException{
sc = new Scanner(System.in);
int t = 1;
while(t-->0){
solve();
}
}
static void solve(){
int n = sc.nextInt();
long a[] = new long[100001];
for(int i=0; i<n; i++){
int x = sc.nextInt();
a[x]+=x;
}
for(int i=2; i<100001; i++){
a[i] = Math.max(a[i]+a[i-2], a[i-1]);
}
System.out.println(a[100000]);
}
static class Pair{
int a, b;
Pair(int a, int b){
this.a = a;
this.b = b;
}
}
} | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | 2807a0aaff6b89e37582e8c1745d5e7a | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.TreeSet;
public class practice_DP {
static Reader r = new Reader();
static PrintWriter out = new PrintWriter(System.out);
private static void solve1() throws IOException {
int t = r.nextInt();
StringBuilder res = new StringBuilder();
while (t-- > 0) {
int n = r.nextInt();
int m = r.nextInt();
int x = r.nextInt();
int y = r.nextInt();
char ch[][] = new char[n][m];
long ans = 0;
for (int i = 0; i < n; i++) {
ch[i] = r.next().toCharArray();
for (int j = 0; j < m; j++) {
if (ch[i][j] == '.') {
if (j + 1 < m && ch[i][j + 1] == '.') {
if (2 * x < y) {
ans += 2 * x;
} else {
ans += y;
}
j++;
} else {
ans += x;
}
}
}
}
res.append(ans).append("\n");
}
out.print(res);
out.close();
}
private static void solve2() throws IOException {
StringBuilder res = new StringBuilder();
int n = r.nextInt();
int k = r.nextInt();
int arr[] = r.nextIntArray(n);
int cnt = 0;
for (int i = 1; i < n; i++) {
if (arr[i] + arr[i - 1] < k) {
cnt += k - (arr[i] + arr[i - 1]);
arr[i] += k - (arr[i] + arr[i - 1]);
}
}
res.append(cnt).append("\n");
for (int i = 0; i < n; i++) {
res.append(arr[i] + " ");
}
out.print(res);
out.close();
}
private static void solve3() throws IOException {
int n = r.nextInt();
int ans = 0;
if ((n & 1) != 0) {
ans = 0;
} else {
ans = (int) Math.pow(2, n / 2);
}
out.print(ans);
out.close();
}
private static void solve4() throws IOException {
int n = r.nextInt();
int cnt = 0;
ArrayList<Integer> ans = new ArrayList<Integer>();
int start = 1, sum = 0;
while (true) {
sum += start;
if (sum > n) {
sum -= start;
break;
} else {
ans.add(start++);
}
}
// System.out.println(sum);
// System.out.println(ans);
ans.set(ans.size() - 1, ans.get(ans.size() - 1) + (n - sum));
out.print(ans.size() + "\n");
for (int candies : ans) {
out.print(candies + " ");
}
out.close();
}
private static void solve5() throws IOException {
int n = r.nextInt();
int fibo[] = new int[21];
fibo[0] = fibo[1] = 1;
for (int i = 2; i <= 20; i++) {
fibo[i] = (fibo[i - 1] + fibo[i - 2]);
}
out.print(fibo[n]);
out.close();
}
private static int binarySearch6(int ele) {
int lt = 0, rt = arr.length - 1;
int ans = 0;
while (lt <= rt) {
int mid = (lt + rt) / 2;
if (arr[mid] > ele) {
rt = mid - 1;
} else {
ans = mid + 1;
lt = mid + 1;
}
}
return ans;
}
private static void solve6() throws IOException {
StringBuilder res = new StringBuilder();
int n = r.nextInt();
arr = r.nextIntArray(n);
Arrays.sort(arr);
int q = r.nextInt();
while (q-- > 0) {
int ele = r.nextInt();
res.append(binarySearch6(ele)).append("\n");
}
out.print(res);
out.close();
}
private static void solve7() throws IOException {
String s = r.next();
int dp1[] = new int[s.length() + 1];
int dp2[] = new int[s.length() + 1];
dp1[0] = dp2[0] = 0;
for (int i = 0; i < s.length(); i++) {
dp1[i + 1] = dp1[i];
dp2[i + 1] = dp2[i];
if (s.charAt(i) == '.') {
if (i + 1 < s.length() && s.charAt(i + 1) == '.') {
dp1[i + 1]++;
}
} else {
if (i + 1 < s.length() && s.charAt(i + 1) == '#') {
dp2[i + 1]++;
}
}
}
// System.out.println(Arrays.toString(dp1));
// System.out.println(Arrays.toString(dp2));
int m = r.nextInt();
while (m-- > 0) {
int lt = r.nextInt() - 1;
int rt = r.nextInt() - 1;
out.print(dp1[rt] - dp1[lt] + dp2[rt] - dp2[lt] + "\n");
}
out.close();
}
static class Query {
int pos, val;
public Query(int idx, int vali) {
pos = idx;
val = vali;
}
}
static int cnt = 0, freq[], arr[];
private static void add(int idx) {
if (freq[arr[idx]] == 0) {
cnt++;
}
freq[arr[idx]]++;
}
private static void remove(int idx) {
freq[arr[idx]]--;
if (freq[arr[idx]] == 0) {
cnt--;
}
}
private static void solve8() throws IOException {
int n = r.nextInt();
int m = r.nextInt();
arr = new int[n + 1];
freq = new int[(int) 1e5 + 1];
Query q[] = new Query[m];
for (int i = 1; i <= n; i++) {
arr[i] = r.nextInt();
add(i);
}
// Applying MO's Algorithm
for (int i = 0; i < m; i++) {
q[i] = new Query(i, r.nextInt());
}
Arrays.sort(q, new Comparator<Query>() {
@Override
public int compare(Query o1, Query o2) {
return o1.val - o2.val;
}
});
int ans[] = new int[m];
int lt = 1;
for (int i = 0; i < m; i++) {
int val = q[i].val;
while (lt < val) {
remove(lt++);
}
ans[q[i].pos] = cnt;
}
for (int i = 0; i < m; i++) {
out.println(ans[i]);
}
out.close();
}
private static void solve9() throws IOException {
int n = r.nextInt();
int k = r.nextInt();
int dp[] = r.nextIntArray(n);
for (int i = 1; i < n; i++) {
dp[i] += dp[i - 1];
}
int min = dp[k - 1], ans = 0;
for (int i = k; i < n; i++) {
if (dp[i] - dp[i - k] < min) {
min = dp[i] - dp[i - k];
ans = i - k + 1;
}
}
out.print(++ans);
out.close();
}
private static long sum(long n) {
return ((n * (3 * n + 1)) / 2);
}
private static long binarySearch10(long n) {
long lt = 1, rt = n;
long ans = 0;
while (lt <= rt) {
long mid = (lt + rt) / 2;
long val = sum(mid);
if (val <= n) {
ans = mid;
lt = mid + 1;
} else {
rt = mid - 1;
}
}
return ans;
}
private static void solve10() throws IOException {
int t = r.nextInt();
while (t-- > 0) {
long n = r.nextLong();
long cnt = 0;
while (n > 1) {
long tallest = binarySearch10(n);
cnt++;
n -= sum(tallest);
}
out.println(cnt);
}
out.close();
}
private static void solve11() throws IOException {
int a1 = r.nextInt();
int a2 = r.nextInt();
int temp = a1;
a1 = Math.min(a1, a2);
a2 = Math.max(a2, temp);
int cnt = 0;
while (a1 > 0 && a2 > 0) {
if (a1 <= 1 && a2 <= 1) {
break;
}
if (a1 > 2) {
cnt++;
a1 -= 2;
a2++;
} else {
cnt++;
a1++;
a2 -= 2;
}
}
out.print(cnt);
out.close();
}
private static int digitSum(int num) {
int sum = 0;
while (num > 0) {
sum += (num % 10);
num /= 10;
}
return sum;
}
private static void solve12() throws IOException {
int k = r.nextInt();
int num = 18;
while (k > 0) {
if (digitSum(++num) == 10) {
k--;
}
}
out.print(num);
out.close();
}
private static void solve13() throws IOException {
int n = r.nextInt();
int h[] = new int[n];
int w[] = new int[n];
int hi[] = new int[n];
int w_cumu = 0;
for (int i = 0; i < n; i++) {
w[i] = r.nextInt();
w_cumu += w[i];
h[i] = r.nextInt();
hi[i] = h[i];
}
Arrays.sort(hi);
for (int i = 0; i < n; i++) {
int ans = (w_cumu - w[i]);
if (hi[n - 1] == h[i]) {
ans *= hi[n - 2];
} else {
ans *= hi[n - 1];
}
out.print(ans + " ");
}
out.close();
}
private static long maxDigit(long num) {
long max = -1;
while (num > 0) {
long digit = num % 10;
num /= 10;
max = Math.max(max, digit);
}
return max;
}
private static void solve14() throws IOException {
long n = r.nextLong();
long cnt = 0;
while (n > 0) {
n -= maxDigit(n);
cnt++;
}
out.print(cnt);
out.close();
}
private static void solve15() throws IOException {
int n = r.nextInt();
int arr[] = r.nextIntArray(n);
int dp[] = new int[n + 1];
int tot = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == 0) {
dp[i + 1] = 1;
} else {
tot++;
dp[i + 1] = -1;
}
}
for (int i = 1; i <= n; i++) {
dp[i] += dp[i - 1];
}
int max = Integer.MIN_VALUE;
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
if (tot + dp[i] - dp[j - 1] > max) {
max = tot + dp[i] - dp[j - 1];
}
}
}
out.print(max);
out.close();
}
private static void solve16() throws IOException {
int t = r.nextInt();
while (t-- > 0) {
int n = r.nextInt();
int arr[] = r.nextIntArray(n);
ArrayList<Integer> sub_seq = new ArrayList<Integer>();
int i = 0;
while (i < n) {
int max = Integer.MIN_VALUE;
while (i < n && arr[i] < 0) {
max = Math.max(max, arr[i++]);
}
if (max != Integer.MIN_VALUE)
sub_seq.add(max);
max = Integer.MIN_VALUE;
while (i < n && arr[i] > 0) {
max = Math.max(max, arr[i++]);
}
if (max != Integer.MIN_VALUE)
sub_seq.add(max);
}
long sum = 0;
for (int ele : sub_seq) {
sum += ele;
}
out.print(sum + "\n");
}
out.close();
}
private static void solve17() throws IOException {
int t = r.nextInt();
while (t-- > 0) {
int n = r.nextInt();
int arr[] = r.nextIntArray(n);
Arrays.sort(arr);
int max = Integer.MIN_VALUE, cnt = 0, ans = 0;
for (int i = 0; i < n; i++) {
max = Math.max(max, arr[i]);
cnt++;
if (max == cnt) {
max = Integer.MIN_VALUE;
cnt = 0;
ans++;
}
}
out.print(ans + "\n");
}
out.close();
}
private static void solve18() throws IOException {
int t = r.nextInt();
while (t-- > 0) {
char str[] = r.next().toCharArray();
TreeSet<Integer> one = new TreeSet<>();
TreeSet<Integer> two = new TreeSet<>();
TreeSet<Integer> three = new TreeSet<>();
for (int i = 0; i < str.length; i++) {
if (str[i] == '1') {
one.add(i);
} else if (str[i] == '2') {
two.add(i);
} else {
three.add(i);
}
}
int min = Integer.MAX_VALUE;
for (int idx1 : one) {
int len1 = Integer.MAX_VALUE, len2 = Integer.MAX_VALUE;
if (two.higher(idx1) != null) {
int idx2 = two.higher(idx1);
if (three.higher(idx2) != null) {
int idx3 = three.higher(idx2);
len1 = Math.min(len1, idx3 - idx1 + 1);
}
}
if (three.higher(idx1) != null) {
int idx2 = three.higher(idx1);
if (two.higher(idx2) != null) {
int idx3 = two.higher(idx2);
len2 = Math.min(len2, idx3 - idx1 + 1);
}
}
min = Math.min(Math.min(len1, len2), min);
}
for (int idx1 : two) {
int len1 = Integer.MAX_VALUE, len2 = Integer.MAX_VALUE;
if (one.higher(idx1) != null) {
int idx2 = one.higher(idx1);
if (three.higher(idx2) != null) {
int idx3 = three.higher(idx2);
len1 = Math.min(len1, idx3 - idx1 + 1);
}
}
if (three.higher(idx1) != null) {
int idx2 = three.higher(idx1);
if (one.higher(idx2) != null) {
int idx3 = one.higher(idx2);
len2 = Math.min(len2, idx3 - idx1 + 1);
}
}
min = Math.min(Math.min(len1, len2), min);
}
for (int idx1 : three) {
int len1 = Integer.MAX_VALUE, len2 = Integer.MAX_VALUE;
if (two.higher(idx1) != null) {
int idx2 = two.higher(idx1);
if (one.higher(idx2) != null) {
int idx3 = one.higher(idx2);
len1 = Math.min(len1, idx3 - idx1 + 1);
}
}
if (one.higher(idx1) != null) {
int idx2 = one.higher(idx1);
if (two.higher(idx2) != null) {
int idx3 = two.higher(idx2);
len2 = Math.min(len2, idx3 - idx1 + 1);
}
}
min = Math.min(Math.min(len1, len2), min);
}
if (min == Integer.MAX_VALUE) {
min = 0;
}
out.println(min);
}
out.close();
}
private static void solve19() throws IOException {
int n = r.nextInt();
long arr[] = new long[n + 1];
long sorted[] = new long[n + 1];
for (int i = 1; i <= n; i++) {
arr[i] = r.nextLong();
sorted[i] = arr[i];
}
Arrays.sort(sorted);
for (int i = 1; i <= n; i++) {
arr[i] += arr[i - 1];
sorted[i] += sorted[i - 1];
}
int m = r.nextInt();
StringBuilder ans = new StringBuilder();
while (m-- > 0) {
int type = r.nextInt();
int lt = r.nextInt();
int rt = r.nextInt();
long an = 0;
if (type == 1) {
an = arr[rt] - arr[lt - 1];
} else {
an = sorted[rt] - sorted[lt - 1];
}
ans.append(an).append("\n");
}
out.print(ans);
out.close();
}
private static void solve20() throws IOException {
int n = r.nextInt();
long arr[] = r.nextLongArray(n);
long dp[][] = new long[n][1 << n];
for (int i = 0; i < n; i++) {
Arrays.fill(dp[i], -1);
}
dp[0][0] = arr[0];
dp[0][1] = -arr[0];
for (int i = 1; i < n; i++) {
int idx = 0;
for (int j = 0; j < dp[i - 1].length; j++) {
if (dp[i - 1][j] != -1) {
dp[i][idx++] = dp[i - 1][j] + arr[i];
dp[i][idx++] = dp[i - 1][j] - arr[i];
} else {
idx++;
}
}
}
boolean flag = false;
for (int i = 0; i < dp[0].length; i++) {
if (Math.abs(dp[n - 1][i]) % 360 == 0) {
flag = true;
break;
}
}
out.print(flag ? "YES" : "NO");
out.close();
}
private static void solve21() throws IOException {
int n = r.nextInt();
int k = r.nextInt();
HashSet<Character> set = new HashSet<>();
char str[] = r.next().toCharArray();
for (int i = 0; i < k; i++) {
set.add(r.next().charAt(0));
}
long ans = 0, cnt = 0;
boolean flag = false;
for (int i = 0; i < str.length; i++) {
if (set.contains(str[i])) {
cnt++;
flag = true;
} else {
if (flag) {
flag = false;
ans += ((cnt * (cnt + 1)) / 2);
cnt = 0;
}
}
}
if (flag)
ans += ((cnt * (cnt + 1)) / 2);
out.print(ans);
out.close();
}
private static void solve22() throws IOException {
int n = r.nextInt();
long freq[] = new long[(int) 1e5 + 1];
for (int i = 0; i < n; i++) {
freq[r.nextInt()]++;
}
long dp[] = new long[(int) 1e5 + 1];
dp[0] = 0;
dp[1] = freq[1];
for (int i = 2; i <= 100000; i++) {
dp[i] = Math.max(dp[i - 1], (long) freq[i] * i + dp[i - 2]);
}
out.print(dp[100000]);
out.close();
}
public static void main(String[] args) throws IOException {
// solve1();
// solve2();
// solve3();
// solve4();
// solve5();
// solve6();
// solve7();
// solve8();
// solve9();
// solve10();
// solve11();
// solve12();
// solve13();
// solve14();
// solve15();
// solve16();
// solve17();
// solve18();
// solve19();
// solve20();
// solve21();
solve22();
}
static class Reader {
final private int BUFFER_SIZE = 1 << 12;
boolean consume = false;
private byte[] buffer;
private int bufferPointer, bytesRead;
private boolean reachedEnd = false;
public Reader() {
buffer = new byte[BUFFER_SIZE];
bufferPointer = 0;
bytesRead = 0;
}
public boolean hasNext() {
return !reachedEnd;
}
private void fillBuffer() throws IOException {
bytesRead = System.in.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) {
buffer[0] = -1;
reachedEnd = true;
}
}
private void consumeSpaces() throws IOException {
while (read() <= ' ' && reachedEnd == false)
;
bufferPointer--;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
public String next() throws IOException {
StringBuilder sb = new StringBuilder();
consumeSpaces();
byte c = read();
do {
sb.append((char) c);
} while ((c = read()) > ' ');
if (consume) {
consumeSpaces();
}
;
if (sb.length() == 0) {
return null;
}
return sb.toString();
}
public String nextLine() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
return str;
}
public int nextInt() throws IOException {
consumeSpaces();
int ret = 0;
byte c = read();
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (consume) {
consumeSpaces();
}
if (neg) {
return -ret;
}
return ret;
}
public long nextLong() throws IOException {
consumeSpaces();
long ret = 0;
byte c = read();
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10L + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (consume) {
consumeSpaces();
}
if (neg) {
return -ret;
}
return ret;
}
public double nextDouble() throws IOException {
consumeSpaces();
double ret = 0;
double div = 1;
byte c = read();
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (consume) {
consumeSpaces();
}
if (neg) {
return -ret;
}
return ret;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
public int[][] nextIntMatrix(int n, int m) throws IOException {
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++) {
grid[i] = nextIntArray(m);
}
return grid;
}
public char[][] nextCharacterMatrix(int n) throws IOException {
char[][] a = new char[n][];
for (int i = 0; i < n; i++) {
a[i] = next().toCharArray();
}
return a;
}
public void close() throws IOException {
if (System.in == null) {
return;
} else {
System.in.close();
}
}
}
} | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | f504ac78eb3556bcde4d9f726647db5a | train_003.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to akβ+β1 and akβ-β1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | /*
Modassir_Ali
algo.java
*/
import java.util.*;
import java.io.*;
import java.util.Stack ;
import java.util.HashSet;
import java.util.HashMap;
public class A_CF260D1
{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static FastReader sc = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
static int ni()throws IOException{return sc.nextInt();}
static long nl()throws IOException{return sc.nextLong();}
static int[][] nai2(int n,int m)throws IOException{int a[][] = new int[n][m];for(int i=0;i<n;i++)for(int j=0;j<m;j++)a[i][j] = ni();return a;}
static int[] nai(int N,int start)throws IOException{int[]A=new int[N+start];for(int i=start;i!=(N+start);i++){A[i]=ni();}return A;}
static Integer[] naI(int N,int start)throws IOException{Integer[]A=new Integer[N+start];for(int i=start;i!=(N+start);i++){A[i]=ni();}return A;}
static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;}
static void print(int arr[]){for(int i=0;i<arr.length;i++)out.print(arr[i]+" ");out.println();}
static void print(long arr[]){for(int i=0;i<arr.length;i++)out.print(arr[i]+" ");out.println();}
static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);}
static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);}
static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));} // return the number of set bits.
static boolean isPrime(int number){if(number==1) return false;if (number == 2 || number == 3){return true;}if (number % 2 == 0) {return false;}int sqrt = (int) Math.sqrt(number) + 1;for(int i = 3; i < sqrt; i += 2){if (number % i == 0){return false;}}return true;}
static boolean isPrime(long number){if(number==1) return false;if (number == 2 || number == 3){return true;}if (number % 2 == 0) {return false;}long sqrt = (long) Math.sqrt(number) + 1;for(int i = 3; i < sqrt; i += 2){if (number % i == 0){return false;}}return true;}
static int power(int n,int p){if(p==0)return 1;int a = power(n,p/2);a = a*a;int b = p & 1;if(b!=0){a = n*a;}return a;}
static long power(long n,long p){if(p==0)return 1;long a = power(n,p/2);a = a*a;long b = p & 1;if(b!=0){a = n*a;}return a;}
static void reverse(int[] a) {int b;for (int i = 0, j = a.length - 1; i < j; i++, j--) {b = a[i];a[i] = a[j];a[j] = b;}}
static void reverse(long[] a) {long b;for (int i = 0, j = a.length - 1; i < j; i++, j--) {b = a[i];a[i] = a[j];a[j] = b;}}
static void swap(int a[],int i,int j){a[i] = a[i] ^ a[j];a[j] = a[j] ^ a[i];a[i] = a[i] ^ a[j];}
static void swap(long a[],int i,int j){a[i] = a[i] ^ a[j];a[j] = a[j] ^ a[i];a[i] = a[i] ^ a[j];}
static int count(int n){int c=0;while(n>0){c++;n = n/10;}return c;}
static int[] prefix_sum(int a[],int n){int s[] = new int[n];s[0] = a[0];for(int i=1;i<n;i++){s[i] = a[i]+s[i-1];}return s;}
static long[] prefix_sum_int(int a[],int n){long s[] = new long[n];s[0] = (long)a[0];for(int i=1;i<n;i++){s[i] = ((long)a[i])+s[i-1];}return s;}
static long[] prefix_sum_Integer(Integer a[],int n){long s[] = new long[n];s[0] = (long)a[0];for(int i=1;i<n;i++){s[i] = ((long)a[i])+s[i-1];}return s;}
static long[] prefix_sum_long(long a[],int n){long s[] = new long[n];s[0] = a[0];for(int i=1;i<n;i++){s[i] = a[i]+s[i-1];}return s;}
static boolean isPerfectSquare(double x){double sr = Math.sqrt(x);return ((sr - Math.floor(sr)) == 0);}
static ArrayList<Integer> sieve(int n) {int k=0; boolean prime[] = new boolean[n+1];ArrayList<Integer> p_arr = new ArrayList<>();for(int i=0;i<n;i++) prime[i] = true;for(int p = 2; p*p <=n; p++){ k=p;if(prime[p] == true) { p_arr.add(p);for(int i = p*2; i <= n; i += p) prime[i] = false; } }for(int i = k+1;i<=n;i++){if(prime[i]==true)p_arr.add(i);}return p_arr;}
static boolean[] seive_check(int n) {boolean prime[] = new boolean[n+1];for(int i=0;i<n;i++) prime[i] = true;for(int p = 2; p*p <=n; p++){ if(prime[p] == true) { for(int i = p*2; i <= n; i += p) prime[i] = false; } }prime[1]=false;return prime;}
static int get_bits(int n){int p=0;while(n>0){p++;n = n>>1;}return p;}
static int get_bits(long n){int p=0;while(n>0){p++;n = n>>1;}return p;}
static int get_2_power(int n){if((n & (n-1))==0)return get_bits(n)-1;return -1;}
static int get_2_power(long n){if((n & (n-1))==0)return get_bits(n)-1;return -1;}
static long cnt[] = new long[100001] ;
static long dp[] = new long[100001] ;
static void close(){out.flush();}
/*-------------------------Main Code Starts(algo.java)----------------------------------*/
public static void main(String[] args) throws IOException {
int n = ni() ;
// LinkedList<Integer> list = new LinkedList<>() ;
long arr[] = new long[n] ;
for(int i=0 ; i<n ; i++){
arr[i] = nl() ;
cnt[(int)arr[i]]++ ;
}
Arrays.fill(dp,-1) ;
// frequency(arr, n);
System.out.println(result(arr, n));
}
static long solve(long arr[], int n){
if(dp[n]!=-1){
return dp[n] ;
}
if(n==0){
return dp[n]=0 ;
}
if(n==1){
return dp[n]=cnt[1] ;
}
else{
return dp[n]=Math.max(solve(arr, n-1), solve(arr, n-2)+cnt[n]*(n)) ;
}
}
static long result(long arr[],int n){
dp[0] = 0 ;
dp[1] = cnt[1] ;
for(int i=2 ; i<100001 ; i++){
dp[i] = Math.max(dp[i-1],dp[i-2]+cnt[i]*i) ;
}
return dp[100000] ;
}
static void frequency(long arr[],int n){
HashMap<Long,Integer> map = new HashMap<>() ;
for(long x : arr){
Integer count = map.get(x) ;
if(count==null){
map.put(x,1) ;
}
else{
count++ ;
map.put(x,count) ;
}
}
for(long x: map.keySet()){
cnt[(int)x] = map.get(x) ;
}
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2,β2,β2,β2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1ββ€βnββ€β105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1ββ€βaiββ€β105). | 1,500 | Print a single integer β the maximum number of points that Alex can earn. | standard output | |
PASSED | 2cbe28526758d1abff34e286d1380c87 | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes | // 4 8 15 16 23 42
// 4 7 1 7 19
// 3 3 10
// 2 3 6
//package com.company;
import java.util.*;
public class Main {
public static void main(String[] args) {
// write your code here
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[][] pairs = new int[n][2];
for(int i = 0; i < n; i++) {
pairs[i][1] = scan.nextInt();
pairs[i][0] = scan.nextInt();
}
Arrays.sort(pairs, (int[] lhs, int[] rhs)->
lhs[0] == rhs[0] ? Integer.compare(rhs[1], lhs[1]) : Integer.compare(rhs[0], lhs[0]));
/*for(int i = 0; i < n; i++) {
System.out.println(pairs[i][0] + ", " + pairs[i][1]);
}*/
long[][] dp = new long[n][4];
long MOD = 1000000007L;
Map<Integer, Integer> outToPos = new HashMap<>();
for(int i = 0; i < n; i++) outToPos.put(pairs[i][0], i);
int[] vols = new int[2 * n];
for(int i = 0; i < n; i++) {
vols[2 * i] = pairs[i][0];
vols[2 * i + 1] = pairs[i][1];
}
Arrays.sort(vols);
int next = -1;
for(int i = vols.length - 1; i >= 0; i--) {
if (!outToPos.containsKey(vols[i]) && next != -1) {
outToPos.put(vols[i], outToPos.get(next));
} else if (outToPos.containsKey((vols[i]))) {
next = vols[i];
}
}
dp[0][0] = pairs[0][0];
dp[0][1] = pairs[0][0];
dp[0][2] = 1;
dp[0][3] = 1;
for(int i = 1; i < n; i++) {
int j = outToPos.containsKey(pairs[i][1]) ? outToPos.get(pairs[i][1]) : -1;
if (j == -1) {
dp[i][0] = pairs[i][0];
dp[i][2] = 1;
} else {
dp[i][0] = dp[j][1] - (pairs[i][1] - pairs[i][0]);
dp[i][2] = dp[j][3];
}
dp[i][1] = dp[i - 1][1];
dp[i][3] = dp[i - 1][3];
if (dp[i][0] == dp[i][1]) {
dp[i][3] = (dp[i][3] + dp[i][2]) % MOD;
} else if (dp[i][0] < dp[i][1]) {
dp[i][1] = dp[i][0];
dp[i][3] = dp[i][2];
}
}
System.out.println(dp[n - 1][3]);
}
}
| Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | e3e6c7716693f1b6d1c237a3a6a4a520 | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes | import java.util.*;
import java.math.*;
// **** E. Culture Code ****
public class E {
static char [] in = new char [1000000];
static long MOD = 1000000007L;
public static void main (String [] arg) throws Throwable {
int n = nextInt();
Pair [] M = new Pair [n];
for (int i =0; i<n; ++i) {
int out = nextInt();
int in = nextInt();
M[i] = new Pair(in, out, out);
}
Arrays.sort(M);
HashMap<Integer, Integer> H = new HashMap<Integer,Integer>();
int max_in = 0;
for (int i = 0; i<n; ++i) {
int out = M[i].j;
H.put(out, i);
max_in = Math.max(M[i].in, max_in);
}
long [] dp = new long [n];
long [] cnt = new long [n];
long ans = 0;
dp[0] = M[0].in;
cnt[0] = 1;
for (int i = 1; i<n; ++i) {
int out = M[i].out;
int in = M[i].in;
int prev_index = findPos(M, H, in);
// If none lower.
//System.err.println("Checking " + i + " with " + in + " , " + out);
int extra_skip = out - M[i-1].out;
long skip_val = dp[i-1] + extra_skip;
long skip_cnt = cnt[i-1];
//if (prev_index == -1) {
// dp[i] = in;
// cnt[i] = 1;
//} else {
// If taking
int extra_space = (prev_index == -1) ? in : in - M[prev_index].out;
long take_val = (prev_index == -1) ? extra_space : dp[prev_index] + extra_space;
long take_cnt = (prev_index == -1) ? 1 : cnt[prev_index];
// If not taking.
//System.err.println(prev_index + " found as prev with extra " + extra_space + " , " + extra_skip);
// Better to Take
if (out > max_in || take_val < skip_val) {
dp[i] = take_val;
cnt[i] = take_cnt;
//if (out > max_in) ans = (ans + cnt[i]) % MOD;
// Can skip or take it makes no difference.
} else if (take_val == skip_val) {
dp[i] = take_val;
cnt[i] = (take_cnt + skip_cnt) % MOD;
// Better to Skip
} else {
dp[i] = skip_val;
cnt[i] = skip_cnt;
}
//System.err.println("DP VAL = " + dp[i]);
//System.err.println("CNT = " + cnt[i]);
//}
}
long best = Integer.MAX_VALUE;
for (int i=0; i<n; ++i) if (M[i].out > max_in) best = Math.min(dp[i], best);
for (int i=0; i<n; ++i) if (M[i].out > max_in && dp[i] == best) ans = (ans + cnt[i]) % MOD;
System.out.println(ans);
}
public static int findPos(Pair[] M, HashMap<Integer,Integer> H, int i) {
if (M[0].out > i) return -1;
if (H.containsKey(i)) return H.get(i);
int MIN = 0;
int MAX = M.length-1;
while (MIN < MAX) {
int piv = (MIN+MAX+1)>>1;
if (M[piv].out > i) {
MAX = piv-1;
} else if (M[piv].out <= i) {
MIN = piv;
}
}
return MIN;
}
/************** HELPER CLASSES ***************/
//static class HS extends HashSet<Integer>{public HS(){super();}public HS(int a){super(a);}};
//static class AL extends ArrayList<Integer>{public AL(){super();}public AL(int a){super (a);}};
static class Pair implements Comparable<Pair> {
int i,j,in,out;long L; public Pair(int xx, int yy, long LL){i=xx;j=yy;L=LL;in=i;out=j;}
public int compareTo(Pair p) { return (this.L < p.L) ? -1 : (this.L == p.L) ? this.i - p.i : 1;}
}
/************** FAST IO CODE FOLLOWS *****************/
public static long nextLong() throws Throwable {
long i = System.in.read();boolean neg = false;while (i < 33) i = System.in.read();if (i == 45) {neg=true;i=48;}i = i - 48;
int j = System.in.read();while (j > 32) {i*=10;i+=j-48;j = System.in.read();}return (neg) ? -i : i;
}
public static int nextInt() throws Throwable {return (int)nextLong();}
public static String next() throws Throwable {
int i = 0; while (i < 33 && i != -1) i = System.in.read(); int cptr = 0; while (i >= 33) { in[cptr++] = (char)i; i = System.in.read();}
return new String(in, 0,cptr);
}
/**** LIBRARIES ****/
public static long gcdL(long a, long b) {while (b != 0) {long tmp = b;b = (a % b);a = tmp;}return a;}
public static int gcd(int a, int b) {while (b != 0) {int tmp = b;b = (a % b);a = tmp;}return a;}
public static int[] sieve(int LIM) {
int i,count = 0;
boolean [] b = new boolean [LIM];
for (i = 2;i<LIM; ++i) if (!b[i]) {count++; for (int j = i<<1; j<LIM; j+=i) b[j] = true;}
int [] primes = new int[count];
for (i = 2,count=0;i<LIM;++i) if (!b[i]) primes[count++] = i;
return primes;
}
public static int[] numPrimeFactors(int LIM) {
int i,count = 0;
int [] b = new int [LIM];
for (i = 2;i<LIM; ++i) if (b[i] == 0) {count++; for (int j = i; j<LIM; j+=i) b[j]++;}
return b;
}
public static StringBuilder stringFromArray(int [] a) {
StringBuilder b = new StringBuilder(9*a.length);
for (int i = 0; i<a.length; ++i) {
if (i != 0) b = b.append(' ');
b = b.append(a[i]);
}
return b;
}
public static long modPow (long a, long n, long MOD) { long S = 1; for (;n > 0; n>>=1, a=(a*a)%MOD) if ((n & 1) != 0) S = (a*S) % MOD; return S;}
}
/* Full Problem Text:
There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them.
The store has n different matryoshkas.
Any matryoshka is a figure of volume out_i with an empty space inside of volume in_i (of course, out_i > in_i).
You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another.
Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll inside the third one and so on.
Matryoshka i can be nested inside matryoshka j if out_i < in_j.
So only the last doll will take space inside your bag.
Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure.
Obviously, it's equal to in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}}),
where i_1, i_2, ..., i_k are the indices of the chosen dolls in the order they are nested in each other.
Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.
You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it.
But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets.
Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset).
Two subsets are considered different if there exists at least one index i such that one of the subsets contains the i-th doll, and another subset doesn't.
Since the answer can be large, print it modulo 10^9 + 7.
*/ | Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | 836aa9508e8ae73cbcad7b3452daf0fe | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
/*
Author: rahejamehul
Date: 8/10/2019
*/
public class E2 {
static long MOD = 1000000007;
public static void main(String[] args) throws Exception {
Reader br = new Reader();
PrintWriter out = new PrintWriter(System.out);
int N = br.num();
pair[] p = new pair[N];
for(int i = 0; i < N; i++){
int[] x = br.arr(2);
p[i] = new pair(x[1],x[0]);
}
Arrays.sort(p);
long max_in = p[0].a;
for(int i = 0; i < seg.length; i++){
seg[i] = new pair(Integer.MAX_VALUE,0);
}
long min_space = Integer.MAX_VALUE;
long ans = 0;
for(int i = 0; i < N; i++){
if(p[i].b > max_in){
update(1,1,N,(i+1),p[i].a,1);
pair q = new pair(p[i].a,1);
if(q.a < min_space){
min_space = q.a;
ans = q.b;
}else if(q.a == min_space){
ans += q.b;
}
}else{
int ind = 0;
int start = 0;
int end = N;
while(start < end){
int mid = (start + end)/2;
if(p[mid].a >= p[i].b){
start = mid+1;
}else{
end = mid-1;
}
}
ind = Math.max(0,start -3);
while(ind < N && p[ind].a >= p[i].b){
ind++;
}
pair q = query(1,1,N,1,ind);
update(1,1,N,(i+1),q.a - p[i].b + p[i].a,q.b);
q.a = q.a - p[i].b + p[i].a;
if(q.a < min_space){
min_space = q.a;
ans = q.b%MOD;
}else if(q.a == min_space){
ans = (ans + MOD + q.b)%MOD;
}
}
}
System.out.println(ans);
}
static pair[] seg = new pair[4 * 2 * 100000 + 10];
public static pair combine(pair a, pair b){
if(a.a < b.a){
return new pair(a.a,a.b%MOD);
}else if(b.a < a.a){
return new pair(b.a,b.b%MOD);
}else{
return new pair(a.a,(a.b + b.b + MOD) % MOD);
}
}
public static void update(int node, int l, int r, int pos, long upd1, long upd2){
int left = node*2;
int right = node*2+1;
int mid = (l+r)/2;
if(!(l <= pos && r >= pos)){
return;
}
if(l == r){
if(l == pos) {
seg[node].a = upd1;
seg[node].b = upd2;
}
return;
}
update(left,l,mid,pos,upd1,upd2);
update(right,mid+1,r,pos,upd1,upd2);
seg[node] = combine(seg[left],seg[right]);
}
public static pair query(int node, int l, int r, int start, int end){
int left = node*2;
int right = node*2+1;
int mid = (l+r)/2;
if(l >= start && r <= end){
return seg[node];
}
if(l==r || end < l || start > r){
return new pair(Integer.MAX_VALUE,0);
}
pair p1 = query(left,l,mid,start,end);
pair p2 = query(right,mid+1,r,start,end);
return combine(p1,p2);
}
static class pair implements Comparable<pair>{
long a,b;
public pair(long _a, long _b){
a = _a;
b = _b;
}
@Override
public int compareTo(pair o) {
return -1 * (int)Math.signum((a == o.a)?b-o.b:a-o.a);
}
}
static class Reader {
public BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public int[] arr(int N) throws Exception {
int[] ret = new int[N];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
ret[i] = Integer.parseInt(st.nextToken());
}
return ret;
}
public int num() throws Exception {
return Integer.parseInt(br.readLine());
}
public String line() throws Exception {
return br.readLine();
}
}
}
| Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | 2b96cb0138553a22e8b279924068db9b | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes | //package codeforces_edu69;
import java.io.*;
import java.util.*;
public class E3 {
public static void main(String[] args) {
int N = IO.nextInt();
List<Doll> dolls = new ArrayList<>();
for (int i = 0; i < N; i++) {
Doll p = new Doll(IO.nextInt(), IO.nextInt());
dolls.add(p);
}
dolls.sort(Comparator.comparingInt(d -> d.in));
TreeMap<Integer, State> tree = new TreeMap<>();
tree.put(0, new State(0, 1L, 0));
for (Doll doll : dolls) {
while (tree.size() >= 2) {
State first = tree.firstEntry().getValue();
State second = tree.ceilingEntry(first.size + 1).getValue();
if (second.size > doll.in)
break;
if (first.size + second.space - first.space > second.size) {
tree.remove(second.size);
} else if (first.size + second.space - first.space < second.size) {
tree.remove(first.size);
} else {
tree.remove(first.size);
second.ways += first.ways;
second.ways %= 1_000_000_007;
}
}
State floor = tree.floorEntry(doll.in).getValue();
State newstate = new State(doll.out, floor.ways, doll.in - floor.size + floor.space);
State existstate = tree.get(newstate.size);
if (existstate == null || existstate.space > newstate.space) {
tree.put(newstate.size, newstate);
} else if (existstate.space == newstate.space) {
existstate.ways += newstate.ways;
existstate.ways %= 1_000_000_007;
}
}
int maxin = dolls.get(dolls.size() - 1).in;
int minspace = tree.values().stream().filter(s -> s.size > maxin).mapToInt(s -> s.space).min().getAsInt();
System.out.println(
tree.values().stream()
.filter(s -> s.size > maxin && s.space == minspace)
.mapToLong(s -> s.ways).sum() % 1_000_000_007);
}
static class Doll {
int out;
int in;
public Doll(int out, int in) {
this.out = out;
this.in = in;
}
}
static class State {
int size;
long ways;
int space;
public State(int size, long ways, int space) {
this.size = size;
this.ways = ways;
this.space = space;
}
}
static class IO {
private static BufferedReader br;
private static StringTokenizer st;
static {
br = new BufferedReader(new InputStreamReader(System.in));
}
static String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
static int nextInt() {
return Integer.parseInt(next());
}
static long nextLong() {
return Long.parseLong(next());
}
static double nextDouble() {
return Double.parseDouble(next());
}
}
}
| Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | c52b1eb5ca9c4e78d2e0828a459a515a | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes | //package codeforces_edu69;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.Collectors;
public class E2 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
List<Doll> dolls = new ArrayList<>();
for (int i = 0; i < N; i++) {
String[] line = br.readLine().split(" ");
Doll p = new Doll(Integer.parseInt(line[0]), Integer.parseInt(line[1]));
dolls.add(p);
}
dolls.sort(Comparator.comparingInt(d -> d.in));
TreeMap<Integer,State> tree = new TreeMap<>();
tree.put(0, new State(0, 1L, 0));
for (Doll doll : dolls) {
while(tree.size() >= 2) {
State first = tree.firstEntry().getValue();
State second = tree.ceilingEntry(first.size + 1).getValue();
if(second.size > doll.in)
break;
if (first.size + second.space - first.space > second.size) {
tree.remove(second.size);
} else if (first.size + second.space - first.space < second.size) {
tree.remove(first.size);
} else {
tree.remove(first.size);
second.ways += first.ways;
second.ways %= 1_000_000_007;
}
}
State floor = tree.floorEntry(doll.in).getValue();
State newstate = new State(doll.out, floor.ways, doll.in - floor.size + floor.space);
State existstate = tree.get(newstate.size);
if(existstate==null || existstate.space > newstate.space) {
tree.put(newstate.size, newstate);
} else if(existstate.space==newstate.space) {
existstate.ways += newstate.ways;
existstate.ways %= 1_000_000_007;
}
}
int maxin = dolls.get(dolls.size()-1).in;
int minspace = tree.values().stream().filter(s -> s.size > maxin).mapToInt(s -> s.space).min().getAsInt();
System.out.println(
tree.values().stream()
.filter(s -> s.size > maxin && s.space == minspace)
.mapToLong(s -> s.ways).sum() % 1_000_000_007);
}
static class Doll {
int out;
int in;
public Doll(int out, int in) {
this.out = out;
this.in = in;
}
}
static class State {
int size;
long ways;
int space;
public State(int size, long ways, int space) {
this.size = size;
this.ways = ways;
this.space = space;
}
}
}
| Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | 440b95baa73e876c923769a98701c431 | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes | // practice with rainboy
import java.io.*;
import java.util.*;
public class CF1197E extends PrintWriter {
CF1197E() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1197E o = new CF1197E(); o.main(); o.flush();
}
static final int INF = 0x3f3f3f3f, MD = 1000000007;
int[] vv, cc;
void update(int i, int n, int v, int c) {
while (i < n) {
if (vv[i] < v) {
vv[i] = v;
cc[i] = c;
} else if (vv[i] == v)
cc[i] = (cc[i] + c) % MD;
i |= i + 1;
}
}
long query(int i) {
int v = -1, c = 0;
while (i >= 0) {
if (v < vv[i]) {
v = vv[i];
c = cc[i];
} else if (v == vv[i])
c = (c + cc[i]) % MD;
i &= i + 1;
i--;
}
return (long) v * MD + c;
}
void main() {
int n = sc.nextInt();
int[] aa = new int[n * 2];
int[] bb = new int[n * 2];
Integer[] ii = new Integer[n * 2];
for (int i = 0; i < n; i++) {
aa[i << 1 ^ 1] = sc.nextInt();
aa[i << 1 ] = sc.nextInt();
}
for (int i = 0; i < n * 2; i++)
ii[i] = i;
Arrays.sort(ii, (i, j) -> aa[i] - aa[j]);
int br = 0;
for (int i = 0; i < n * 2; i++)
bb[ii[i]] = i + 1 == n * 2 || aa[ii[i]] != aa[ii[i + 1]] ? br++ : br;
for (int i = 0; i < n; i++)
ii[i] = i;
Arrays.sort(ii, 0, n, (i, j) -> bb[i << 1] - bb[j << 1]);
int bl = bb[ii[n - 1] << 1];
vv = new int[br];
cc = new int[br];
update(0, br, 0, 1);
int e_ = INF, c_ = 0;
for (int i = 0; i < n; i++) {
int il = ii[i] << 1, ir = il ^ 1;
long vc = query(bb[il]);
int v = (int) (vc / MD), c = (int) (vc % MD);
v += aa[ir] - aa[il];
update(bb[ir], br, v, c);
if (bb[ir] > bl) {
int e = aa[ir] - v;
if (e_ > e) {
e_ = e;
c_ = c;
} else if (e_ == e)
c_ = (c_ + c) % MD;
}
}
println(c_);
}
}
| Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | b497ba12d398e85e7e9258f6cedcba5e | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes |
import java.io.*;
import java.util.*;
public class Solution {
long mod = 1000000007L;
private void solve() throws Exception {
int n = nextInt();
Volume[] out = new Volume[n];
Volume[] in = new Volume[n];
for(int i = 0; i < n; i++) {
out[i] = new Volume(i, nextLong());
in[i] = new Volume(i, nextLong());
}
Arrays.sort(out, Comparator.comparing(v -> v.v));
Arrays.sort(in, Comparator.comparing(v -> v.v));
long[] reach = new long[n];
for(int o = 0; o < n; o++) reach[out[o].idx] = out[o].v;
int i = 0;
int o = 0;
long[] min = new long[n];
long[] count = new long[n];
while(i < n && out[o].v > in[i].v) {
min[in[i].idx] = in[i].v;
count[in[i].idx] = 1L;
i++;
}
if(i == n) {
System.out.println(n);
return;
}
int bestO = -1;
while(i < n) {
if(bestO >= 0) min[out[bestO].idx] += in[i].v-reach[out[bestO].idx];
while(out[o].v <= in[i].v) {
min[out[o].idx] += in[i].v-out[o].v;
if(bestO == -1 || min[out[o].idx] < min[out[bestO].idx]) {
bestO = o;
} else if(min[out[o].idx] == min[out[bestO].idx]) {
count[out[o].idx] = (count[out[o].idx] + count[out[bestO].idx])%mod;
bestO = o;
}
o++;
}
min[in[i].idx] = min[out[bestO].idx];
count[in[i].idx] = count[out[bestO].idx];
reach[out[bestO].idx] = in[i].v;
i++;
}
long best = 1L<<60;
long res = 0L;
while(o < n) {
if(min[out[o].idx] < best) {
best = min[out[o].idx];
res = count[out[o].idx];
}else if(min[out[o].idx] == best) {
res = (res+count[out[o].idx])%mod;
}
o++;
}
System.out.println(res);
}
class Volume{
int idx;
long v;
public Volume(int idx, long v) {
this.idx = idx;
this.v = v;
}
}
public static void main(String[] args) {
new Thread(null, new Runnable() {
public void run() {
new Solution().run();
}
}, "1", 1 << 27).start();
}
private BufferedReader in;
// private PrintWriter out;
private StringTokenizer tokenizer;
public void run() {
try {
tokenizer = null;
// long start = System.nanoTime();
in = new BufferedReader(new InputStreamReader(System.in));
// out = new PrintWriter(System.out);
//
//
// in = new BufferedReader(new FileReader("grading.txt"));
// out = new PrintWriter(new File("outputC.txt"));
solve();
// System.out.println((System.nanoTime()-start)/1E9);
in.close();
// out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private float nextFloat() throws IOException {
return Float.parseFloat(nextToken());
}
private String nextLine() throws IOException {
return new String(in.readLine());
}
private String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(in.readLine());
}
return tokenizer.nextToken();
}
} | Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | bf64e1e609a20c78c9b53e173a0dd425 | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution {
long mod = 1000000007L;
private void solve() throws Exception {
int n = nextInt();
Volume[] out = new Volume[n];
Volume[] in = new Volume[n];
for(int i = 0; i < n; i++) {
out[i] = new Volume(i, nextLong());
in[i] = new Volume(i, nextLong());
}
Arrays.sort(out, Comparator.comparing(v -> v.v));
Arrays.sort(in, Comparator.comparing(v -> v.v));
long[] reach = new long[n];
for(int o = 0; o < n; o++) reach[out[o].idx] = out[o].v;
int i = 0;
int o = 0;
long[] min = new long[n];
long[] count = new long[n];
while(i < n && out[o].v > in[i].v) {
min[in[i].idx] = in[i].v;
count[in[i].idx] = 1L;
i++;
}
if(i == n) {
System.out.println(n);
return;
}
int bestO = -1;
while(i < n) {
if(bestO >= 0) min[out[bestO].idx] += in[i].v-reach[out[bestO].idx];
while(out[o].v <= in[i].v) {
min[out[o].idx] += in[i].v-out[o].v;
if(bestO == -1 || min[out[o].idx] < min[out[bestO].idx]) {
bestO = o;
} else if(min[out[o].idx] == min[out[bestO].idx]) {
count[out[o].idx] = (count[out[o].idx] + count[out[bestO].idx])%mod;
bestO = o;
}
o++;
}
min[in[i].idx] = min[out[bestO].idx];
count[in[i].idx] = count[out[bestO].idx];
reach[out[bestO].idx] = in[i].v;
i++;
}
long best = 1L<<60;
long res = 0L;
while(o < n) {
if(min[out[o].idx] < best) {
best = min[out[o].idx];
res = count[out[o].idx];
}else if(min[out[o].idx] == best) {
res = (res+count[out[o].idx])%mod;
}
o++;
}
System.out.println(res);
}
class Volume{
int idx;
long v;
public Volume(int idx, long v) {
this.idx = idx;
this.v = v;
}
}
public static void main(String[] args) {
new Thread(null, new Runnable() {
public void run() {
new Solution().run();
}
}, "1", 1 << 27).start();
}
private BufferedReader in;
// private PrintWriter out;
private StringTokenizer tokenizer;
public void run() {
try {
tokenizer = null;
// long start = System.nanoTime();
in = new BufferedReader(new InputStreamReader(System.in));
// out = new PrintWriter(System.out);
//
//
// in = new BufferedReader(new FileReader("grading.txt"));
// out = new PrintWriter(new File("outputC.txt"));
solve();
// System.out.println((System.nanoTime()-start)/1E9);
in.close();
// out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
private int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
private long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
private float nextFloat() throws IOException {
return Float.parseFloat(nextToken());
}
private String nextLine() throws IOException {
return new String(in.readLine());
}
private String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(in.readLine());
}
return tokenizer.nextToken();
}
} | Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | 56311cf66807b6e7dca4dbb3cd42a673 | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes |
import java.io.*;
import java.util.*;
public class E {
// ------------------------
static class O implements Comparable<O>{
int out,in,idx;
public O(int o,int i,int d){
out=o;
in=i;
idx=d;
}
public int compareTo(O other){
if(other.out==out&&other.in==in)
return idx-other.idx;
if(other.out==out)
return in-other.in;
return out-other.out;
}
}
static class I implements Comparable<I>{
int out,in,idx;
public I(O o){
out=o.out;
in=o.in;
idx=o.idx;
}
public int compareTo(I other){
if(other.out==out&&other.in==in)
return idx-other.idx;
if(other.in==in)
return out-other.out;
return in-other.in;
}
}
static class P{
long es;
long ct;
public P(long e,long c){
es=e;
ct=c;
}
public String toString(){
return es+":"+ct;
}
}
static long MOD=1000000007;
public static void main(String[] args) {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
// ------------------------
int n=sc.nextInt();
O[]matO=new O[n];
I[]matI=new I[n];
long maxIn=0;
for(int i=0;i<n;i++){
matO[i]=new O(sc.nextInt(),sc.nextInt(),i);
matI[i]=new I(matO[i]);
maxIn=Math.max(maxIn,matO[i].in);
}
Arrays.sort(matO);
Arrays.sort(matI);
long minES=Integer.MAX_VALUE;
long es=Integer.MAX_VALUE,ct=0;
HashMap<String,P>map=new HashMap<String,P>();
long ans=0;
int index=0;
for(int i=0;i<n;i++){
while(index<n&&matO[index].out<=matI[i].in){
P p=map.get(matO[index].out+"/"+matO[index].in);
if(p.es<es){
es=p.es;
ct=p.ct;
}else if(p.es==es){
ct=(ct+p.ct)%MOD;
}
index++;
}
P p=new P(matI[i].in-matI[i].out,1);
if(es<0){
p.es+=es;
p.ct=ct;
}
if(matI[i].out>maxIn){
if(p.es+matI[i].out==minES)
ans=(ans+p.ct)%MOD;
else if(p.es+matI[i].out<minES){
ans=p.ct;
minES=p.es+matI[i].out;
}
}
String s=matI[i].out+"/"+matI[i].in;
map.put(s, p);
}
out.println(ans);
// ------------------------
out.close();
}
//------------------------
public static PrintWriter out;
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | 36f2087eb0ebeaf83cb0177fb7373e7a | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class A {
static long INF = (long) 1e18;
static class pair {
int in, out;
pair(int a, int b) {
in = b;
out = a;
}
}
static int MOD = (int) 1e9 + 7;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
pair[] a = new pair[n];
for (int i = 0; i < n; i++)
a[i] = new pair(sc.nextInt(), sc.nextInt());
Arrays.sort(a, (x, y) -> x.in - y.in);
int ans = 0;
PriorityQueue<Integer> pq = new PriorityQueue<Integer>((x, y) -> a[x].out - a[y].out);
long min = INF, totalCnt = 0;
long[] dp = new long[n], cnt = new long[n];
// dp(i) is the min wasted space for subset ending at i and that cannot be
// extended to the left
// if i cannot be extended to the right, then this subset is big enough
int[] maxSuf = new int[n + 1];
for (int i = n - 1; i >= 0; i--)
maxSuf[i] = Math.max(maxSuf[i + 1], a[i].in);
long minDp=INF;
for (int i = 0; i < n; i++) {
while (!pq.isEmpty() && a[pq.peek()].out <= a[i].in) {
int j = pq.poll();
long x = dp[j] - a[j].out;
if (x == min)
totalCnt += cnt[j];
else if (x < min) {
totalCnt = cnt[j];
min = x;
}
}
if (totalCnt == 0) {
cnt[i] = 1;
dp[i] = a[i].in;
}
else
{
totalCnt %= MOD;
cnt[i] = totalCnt;
dp[i] = min + a[i].in;
}
if (a[i].out > maxSuf[i + 1])
minDp=Math.min(minDp, dp[i]);
pq.add(i);
}
for (int i = 0; i < n; i++) {
if (a[i].out > maxSuf[i + 1] && dp[i]==minDp) {
ans += cnt[i];
if (ans >= MOD)
ans -= MOD;
}
}
out.println(ans);
out.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
Scanner(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
return br.readLine();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(next());
}
boolean ready() throws IOException {
return br.ready();
}
}
} | Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | a7a2f49c0c21dd1b1177a8538db1b499 | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
static class TaskE {
static final int MASK = (1 << 30) - 1;
static final int MOD = 1000 * 1000 * 1000 + 7;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int[] a = new int[n + 1];
int[] b = new int[n + 1];
ArrayList<Long> al = new ArrayList<>();
for (int i = 1; i <= n; i++) {
a[i] = in.nextInt();
b[i] = in.nextInt();
al.add((((long) a[i]) << 30) | b[i]);
}
Collections.sort(al);
int[] dp = new int[n + 1];
int[] num_ways = new int[n + 1];
dp[0] = 0;
num_ways[0] = 1;
int[] max_in = new int[n + 2];
for (int i = 1; i <= n; i++) {
long val = al.get(i - 1);
b[i] = (int) (val >>> 30);
a[i] = (int) (val & MASK);
}
max_in[n + 1] = 0;
for (int i = n; i >= 1; i--) max_in[i] = Integer.max(max_in[i + 1], a[i]);
int min_space = MOD;
int min_space_ways = 0;
for (int i = 1; i <= n; i++) {
int lo = 0, hi = i - 1;
int IN = a[i], OUT = b[i];
while (lo < hi) {
int mid = (lo + hi + 1) / 2;
int OUT_here = (mid == 0 ? -1 : b[mid]);
if (OUT_here <= IN) {
lo = mid;
} else {
hi = mid - 1;
}
}
int j = lo;
int x = OUT - IN + dp[j];
dp[i] = dp[i - 1];
num_ways[i] = num_ways[i - 1];
if (dp[i - 1] <= x) {
dp[i] = x;
num_ways[i] = num_ways[j];
if (dp[i - 1] == x) {
num_ways[i] += num_ways[i - 1];
if (num_ways[i] >= MOD)
num_ways[i] -= MOD;
}
}
if (OUT > max_in[i + 1]) {
if (OUT - x < min_space) {
min_space = OUT - x;
min_space_ways = num_ways[j];
} else if (OUT - x == min_space) {
min_space_ways += num_ways[j];
if (min_space_ways >= MOD) min_space_ways -= MOD;
}
}
}
out.println(min_space_ways);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void println(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
writer.print('\n');
}
public void close() {
writer.close();
}
}
}
| Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | 2507b57f222cc0b95b3bdfe751a1b30d | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class Main {
static int inf = (int) 1e9 + 7;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(System.out);
int n = nextInt();
int mod = inf;
ball a[] = new ball[n];
for(int i = 0;i < n;i++) {
int out = nextInt();
int in = nextInt();
a[i] = new ball(in, out);
}
Arrays.sort(a, new ball());
pair dp[] = new pair[n];
segment_tree b = new segment_tree(n);
for(int i = n - 1;i >= 0;i--) {
int id = n;
int l = -1;
while(id - l > 1) {
int mid = (id + l) / 2;
if (a[mid].in >= a[i].out) id = mid;
else l = mid;
}
if (id == n) {
dp[i] = new pair(a[i].in, 1);
}else{
dp[i] = new pair();
dp[i].x = b.get_min(id) - (a[i].out - a[i].in);
dp[i].y = b.get_sum(id);
}
b.set(dp[i], i);
}
int min = inf;
int min_out = inf;
for(int i = 0;i < n;i++) {
if (min_out <= a[i].in) break;
min_out = Math.min(min_out, a[i].out);
min = Math.min(min, dp[i].x);
}
int ans = 0;
for(int i = 0;i < n;i++) {
if (min_out <= a[i].in) break;
if (dp[i].x == min) ans = (ans + dp[i].y) % mod;
}
pw.println(ans);
pw.close();
}
static BufferedReader br;
static StringTokenizer st = new StringTokenizer("");
static PrintWriter pw;
/*static String next() throws IOException {
int c = br.read();
while (Character.isWhitespace(c)) c = br.read();
StringBuilder sb = new StringBuilder();
while (!Character.isWhitespace(c)) {
sb.appendCodePoint(c);
c = br.read();
}
return sb.toString();
}*/
static String next() throws IOException {
if (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static Double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
class ball implements Comparator<ball>{
int in, out;
ball(int in, int out) {
this.in = in;
this.out = out;
}
ball() {}
@Override
public int compare(ball o1, ball o2) {
return Integer.compare(o1.in, o2.in);
}
}
class pair {
int x, y;
pair(int a, int b) {
x = a;
y = b;
}
pair() {}
}
class segment_tree {
static int mod = (int) 1e9 + 7;
int min[], sum[], last;
segment_tree(int n) {
last = n - 1;
min = new int [n * 4];
sum = new int [n * 4];
for(int i = 0;i < n * 4;i++) min[i] = mod;
}
void set(pair a, int id) {
set(0, 0, last, a, id);
}
void set(int v, int l, int r, pair a, int id) {
if (l > id || r < id) return;
if (l == id && r == id) {
min[v] = a.x;
sum[v] = a.y;
return;
}
int m = ((l + r) >> 1);
set(v * 2 + 1, l, m, a, id);
set(v * 2 + 2, m + 1, r, a, id);
min[v] = Math.min(min[v * 2 + 1], min[v * 2 + 2]);
sum[v] = 0;
if (min[v * 2 + 1] == min[v]) sum[v] += sum[v * 2 + 1];
if (min[v * 2 + 2] == min[v]) sum[v] += sum[v * 2 + 2];
if (sum[v] >= mod) sum[v] -= mod;
}
int get_sum(int l) {
return get_sum(0, 0, last, get_min(l), l);
}
int get_min(int l) {
return get_min(0, 0, last, l);
}
int get_min(int v, int l, int r, int left) {
if (r < left) return mod;
if (l >= left) return min[v];
int m = ((l + r) >> 1);
return Math.min(get_min(v * 2 + 1, l, m, left), get_min(v * 2 + 2, m + 1, r, left));
}
int get_sum(int v, int l, int r, int min_c, int left) {
if (r < left) return 0;
if (l >= left) return min[v] == min_c ? sum[v] : 0;
int m = ((l + r) >> 1);
return (get_sum(v * 2 + 1, l, m, min_c, left) + get_sum(v * 2 + 2, m + 1, r, min_c, left)) % mod;
}
}
| Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | ab1aa7765a9dc920eb59ef93477a1e97 | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes |
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;
public class CF1197E {
public static void main(String[] args) throws Exception {
boolean local = System.getProperty("ONLINE_JUDGE") == null;
boolean async = false;
Charset charset = Charset.forName("ascii");
FastIO io = local ? new FastIO(new FileInputStream("D:\\DATABASE\\TESTCASE\\Code.in"), System.out, charset) : new FastIO(System.in, System.out, charset);
Task task = new Task(io, new Debug(local));
if (async) {
Thread t = new Thread(null, task, "dalt", 1 << 27);
t.setPriority(Thread.MAX_PRIORITY);
t.start();
t.join();
} else {
task.run();
}
if (local) {
io.cache.append("\n\n--memory -- \n" + ((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) >> 20) + "M");
}
io.flush();
}
public static class Task implements Runnable {
final FastIO io;
final Debug debug;
int inf = (int) 1e9;
public Task(FastIO io, Debug debug) {
this.io = io;
this.debug = debug;
}
@Override
public void run() {
solve();
}
public void solve() {
int n = io.readInt();
Box[] boxes = new Box[n + 1];
int[] allValues = new int[n + n + 2];
for (int i = 1; i <= n; i++) {
boxes[i] = new Box();
allValues[i] = boxes[i].out = io.readInt();
allValues[i + n] = boxes[i].in = io.readInt();
}
DiscreteMap dm = new DiscreteMap(allValues, 0, allValues.length);
int maxIn = 0;
for (int i = 1; i <= n; i++) {
boxes[i].in = dm.rankOf(boxes[i].in);
boxes[i].out = dm.rankOf(boxes[i].out);
maxIn = Math.max(boxes[i].in, maxIn);
}
int m = dm.maxRank();
int[] dp = new int[m + 1];
int[] way = new int[m + 1];
dp[0] = 0;
way[0] = 1;
Segment root = new Segment(dm.minRank(), dm.maxRank());
root.update(0, 0, dm.minRank(), dm.maxRank(), 0, 1);
Map<Integer, List<Box>> groupByOut = Arrays.asList(boxes)
.subList(1, boxes.length)
.stream()
.collect(Collectors.groupingBy((x) -> x.out));
int[] q = new int[2];
for (int i = 1; i <= dm.maxRank(); i++) {
dp[i] = inf;
way[i] = 0;
for (Box box : groupByOut.getOrDefault(i, Collections.emptyList())) {
q[0] = inf;
q[1] = 0;
root.query(0, box.in, dm.minRank(), dm.maxRank(), q);
q[0] += dm.iThElement(box.in);
if (dp[i] > q[0]) {
dp[i] = q[0];
way[i] = 0;
}
if (dp[i] == q[0]) {
way[i] = mod.plus(way[i], q[1]);
}
}
root.update(i, i, dm.minRank(), dm.maxRank(), dp[i] - dm.iThElement(i), way[i]);
}
int minWaste = inf;
int minWasteWay = 0;
for (int i = maxIn + 1; i <= dm.maxRank(); i++) {
if (minWaste > dp[i]) {
minWaste = dp[i];
minWasteWay = 0;
}
if (minWaste == dp[i]) {
minWasteWay = mod.plus(minWasteWay, way[i]);
}
}
io.cache.append(minWasteWay);
}
}
static Modular mod = new Modular((int) 1e9 + 7);
public static class Segment implements Cloneable {
private Segment left;
private Segment right;
int min;
int way;
public void pushUp() {
min = Math.min(left.min, right.min);
way = 0;
if (left.min == min) {
way = mod.plus(way, left.way);
}
if (right.min == min) {
way = mod.plus(way, right.way);
}
}
public void pushDown() {
}
public Segment(int l, int r) {
if (l < r) {
int m = (l + r) >> 1;
left = new Segment(l, m);
right = new Segment(m + 1, r);
pushUp();
} else {
}
}
private boolean covered(int ll, int rr, int l, int r) {
return ll <= l && rr >= r;
}
private boolean noIntersection(int ll, int rr, int l, int r) {
return ll > r || rr < l;
}
public void update(int ll, int rr, int l, int r, int v, int w) {
if (noIntersection(ll, rr, l, r)) {
return;
}
if (covered(ll, rr, l, r)) {
if (min > v) {
min = v;
way = 0;
}
if (min == v) {
way = mod.plus(way, w);
}
return;
}
pushDown();
int m = (l + r) >> 1;
left.update(ll, rr, l, m, v, w);
right.update(ll, rr, m + 1, r, v, w);
pushUp();
}
public void query(int ll, int rr, int l, int r, int[] ans) {
if (noIntersection(ll, rr, l, r)) {
return;
}
if (covered(ll, rr, l, r)) {
if (ans[0] > min) {
ans[0] = min;
ans[1] = 0;
}
if (ans[0] == min) {
ans[1] = mod.plus(ans[1], way);
}
return;
}
pushDown();
int m = (l + r) >> 1;
left.query(ll, rr, l, m, ans);
right.query(ll, rr, m + 1, r, ans);
}
}
/**
* Created by dalt on 2018/6/1.
*/
public static class Randomized {
static Random random = new Random();
public static double nextDouble(double min, double max) {
return random.nextDouble() * (max - min) + min;
}
public static void randomizedArray(int[] data, int from, int to) {
to--;
for (int i = from; i <= to; i++) {
int s = nextInt(i, to);
int tmp = data[i];
data[i] = data[s];
data[s] = tmp;
}
}
public static void randomizedArray(long[] data, int from, int to) {
to--;
for (int i = from; i <= to; i++) {
int s = nextInt(i, to);
long tmp = data[i];
data[i] = data[s];
data[s] = tmp;
}
}
public static void randomizedArray(double[] data, int from, int to) {
to--;
for (int i = from; i <= to; i++) {
int s = nextInt(i, to);
double tmp = data[i];
data[i] = data[s];
data[s] = tmp;
}
}
public static void randomizedArray(float[] data, int from, int to) {
to--;
for (int i = from; i <= to; i++) {
int s = nextInt(i, to);
float tmp = data[i];
data[i] = data[s];
data[s] = tmp;
}
}
public static <T> void randomizedArray(T[] data, int from, int to) {
to--;
for (int i = from; i <= to; i++) {
int s = nextInt(i, to);
T tmp = data[i];
data[i] = data[s];
data[s] = tmp;
}
}
public static int nextInt(int l, int r) {
return random.nextInt(r - l + 1) + l;
}
}
public static class DiscreteMap {
int[] val;
int f;
int t;
public DiscreteMap(int[] val, int f, int t) {
Randomized.randomizedArray(val, f, t);
Arrays.sort(val, f, t);
int wpos = f + 1;
for (int i = f + 1; i < t; i++) {
if (val[i] == val[i - 1]) {
continue;
}
val[wpos++] = val[i];
}
this.val = val;
this.f = f;
this.t = wpos;
}
/**
* Return 0, 1, so on
*/
public int rankOf(int x) {
return Arrays.binarySearch(val, f, t, x) - f;
}
public int floorRankOf(int x) {
int index = Arrays.binarySearch(val, f, t, x);
if (index >= 0) {
return index - f;
}
index = -(index + 1);
return index - 1 - f;
}
public int ceilRankOf(int x) {
int index = Arrays.binarySearch(val, f, t, x);
if (index >= 0) {
return index - f;
}
index = -(index + 1);
return index - f;
}
/**
* Get the i-th smallest element
*/
public int iThElement(int i) {
return val[f + i];
}
public int minRank() {
return 0;
}
public int maxRank() {
return t - f - 1;
}
@Override
public String toString() {
return Arrays.toString(Arrays.copyOfRange(val, f, t));
}
}
public static class Box {
int in;
int out;
}
/**
* Mod operations
*/
public static class Modular {
int m;
public Modular(int m) {
this.m = m;
}
public int valueOf(int x) {
x %= m;
if (x < 0) {
x += m;
}
return x;
}
public int valueOf(long x) {
x %= m;
if (x < 0) {
x += m;
}
return (int) x;
}
public int mul(int x, int y) {
return valueOf((long) x * y);
}
public int mul(long x, long y) {
x = valueOf(x);
y = valueOf(y);
return valueOf(x * y);
}
public int plus(int x, int y) {
return valueOf(x + y);
}
public int plus(long x, long y) {
x = valueOf(x);
y = valueOf(y);
return valueOf(x + y);
}
@Override
public String toString() {
return "mod " + m;
}
}
public static class FastIO {
public final StringBuilder cache = new StringBuilder(1 << 13);
private final InputStream is;
private final OutputStream os;
private final Charset charset;
private StringBuilder defaultStringBuf = new StringBuilder(1 << 13);
private byte[] buf = new byte[1 << 13];
private int bufLen;
private int bufOffset;
private int next;
public FastIO(InputStream is, OutputStream os, Charset charset) {
this.is = is;
this.os = os;
this.charset = charset;
}
public FastIO(InputStream is, OutputStream os) {
this(is, os, Charset.forName("ascii"));
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public int readInt() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
int val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
public long readLong() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
long val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
public double readDouble() {
boolean sign = true;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+';
next = read();
}
long val = 0;
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
if (next != '.') {
return sign ? val : -val;
}
next = read();
long radix = 1;
long point = 0;
while (next >= '0' && next <= '9') {
point = point * 10 + next - '0';
radix = radix * 10;
next = read();
}
double result = val + (double) point / radix;
return sign ? result : -result;
}
public String readString(StringBuilder builder) {
skipBlank();
while (next > 32) {
builder.append((char) next);
next = read();
}
return builder.toString();
}
public String readString() {
defaultStringBuf.setLength(0);
return readString(defaultStringBuf);
}
public int readLine(char[] data, int offset) {
int originalOffset = offset;
while (next != -1 && next != '\n') {
data[offset++] = (char) next;
next = read();
}
return offset - originalOffset;
}
public int readString(char[] data, int offset) {
skipBlank();
int originalOffset = offset;
while (next > 32) {
data[offset++] = (char) next;
next = read();
}
return offset - originalOffset;
}
public int readString(byte[] data, int offset) {
skipBlank();
int originalOffset = offset;
while (next > 32) {
data[offset++] = (byte) next;
next = read();
}
return offset - originalOffset;
}
public char readChar() {
skipBlank();
char c = (char) next;
next = read();
return c;
}
public void flush() throws IOException {
os.write(cache.toString().getBytes(charset));
os.flush();
cache.setLength(0);
}
public boolean hasMore() {
skipBlank();
return next != -1;
}
}
public static class Debug {
private boolean allowDebug;
public Debug(boolean allowDebug) {
this.allowDebug = allowDebug;
}
public void assertTrue(boolean flag) {
if (!allowDebug) {
return;
}
if (!flag) {
fail();
}
}
public void fail() {
throw new RuntimeException();
}
public void assertFalse(boolean flag) {
if (!allowDebug) {
return;
}
if (flag) {
fail();
}
}
private void outputName(String name) {
System.out.print(name + " = ");
}
public void debug(String name, int x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println("" + x);
}
public void debug(String name, long x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println("" + x);
}
public void debug(String name, double x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println("" + x);
}
public void debug(String name, int[] x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println(Arrays.toString(x));
}
public void debug(String name, long[] x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println(Arrays.toString(x));
}
public void debug(String name, double[] x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println(Arrays.toString(x));
}
public void debug(String name, Object x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println("" + x);
}
public void debug(String name, Object... x) {
if (!allowDebug) {
return;
}
outputName(name);
System.out.println(Arrays.deepToString(x));
}
}
}
| Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | 5a8e0b9d439ffdaedc8beef05298a1c4 | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Comparator.*;
public class Main {
FastScanner in;
PrintWriter out;
boolean multitests = false;
long mod = (long) 1e9 + 7; // 998_244_353L || (long) 1e9 + 9
ArrayList<Integer>[] graph;
ArrayList<GraphPair>[] weightedGraph;
private void solve() throws IOException {
// solveA();
// solveB();
// solveC();
// solveD();
solveE();
// solveF();
}
private void solveA() throws IOException {
int n = in.nextInt();
int[] a = in.nextIntArray(n);
int max1 = max(a[0], a[1]), max2 = min(a[0], a[1]);
for (int i = 2; i < n; i++) {
if (a[i] > max1) {
max2 = max1;
max1 = a[i];
} else if (a[i] > max2) {
max2 = a[i];
}
}
out.println(min(n - 2, min(max1, max2) - 1));
}
private void solveB() throws IOException {
int n = in.nextInt();
int[] a = in.nextIntArray(n);
int maxId = 0;
for (int i = 1; i < n; i++)
if (a[i] > a[maxId])
maxId = i;
int prev = a[maxId];
int l = maxId - 1, r = maxId + 1;
while (l >= 0 || r < n) {
if (l < 0 || (r < n && a[l] < a[r])) {
if (a[r] < prev) {
prev = a[r++];
} else
break;
} else if (r >= n || (l >= 0 && a[l] > a[r])) {
if (a[l] < prev) {
prev = a[l--];
} else
break;
} else
break;
}
out.println(l < 0 && r >= n ? "YES" : "NO");
}
private void solveC() throws IOException {
int n = in.nextInt(), k = in.nextInt();
int[] a = in.nextIntArray(n);
int[] b = new int[n - 1];
for (int i = 0; i < n - 1; i++)
b[i] = a[i + 1] - a[i];
shuffleInt(b);
sort(b);
long ans = 0;
for (int i = 0; i < n - k; i++)
ans += b[i];
out.println(ans);
}
private void solveD() throws IOException {
int n = in.nextInt(), m = in.nextInt();
long K = in.nextLong();
long[] a = in.nextLongArray(n);
long[] suffSum = new long[n];
for (int i = n - 1; i >= 0; i--)
suffSum[i] = a[i] + (i + 1 < n ? suffSum[i + 1] : 0);
// out.println(Arrays.toString(suffSum));
long ans = 0;
for (int first = 0; first < min(n, m); first++) {
int len = 1 + (n - (first + 1)) / m;
long[] b = new long[len];
int i = first;
for (int j = 0; j < len; j++, i += m) {
//out.print(i + "|");
b[j] = Long.MIN_VALUE;
for (int k = max(0, i - m + 1); k <= i; k++) {
b[j] = max(b[j], suffSum[k]);
}
b[j] -= K;
}
//out.println();
long del = 0;
for (int j = i - m + 1; j < n; j++)
del += a[j];
for (int j = 0; j < len; j++)
b[j] -= del;
//for (int j = 0; j < len; j++)
//out.print(b[j] + " ");
//out.println();
long max = Long.MIN_VALUE + K;
i = first;
//out.flush();
long pdel = del;
for (int j = 0; j < len; j++, i += m) {
max = max(max - K, b[j]);
del = i + 1 < n ? (suffSum[i + 1] - pdel) : 0;
ans = max(ans, max - del);
}
}
out.println(ans);
}
class Segment {
int l, r;
Segment(int r, int l) {
this.l = l;
this.r = r;
}
}
class Pair {
int diff, ans;
Pair(int diff, int ans) {
this.diff = diff;
this.ans = ans;
}
}
private void solveE() throws IOException {
int n = in.nextInt();
Segment[] p = new Segment[n];
for (int i = 0; i < n; i++)
p[i] = new Segment(in.nextInt(), in.nextInt());
sort(p, comparingInt(o -> o.r));
int maxL = p[0].l;
for (int i = 1; i < n; i++)
if (p[i].l > maxL)
maxL = p[i].l;
TreeMap<Integer, Pair> map = new TreeMap<>();
map.put(0, new Pair(0, 1));
for (int i = 0; i < n; i++) {
if (p[i].r > maxL)
p[i].r = maxL + 1;
int prev = map.floorKey(p[i].l);
Pair pe = map.get(prev);
int newDiff = pe.diff + p[i].l - prev;
Pair next = map.get(p[i].r);
if (next == null) {
int nd = map.lowerEntry(p[i].r).getValue().diff + p[i].r - map.lowerKey(p[i].r);
if (nd < newDiff)
map.put(p[i].r, new Pair(nd, map.lowerEntry(p[i].r).getValue().ans));
else if (nd == newDiff)
map.put(p[i].r, new Pair(newDiff, pe.ans + map.lowerEntry(p[i].r).getValue().ans));
else // nd > new Diff
map.put(p[i].r, new Pair(newDiff, pe.ans));
} else if (newDiff < next.diff)
map.put(p[i].r, new Pair(newDiff, pe.ans));
else if (newDiff == next.diff)
map.get(p[i].r).ans = map.get(p[i].r).ans + pe.ans;
if (map.get(p[i].r).ans >= mod)
map.get(p[i].r).ans -= mod;
}
out.println(map.get(maxL + 1).ans);
}
private void solveF() throws IOException {
}
void shuffleInt(int[] a) {
Random random = new Random();
for (int i = a.length - 1; i > 0; i--) {
int j = random.nextInt(i + 1);
int swap = a[j];
a[j] = a[i];
a[i] = swap;
}
}
void shuffleLong(long[] a) {
Random random = new Random();
for (int i = a.length - 1; i > 0; i--) {
int j = random.nextInt(i + 1);
long swap = a[j];
a[j] = a[i];
a[i] = swap;
}
}
void reverseInt(int[] a) {
for (int i = 0, j = a.length - 1; i < j; i++, j--) {
int swap = a[i];
a[i] = a[j];
a[j] = swap;
}
}
void reverseLong(long[] a) {
for (int i = 0, j = a.length - 1; i < j; i++, j--) {
long swap = a[i];
a[i] = a[j];
a[j] = swap;
}
}
int maxInt(int[] a) {
int max = a[0];
for (int i = 1; i < a.length; i++)
if (max < a[i])
max = a[i];
return max;
}
long maxLong(long[] a) {
long max = a[0];
for (int i = 1; i < a.length; i++)
if (max < a[i])
max = a[i];
return max;
}
int minInt(int[] a) {
int min = a[0];
for (int i = 1; i < a.length; i++)
if (min > a[i])
min = a[i];
return min;
}
long minLong(long[] a) {
long min = a[0];
for (int i = 1; i < a.length; i++)
if (min > a[i])
min = a[i];
return min;
}
long sumInt(int[] a) {
long s = 0;
for (int i = 0; i < a.length; i++)
s += a[i];
return s;
}
long sumLong(long[] a) {
long s = 0;
for (int i = 0; i < a.length; i++)
s += a[i];
return s;
}
long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
long binpowmod(long a, long n) {
long res = 1;
a %= mod;
n %= mod - 1;
while (n > 0) {
if (n % 2 == 1)
res = (res * a) % mod;
a = (a * a) % mod;
n /= 2;
}
return res;
}
class GraphPair implements Comparable<GraphPair> {
int v;
long w;
GraphPair(int v, long w) {
this.v = v;
this.w = w;
}
public int compareTo(GraphPair o) {
return w != o.w ? Long.compare(w, o.w) : Integer.compare(v, o.v);
}
}
ArrayList<Integer>[] createGraph(int n) throws IOException {
ArrayList<Integer>[] graph = new ArrayList[n];
for (int i = 0; i < n; i++)
graph[i] = new ArrayList<>();
return graph;
}
ArrayList<GraphPair>[] createWeightedGraph(int n) throws IOException {
ArrayList<GraphPair>[] graph = new ArrayList[n];
for (int i = 0; i < n; i++)
graph[i] = new ArrayList<>();
return graph;
}
class FastScanner {
StringTokenizer st;
BufferedReader br;
FastScanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s), 32768);
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
boolean hasNext() throws IOException {
return br.ready() || (st != null && st.hasMoreTokens());
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
return a;
}
int[][] nextIntTable(int n, int m) throws IOException {
int[][] a = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
a[i][j] = in.nextInt();
return a;
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
long[] nextLongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = in.nextLong();
return a;
}
long[][] nextLongTable(int n, int m) throws IOException {
long[][] a = new long[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
a[i][j] = in.nextLong();
return a;
}
ArrayList<Integer>[] nextGraph(int n, int m, boolean directed) throws IOException {
ArrayList<Integer>[] graph = createGraph(n);
for (int i = 0; i < m; i++) {
int v = in.nextInt() - 1, u = in.nextInt() - 1;
graph[v].add(u);
if (!directed)
graph[u].add(v);
}
return graph;
}
ArrayList<GraphPair>[] nextWeightedGraph(int n, int m, boolean directed) throws IOException {
ArrayList<GraphPair>[] graph = createWeightedGraph(n);
for (int i = 0; i < m; i++) {
int v = in.nextInt() - 1, u = in.nextInt() - 1;
long w = in.nextLong();
graph[v].add(new GraphPair(u, w));
if (!directed)
graph[u].add(new GraphPair(v, w));
}
return graph;
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
String nextLine() throws IOException {
return br.readLine();
}
boolean hasNextLine() throws IOException {
return br.ready();
}
}
private void run() throws IOException {
in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in"));
out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out"));
for (int t = multitests ? in.nextInt() : 1; t-- > 0; )
solve();
out.flush();
out.close();
}
public static void main(String[] args) throws IOException {
new Main().run();
}
} | Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | d66609885d476748f850fcd83e25224b | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Comparator.*;
public class Main {
FastScanner in;
PrintWriter out;
boolean multitests = false;
long mod = (long) 1e9 + 7; // 998_244_353L || (long) 1e9 + 9
ArrayList<Integer>[] graph;
ArrayList<GraphPair>[] weightedGraph;
private void solve() throws IOException {
// solveA();
// solveB();
// solveC();
// solveD();
solveE();
// solveF();
}
private void solveA() throws IOException {
int n = in.nextInt();
int[] a = in.nextIntArray(n);
int max1 = max(a[0], a[1]), max2 = min(a[0], a[1]);
for (int i = 2; i < n; i++) {
if (a[i] > max1) {
max2 = max1;
max1 = a[i];
} else if (a[i] > max2) {
max2 = a[i];
}
}
out.println(min(n - 2, min(max1, max2) - 1));
}
private void solveB() throws IOException {
int n = in.nextInt();
int[] a = in.nextIntArray(n);
int maxId = 0;
for (int i = 1; i < n; i++)
if (a[i] > a[maxId])
maxId = i;
int prev = a[maxId];
int l = maxId - 1, r = maxId + 1;
while (l >= 0 || r < n) {
if (l < 0 || (r < n && a[l] < a[r])) {
if (a[r] < prev) {
prev = a[r++];
} else
break;
} else if (r >= n || (l >= 0 && a[l] > a[r])) {
if (a[l] < prev) {
prev = a[l--];
} else
break;
} else
break;
}
out.println(l < 0 && r >= n ? "YES" : "NO");
}
private void solveC() throws IOException {
int n = in.nextInt(), k = in.nextInt();
int[] a = in.nextIntArray(n);
int[] b = new int[n - 1];
for (int i = 0; i < n - 1; i++)
b[i] = a[i + 1] - a[i];
shuffleInt(b);
sort(b);
long ans = 0;
for (int i = 0; i < n - k; i++)
ans += b[i];
out.println(ans);
}
private void solveD() throws IOException {
int n = in.nextInt(), m = in.nextInt();
long K = in.nextLong();
long[] a = in.nextLongArray(n);
long[] suffSum = new long[n];
for (int i = n - 1; i >= 0; i--)
suffSum[i] = a[i] + (i + 1 < n ? suffSum[i + 1] : 0);
// out.println(Arrays.toString(suffSum));
long ans = 0;
for (int first = 0; first < min(n, m); first++) {
int len = 1 + (n - (first + 1)) / m;
long[] b = new long[len];
int i = first;
for (int j = 0; j < len; j++, i += m) {
//out.print(i + "|");
b[j] = Long.MIN_VALUE;
for (int k = max(0, i - m + 1); k <= i; k++) {
b[j] = max(b[j], suffSum[k]);
}
b[j] -= K;
}
//out.println();
long del = 0;
for (int j = i - m + 1; j < n; j++)
del += a[j];
for (int j = 0; j < len; j++)
b[j] -= del;
//for (int j = 0; j < len; j++)
//out.print(b[j] + " ");
//out.println();
long max = Long.MIN_VALUE + K;
i = first;
//out.flush();
long pdel = del;
for (int j = 0; j < len; j++, i += m) {
max = max(max - K, b[j]);
del = i + 1 < n ? (suffSum[i + 1] - pdel) : 0;
ans = max(ans, max - del);
}
}
out.println(ans);
}
class Segment {
int l, r;
Segment(int r, int l) {
this.l = l;
this.r = r;
}
}
class Pair {
int diff, ans;
Pair(int diff, int ans) {
this.diff = diff;
this.ans = ans;
}
}
private void solveE() throws IOException {
int n = in.nextInt();
Segment[] p = new Segment[n];
for (int i = 0; i < n; i++)
p[i] = new Segment(in.nextInt(), in.nextInt());
sort(p, comparingInt(o -> o.r));
int maxL = p[0].l;
for (int i = 0; i < n; i++)
if (p[i].l > maxL)
maxL = p[i].l;
long ans = 0;
int minDiff = (int) 1e9 + 1;
TreeMap<Integer, Pair> map = new TreeMap<>();
map.put(0, new Pair(0, 1));
for (int i = 0; i < n; i++) {
int prev = map.floorKey(p[i].l);
Pair pe = map.get(prev);
int newDiff = pe.diff + p[i].l - prev;
if (p[i].r > maxL) {
if (newDiff < minDiff) {
ans = pe.ans;
minDiff = newDiff;
} else if (newDiff == minDiff)
ans = (ans + pe.ans) % mod;
else if (minDiff == (int) 1e9 + 1)
n = 1 / 0;
} else {
Pair next = map.get(p[i].r);
if (next == null || next.diff > newDiff) {
int nd = map.lowerEntry(p[i].r).getValue().diff + p[i].r - map.lowerKey(p[i].r);
if (nd < newDiff) {
map.put(p[i].r, new Pair(nd, map.lowerEntry(p[i].r).getValue().ans));
} else if (nd == newDiff) {
map.put(p[i].r, new Pair(newDiff, pe.ans + map.lowerEntry(p[i].r).getValue().ans));
if (map.get(p[i].r).ans >= mod)
map.get(p[i].r).ans -= mod;
} else { // nd > new Diff
map.put(p[i].r, new Pair(newDiff, pe.ans));
}
} else if (next.diff == newDiff) {
map.get(p[i].r).ans = map.get(p[i].r).ans + pe.ans;
if (map.get(p[i].r).ans >= mod)
map.get(p[i].r).ans -= mod;
}
}
}
out.println(ans);
}
private void solveF() throws IOException {
}
void shuffleInt(int[] a) {
Random random = new Random();
for (int i = a.length - 1; i > 0; i--) {
int j = random.nextInt(i + 1);
int swap = a[j];
a[j] = a[i];
a[i] = swap;
}
}
void shuffleLong(long[] a) {
Random random = new Random();
for (int i = a.length - 1; i > 0; i--) {
int j = random.nextInt(i + 1);
long swap = a[j];
a[j] = a[i];
a[i] = swap;
}
}
void reverseInt(int[] a) {
for (int i = 0, j = a.length - 1; i < j; i++, j--) {
int swap = a[i];
a[i] = a[j];
a[j] = swap;
}
}
void reverseLong(long[] a) {
for (int i = 0, j = a.length - 1; i < j; i++, j--) {
long swap = a[i];
a[i] = a[j];
a[j] = swap;
}
}
int maxInt(int[] a) {
int max = a[0];
for (int i = 1; i < a.length; i++)
if (max < a[i])
max = a[i];
return max;
}
long maxLong(long[] a) {
long max = a[0];
for (int i = 1; i < a.length; i++)
if (max < a[i])
max = a[i];
return max;
}
int minInt(int[] a) {
int min = a[0];
for (int i = 1; i < a.length; i++)
if (min > a[i])
min = a[i];
return min;
}
long minLong(long[] a) {
long min = a[0];
for (int i = 1; i < a.length; i++)
if (min > a[i])
min = a[i];
return min;
}
long sumInt(int[] a) {
long s = 0;
for (int i = 0; i < a.length; i++)
s += a[i];
return s;
}
long sumLong(long[] a) {
long s = 0;
for (int i = 0; i < a.length; i++)
s += a[i];
return s;
}
long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
long binpowmod(long a, long n) {
long res = 1;
a %= mod;
n %= mod - 1;
while (n > 0) {
if (n % 2 == 1)
res = (res * a) % mod;
a = (a * a) % mod;
n /= 2;
}
return res;
}
class GraphPair implements Comparable<GraphPair> {
int v;
long w;
GraphPair(int v, long w) {
this.v = v;
this.w = w;
}
public int compareTo(GraphPair o) {
return w != o.w ? Long.compare(w, o.w) : Integer.compare(v, o.v);
}
}
ArrayList<Integer>[] createGraph(int n) throws IOException {
ArrayList<Integer>[] graph = new ArrayList[n];
for (int i = 0; i < n; i++)
graph[i] = new ArrayList<>();
return graph;
}
ArrayList<GraphPair>[] createWeightedGraph(int n) throws IOException {
ArrayList<GraphPair>[] graph = new ArrayList[n];
for (int i = 0; i < n; i++)
graph[i] = new ArrayList<>();
return graph;
}
class FastScanner {
StringTokenizer st;
BufferedReader br;
FastScanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s), 32768);
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
boolean hasNext() throws IOException {
return br.ready() || (st != null && st.hasMoreTokens());
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
return a;
}
int[][] nextIntTable(int n, int m) throws IOException {
int[][] a = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
a[i][j] = in.nextInt();
return a;
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
long[] nextLongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = in.nextLong();
return a;
}
long[][] nextLongTable(int n, int m) throws IOException {
long[][] a = new long[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
a[i][j] = in.nextLong();
return a;
}
ArrayList<Integer>[] nextGraph(int n, int m, boolean directed) throws IOException {
ArrayList<Integer>[] graph = createGraph(n);
for (int i = 0; i < m; i++) {
int v = in.nextInt() - 1, u = in.nextInt() - 1;
graph[v].add(u);
if (!directed)
graph[u].add(v);
}
return graph;
}
ArrayList<GraphPair>[] nextWeightedGraph(int n, int m, boolean directed) throws IOException {
ArrayList<GraphPair>[] graph = createWeightedGraph(n);
for (int i = 0; i < m; i++) {
int v = in.nextInt() - 1, u = in.nextInt() - 1;
long w = in.nextLong();
graph[v].add(new GraphPair(u, w));
if (!directed)
graph[u].add(new GraphPair(v, w));
}
return graph;
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
String nextLine() throws IOException {
return br.readLine();
}
boolean hasNextLine() throws IOException {
return br.ready();
}
}
private void run() throws IOException {
in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in"));
out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out"));
for (int t = multitests ? in.nextInt() : 1; t-- > 0; )
solve();
out.flush();
out.close();
}
public static void main(String[] args) throws IOException {
new Main().run();
}
} | Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | 80a14507df5ec00e9beff238b1506a44 | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes | //created by Whiplash99
import java.io.*;
import java.util.*;
public class E
{
private static final long MOD=(long) (1e9+7);
static class Pair implements Comparable<Pair>
{
long f, s;
Pair(long f, long s){this.f = f;this.s = s;}
public int compareTo(Pair b){return Long.compare(this.s,b.s);}
}
private static int _lb(Pair pairs[], int start, int end, long val)
{
int mid, ans=pairs.length;
while (start<=end)
{
mid=(start+end)/2;
if(pairs[mid].s>=val){ans=mid; end=mid-1;}
else start=mid+1;
}
return ans;
}
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i,N;
N=Integer.parseInt(br.readLine().trim());
Pair pairs[]=new Pair[N];
for(i=0;i<N;i++)
{
String s[]=br.readLine().trim().split(" ");
long out=Long.parseLong(s[0]);
long in=Long.parseLong(s[1]);
pairs[i]=new Pair(out,in);
}
Arrays.sort(pairs);
Pair suf[]=new Pair[N];
for(i=0;i<N;i++) suf[i]=new Pair(0,0);
suf[N-1].f=pairs[N-1].s; suf[N-1].s=1;
for(i=N-2;i>=0;i--)
{
int pos=_lb(pairs,i+1,N-1,pairs[i].f);
long min,count;
if(pos==N)
{
min=pairs[i].s;
count=1;
}
else
{
min =suf[pos].f-pairs[i].f+pairs[i].s;
count=suf[pos].s;
}
suf[i].f=Math.min(suf[i+1].f,min);
if(suf[i].f==min) suf[i].s+=count;
if(suf[i].f==suf[i+1].f) suf[i].s+=suf[i+1].s;
suf[i].s%=MOD;
}
System.out.println(suf[0].s);
}
} | Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | 2e2d58ce6f68285e94ae6aabc85c0bd0 | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes | //created by Whiplash99
import java.io.*;
import java.util.*;
public class E
{
private static final long MOD=(long) (1e9+7);
static class Pair implements Comparable<Pair>
{
long f, s;
Pair(long f, long s){this.f = f;this.s = s;}
public int compareTo(Pair b){return Long.compare(this.s,b.s);}
}
private static int _lb(Pair pairs[], int start, int end, long val)
{
int mid, ans=pairs.length;
while (start<=end)
{
mid=(start+end)/2;
if(pairs[mid].s>=val){ans=mid; end=mid-1;}
else start=mid+1;
}
return ans;
}
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int i,N;
N=Integer.parseInt(br.readLine().trim());
Pair pairs[]=new Pair[N];
for(i=0;i<N;i++)
{
String s[]=br.readLine().trim().split(" ");
long out=Long.parseLong(s[0]);
long in=Long.parseLong(s[1]);
pairs[i]=new Pair(out,in);
}
Arrays.sort(pairs);
Pair val[]=new Pair[N];
Pair suf[]=new Pair[N];
for(i=0;i<N;i++) {val[i]=new Pair(0,0); suf[i]=new Pair(0,0);}
suf[N-1].f=val[N-1].f=pairs[N-1].s; suf[N-1].s=val[N-1].s=1;
for(i=N-2;i>=0;i--)
{
int pos=_lb(pairs,i+1,N-1,pairs[i].f);
if(pos==N)
{
val[i].f=pairs[i].s;
val[i].s=1;
}
else
{
val[i].f=suf[pos].f-pairs[i].f+pairs[i].s;
val[i].s=suf[pos].s;
}
suf[i].f=Math.min(suf[i+1].f,val[i].f);
if(suf[i].f==val[i].f) suf[i].s+=val[i].s;
if(suf[i].f==suf[i+1].f) suf[i].s+=suf[i+1].s;
suf[i].s%=MOD;
}
System.out.println(suf[0].s);
}
} | Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | 322be64a92ad0e5e456d2e06f8a88d71 | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes | import java.util.*;
import java.io.*;
import java.text.*;
public class Main{
//SOLUTION BEGIN
//Into the Hardware Mode
void pre() throws Exception{}
void solve(int TC) throws Exception{
int n = ni();
long[][] p = new long[n][];
for(int i = 0; i< n; i++)p[i] = new long[]{nl(), nl()};
Arrays.sort(p, (long[] l1, long[] l2) -> Long.compare(l1[1], l2[1]));
TreeMap<Long, Long> ways = new TreeMap<>();
ways.put(0l, 1l);
PriorityQueue<Pair> q = new PriorityQueue<>((Pair p1, Pair p2) -> Long.compare(p1.a, p2.a));
for(int i = 0; i< n; i++){
while(!q.isEmpty() && q.peek().a <= p[i][1]){
Pair pp = q.poll();
ways.put(pp.b, (ways.getOrDefault(pp.b, 0l)+pp.c)%mod);
}
Map.Entry<Long, Long> key = ways.firstEntry();
q.add(new Pair(i, p[i][0], key.getKey()+p[i][1]-p[i][0], key.getValue()));
}
TreeMap<Long, Long> aa = new TreeMap<>();
while(!q.isEmpty()){
Pair pp = q.poll();
aa.put(pp.b+p[pp.ind][0], (aa.getOrDefault(pp.b+p[pp.ind][0], 0l)+pp.c)%mod);
}
pn(aa.firstEntry().getValue());
}
class Pair{
int ind;
long a, b, c;
public Pair(int I, long A, long B, long C){
ind = I;a = A;b = B;c = C;
}
}
//SOLUTION END
void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
long IINF = (long)1e18, mod = (long)1e9+7;
final int INF = (int)1e9, MX = (int)2e5+5;
DecimalFormat df = new DecimalFormat("0.00000000000");
double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-6;
static boolean multipleTC = false, memory = false, fileIO = false;
FastReader in;PrintWriter out;
void run() throws Exception{
if(fileIO){
in = new FastReader("input.txt");
out = new PrintWriter("output.txt");
}else {
in = new FastReader();
out = new PrintWriter(System.out);
}
//Solution Credits: Taranpreet Singh
int T = (multipleTC)?ni():1;
pre();for(int t = 1; t<= T; t++)solve(t);
out.flush();
out.close();
}
public static void main(String[] args) throws Exception{
if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start();
else new Main().run();
}
long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
void p(Object o){out.print(o);}
void pn(Object o){out.println(o);}
void pni(Object o){out.println(o);out.flush();}
String n()throws Exception{return in.next();}
String nln()throws Exception{return in.nextLine();}
int ni()throws Exception{return Integer.parseInt(in.next());}
long nl()throws Exception{return Long.parseLong(in.next());}
double nd()throws Exception{return Double.parseDouble(in.next());}
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception{
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception{
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException e){
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception{
String str = "";
try{
str = br.readLine();
}catch (IOException e){
throw new Exception(e.toString());
}
return str;
}
}
} | Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | f7f82af5b898238e1b0baf33525ab556 | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Collections;
import java.util.TreeSet;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author beginner1010
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
static class TaskE {
final int mod = (int) 1e9 + 7;
final int INF = Integer.MAX_VALUE;
int add(int x, int y) {
x += y;
if (x >= mod) x -= mod;
return x;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
ArrayList<Box> boxes = new ArrayList<>();
int n = in.nextInt();
for (int i = 0; i < n; i++) {
int y = in.nextInt();
int x = in.nextInt();
boxes.add(new Box(x, y, i));
}
Collections.sort(boxes);
for (int i = 0; i < boxes.size(); i++) {
boxes.get(i).idx = i;
}
TreeSet<Box> set = new TreeSet<>();
segmentTree T = new segmentTree(n);
for (int i = n - 1; i >= 0; i--) {
Box cur = boxes.get(i);
Box aux = new Box(cur.y, -1, -1);
Box upper = set.ceiling(aux);
if (upper == null) {
T.update(i, new Pair(cur.x, 1));
} else {
int upperIdx = upper.idx;
Pair min = T.getMin(upperIdx, n);
T.update(i, new Pair(min.space + (cur.x - cur.y), min.ways));
}
set.add(boxes.get(i));
}
out.println(T.getMin(0, n).ways);
}
class Box implements Comparable<Box> {
int x;
int y;
int idx;
Box(int x, int y, int idx) {
this.x = x;
this.y = y;
this.idx = idx;
}
public int compareTo(Box o) {
if (this.x != o.x) return this.x < o.x ? -1 : 1;
if (this.y != o.y) return this.y < o.y ? -1 : 1;
if (this.idx != o.idx) return this.idx < o.idx ? -1 : 1;
return 0;
}
}
class Pair {
int space;
int ways;
Pair(int space, int ways) {
this.space = space;
this.ways = ways;
}
}
class segmentTree {
Pair[] segment;
int n;
Pair ans;
segmentTree(int n) {
this.n = n;
segment = new Pair[n << 1];
Arrays.fill(segment, new Pair(INF, 0));
}
Pair combine(Pair a, Pair b) {
if (a == null)
return new Pair(b.space, b.ways);
if (b == null) {
return new Pair(a.space, a.ways);
}
if (a.space < b.space)
return new Pair(a.space, a.ways);
if (b.space < a.space)
return new Pair(b.space, b.ways);
return new Pair(a.space, add(a.ways, b.ways));
}
Pair getMin(int l, int r) {
ans = new Pair(INF, 0);
for (l += this.n, r += this.n; l < r; l >>= 1, r >>= 1) {
if ((l & 1) == 1) {
ans = combine(segment[l++], ans);
}
if ((r & 1) == 1) {
ans = combine(segment[--r], ans);
}
}
return ans;
}
void update(int pos, Pair val) {
pos += this.n;
segment[pos] = new Pair(val.space, val.ways);
for (pos >>= 1; pos > 0; pos >>= 1) {
segment[pos] = combine(segment[pos * 2], segment[pos * 2 + 1]);
}
}
}
}
static class InputReader {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputStream stream;
public InputReader(InputStream stream) {
this.stream = stream;
}
private boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isWhitespace(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isWhitespace(c));
return res * sgn;
}
}
}
| Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | 3f1250f74a22a738e7f5fc3bae23075b | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Collections;
import java.util.TreeSet;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author beginner1010
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
static class TaskE {
final int mod = (int) 1e9 + 7;
final int INF = Integer.MAX_VALUE;
int add(int x, int y) {
x += y;
if (x >= mod) x -= mod;
return x;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
ArrayList<Box> boxes = new ArrayList<>();
int n = in.nextInt();
for (int i = 0; i < n; i++) {
int y = in.nextInt();
int x = in.nextInt();
boxes.add(new Box(x, y, i));
}
Collections.sort(boxes);
for (int i = 0; i < boxes.size(); i++) {
boxes.get(i).idx = i;
}
TreeSet<Box> set = new TreeSet<>();
segmentTree T = new segmentTree(n);
for (int i = n - 1; i >= 0; i--) {
Box cur = boxes.get(i);
Box aux = new Box(cur.y, -1, -1);
Box upper = set.ceiling(aux);
if (upper == null) {
T.update(i, new Pair(cur.x, 1));
} else {
int upperIdx = upper.idx;
Pair min = T.getMin(upperIdx, n);
T.update(i, new Pair(min.space + (cur.x - cur.y), min.ways));
}
set.add(boxes.get(i));
}
out.println(T.getMin(0, n).ways);
}
class Box implements Comparable<Box> {
int x;
int y;
int idx;
Box(int x, int y, int idx) {
this.x = x;
this.y = y;
this.idx = idx;
}
public int compareTo(Box o) {
if (this.x != o.x) return this.x < o.x ? -1 : 1;
if (this.y != o.y) return this.y < o.y ? -1 : 1;
if (this.idx != o.idx) return this.idx < o.idx ? -1 : 1;
return 0;
}
}
class Pair {
int space;
int ways;
Pair(int space, int ways) {
this.space = space;
this.ways = ways;
}
}
class segmentTree {
Pair[] segment;
int n;
Pair ans;
segmentTree(int n) {
this.n = n;
segment = new Pair[n << 1];
Arrays.fill(segment, new Pair(INF, 0));
}
Pair combine(Pair a, Pair b) {
if (a == null) return new Pair(b.space, b.ways);
if (b == null) return new Pair(a.space, a.ways);
if (a.space < b.space) return new Pair(a.space, a.ways);
if (b.space < a.space) return new Pair(b.space, b.ways);
return new Pair(a.space, add(a.ways, b.ways));
}
Pair getMin(int l, int r) {
ans = new Pair(INF, 0);
for (l += this.n, r += this.n; l < r; l >>= 1, r >>= 1) {
if ((l & 1) == 1) ans = combine(segment[l++], ans);
if ((r & 1) == 1) ans = combine(segment[--r], ans);
}
return ans;
}
void update(int pos, Pair val) {
for (segment[pos += this.n] = new Pair(val.space, val.ways); pos > 0; pos >>= 1) {
segment[pos >> 1] = combine(segment[pos], segment[pos ^ 1]);
}
}
}
}
static class InputReader {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputStream stream;
public InputReader(InputStream stream) {
this.stream = stream;
}
private boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isWhitespace(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isWhitespace(c));
return res * sgn;
}
}
}
| Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | a9ad5380ae4aedeea07285624c411d0b | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Collections;
import java.util.TreeSet;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author beginner1010
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
static class TaskE {
final int mod = (int) 1e9 + 7;
final int INF = Integer.MAX_VALUE;
int add(int x, int y) {
x += y;
if (x >= mod) x -= mod;
return x;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
ArrayList<Box> boxes = new ArrayList<>();
int n = in.nextInt();
for (int i = 0; i < n; i++) {
int y = in.nextInt();
int x = in.nextInt();
boxes.add(new Box(x, y, i));
}
Collections.sort(boxes);
for (int i = 0; i < boxes.size(); i++) {
boxes.get(i).idx = i;
}
TreeSet<Box> set = new TreeSet<>();
segmentTree T = new segmentTree(n);
for (int i = n - 1; i >= 0; i--) {
Box cur = boxes.get(i);
Box aux = new Box(cur.y, -1, -1);
Box upper = set.ceiling(aux);
if (upper == null) {
T.update(i, new Pair(cur.x, 1));
} else {
int upperIdx = upper.idx;
Pair min = T.getMin(upperIdx, n);
T.update(i, new Pair(min.space + (cur.x - cur.y), min.ways));
}
set.add(boxes.get(i));
}
out.println(T.getMin(0, n).ways);
}
class Box implements Comparable<Box> {
int x;
int y;
int idx;
Box(int x, int y, int idx) {
this.x = x;
this.y = y;
this.idx = idx;
}
public int compareTo(Box o) {
if (this.x != o.x) return this.x < o.x ? -1 : 1;
if (this.y != o.y) return this.y < o.y ? -1 : 1;
if (this.idx != o.idx) return this.idx < o.idx ? -1 : 1;
return 0;
}
}
class Pair {
int space;
int ways;
Pair(int space, int ways) {
this.space = space;
this.ways = ways;
}
}
class segmentTree {
Pair[] segment;
int n;
Pair ans;
segmentTree(int n) {
this.n = n;
segment = new Pair[n << 1];
Arrays.fill(segment, new Pair(INF, 0));
}
Pair combine(Pair a, Pair b) {
if (a == null) return new Pair(b.space, b.ways);
if (b == null) return new Pair(a.space, a.ways);
if (a.space < b.space) return new Pair(a.space, a.ways);
if (b.space < a.space) return new Pair(b.space, b.ways);
return new Pair(a.space, add(a.ways, b.ways));
}
Pair getMin(int l, int r) {
ans = new Pair(INF, 0);
for (l += this.n, r += this.n; l < r; l >>= 1, r >>= 1) {
if ((l & 1) == 1) ans = combine(segment[l++], ans);
if ((r & 1) == 1) ans = combine(segment[--r], ans);
}
return ans;
}
void update(int pos, Pair val) {
for (segment[pos += this.n] = new Pair(val.space, val.ways); pos > 0; ) {
Pair a = combine(segment[pos], segment[pos ^ 1]);
segment[pos >>= 1] = a;
}
}
}
}
static class InputReader {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputStream stream;
public InputReader(InputStream stream) {
this.stream = stream;
}
private boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isWhitespace(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isWhitespace(c));
return res * sgn;
}
}
}
| Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | 056fdacf69a5d74d8635745d0a487bb3 | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class E implements Runnable {
public static void main (String[] args) {new Thread(null, new E(), "_cf", 1 << 28).start();}
public void run() {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
System.err.println("");
int n = fs.nextInt();
Doll[] dolls = new Doll[n];
for(int i = 0; i < n; i++) {
dolls[i] = new Doll(fs.nextInt(), fs.nextInt());
}
Arrays.sort(dolls);
long[] mins = new long[n], ways = new long[n];
ST st = new ST(n);
for(int i = n-1; i >= 0; i--) {
int lo = i+1, hi = n-1;
int where = -1;
for(int bs = 0; bs < 50 && lo <= hi; bs++) {
int mid = (lo + hi) / 2;
if(dolls[mid].in >= dolls[i].out) {
where = mid;
hi = mid-1;
}
else {
lo = mid+1;
}
}
if(where == -1) {
st.upd(1, i, dolls[i].in, 1);
}
else {
long[] it = st.query(1, where, n-1);
long v1 = sub(it[0], dolls[i].out);
v1 = add(v1, dolls[i].in);
st.upd(1, i, v1, it[1]);
}
}
//who are the terminals?
long res = 0;
long[] q;
long minVal = (long)1e18;
for(int i = 0; i < n; i++) {
if(i == 0) {
q = st.query(1, i, i);
minVal = Math.min(minVal, q[0]);
}
else if(dolls[i].in < dolls[0].out) {
q = st.query(1, i, i);
minVal = Math.min(minVal, q[0]);
}
}
for(int i = 0; i < n; i++) {
if(i == 0) {
q = st.query(1, i, i);
if(q[0] == minVal)
res = add(res, q[1]);
}
else if(dolls[i].in < dolls[0].out) {
q = st.query(1, i, i);
if(q[0] == minVal)
res = add(res, q[1]);
}
}
out.println(res);
out.close();
}
class Doll implements Comparable<Doll> {
int out, in;
Doll(int o, int i) {
out = o; in = i;
}
public int compareTo(Doll d) {
int comp = Integer.compare(in, d.in);
if(comp == 0) comp = Integer.compare(out, d.out);
return comp;
}
}
int MOD = (int)1e9+7;
long sub(long a, long b) {
a -= b;
if(a < 0) a += MOD;
return a;
}
long add(long a, long b) {
a += b;
if(a >= MOD) a -= MOD;
return a;
}
class ST {
int n, lo[], hi[];
long[] minFree, waysMin;
long oo = (long)1e18;
ST(int a) {
n = 4 * a + 100;
lo = new int[n];
hi = new int[n];
minFree = new long[n];
waysMin = new long[n];
init(1, 0, a-1);
}
void init(int p, int L, int R) {
lo[p] = L; hi[p] = R;
if(L == R) {
minFree[p] = oo;
waysMin[p] = 1;
return;
}
int lf = 2*p, rg = 1+lf;
int mid = (L+R)/2;
init(lf, L, mid);
init(rg, mid+1, R);
}
void upd(int p, int idx, long val, long ways) {
if(lo[p] == hi[p]) {
minFree[p] = val;
waysMin[p] = ways;
return;
}
int lf = 2*p, rg = 1+lf;
if(idx <= hi[lf]) {
upd(lf, idx, val, ways);
}
else {
upd(rg, idx, val, ways);
}
if(minFree[lf] == minFree[rg]) {
minFree[p] = minFree[lf];
waysMin[p] = add(waysMin[lf],waysMin[rg]);
}
else if(minFree[lf] < minFree[rg]) {
minFree[p] = minFree[lf];
waysMin[p] = waysMin[lf];
}
else {
minFree[p] = minFree[rg];
waysMin[p] = waysMin[rg];
}
}
long[] query(int p, int L, int R) {
if(hi[p] < L || R < lo[p]) return null;
if(L <= lo[p] && hi[p] <= R) {
return new long[] {minFree[p], waysMin[p]};
}
int lf = 2*p, rg = 1+lf;
long[] r1 = query(lf, L, R);
long[] r2 = query(rg, L, R);
if(r1 == null) return r2;
if(r2 == null) return r1;
if(r1[0] < r2[0]) return r1;
if(r2[0] < r1[0]) return r2;
r1[1] = add(r1[1], r2[1]);
return r1;
}
}
class FastScanner {
public int BS = 1<<16;
public char NC = (char)0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
public char nextChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public long nextLong() {
num=1;
boolean neg = false;
if(c==NC)c=nextChar();
for(;(c<'0' || c>'9'); c = nextChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=nextChar()) {
res = (res<<3)+(res<<1)+c-'0';
num*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/num;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c>32) {
res.append(c);
c=nextChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c!='\n') {
res.append(c);
c=nextChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=nextChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
public int[] nextIntArray(int n) {
int[] res = new int[n];
for(int i = 0; i < n; i++) res[i] = nextInt();
return res;
}
}
} | Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | ea53eb50f4f8633823d1e603d2eabadf | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.Comparator;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Rustam Musin (t.me/musin_acm)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
EKulturniiKod solver = new EKulturniiKod();
solver.solve(1, in, out);
out.close();
}
static class EKulturniiKod {
int mod = (int) 1e9 + 7;
int inf = (int) 1e9 + 1;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
Item[] a = new Item[n];
for (int i = 0; i < n; i++) {
int out1 = in.readInt();
int in1 = in.readInt();
a[i] = new Item(i, in1, out1);
}
Arrays.sort(a, Comparator.comparingInt(i -> i.in));
Fenwick fenwick = new InvFenwick(n);
for (int i = n - 1; i >= 0; i--) {
int j = findFirstIndexByIn(a, a[i].out);
Node p = fenwick.get(j);
Node r = j == n
? new Node(a[i].in, 1)
: new Node(p.emptiness - (a[i].out - a[i].in), p.count);
fenwick.add(i, r);
}
Node ans = fenwick.get(0);
out.print(ans.count);
}
int findFirstIndexByIn(Item[] a, int minIn) {
int l = -1;
int r = a.length;
while (r - l > 1) {
int m = l + r >> 1;
if (a[m].in < minIn) {
l = m;
} else {
r = m;
}
}
return r;
}
class Item {
final int index;
final int in;
final int out;
Item(int index, int in, int out) {
this.index = index;
this.in = in;
this.out = out;
}
public String toString() {
return "Item{" +
"index=" + index +
", in=" + in +
", out=" + out +
'}';
}
}
class Node implements Comparable<Node> {
final int emptiness;
final int count;
Node(int emptiness, int count) {
this.emptiness = emptiness;
this.count = count;
}
Node combine(Node with) {
if (equals(with)) {
return new Node(emptiness, (count + with.count) % mod);
}
return compareTo(with) < 0 ? this : with;
}
public int compareTo(Node o) {
return Integer.compare(emptiness, o.emptiness);
}
public boolean equals(Object obj) {
return compareTo((Node) obj) == 0;
}
public String toString() {
return "Node{" +
"emptiness=" + emptiness +
", count=" + count +
'}';
}
}
class InvFenwick extends Fenwick {
final int n;
InvFenwick(int n) {
super(n);
this.n = n;
}
Node get(int at) {
return super.get(inv(at));
}
void add(int at, Node node) {
super.add(inv(at), node);
}
int inv(int at) {
return n - at - 1;
}
}
class Fenwick {
Node[] tree;
Fenwick(int n) {
tree = new Node[n + 1];
Arrays.fill(tree, new Node(inf, 0));
}
Node get(int at) {
Node res = new Node(inf, 0);
for (at++; at > 0; at -= at & -at) {
res = res.combine(tree[at]);
}
return res;
}
void add(int at, Node node) {
for (at++; at < tree.length; at += at & -at) {
tree[at] = tree[at].combine(node);
}
}
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void print(int i) {
writer.print(i);
}
}
}
| Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | 183125326e6c6ff06f08dfcd57a4c484 | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes | import java.util.*;
import java.math.*;
public class Solution{
private int mod = (int)Math.pow(10, 9) + 7;
private int [][] st;
private int n;
private void solve(){
Scanner sc = new Scanner(System.in);
this.n = sc.nextInt();
int [][] dolls = new int[n][2];
for(int i = 0; i < n; i++){
int s = sc.nextInt();
int d = sc.nextInt();
dolls[i][0] = s;
dolls[i][1] = d;
}
// nested if outi <= inj
Arrays.sort(dolls, new Comparator<int[]>(){
@Override
public int compare(int [] a, int [] b){
if(a[1] == b[1]){
return a[0] - b[0];
}
return a[1] - b[1];
}
});
st = new int[n * 2 + 1][2];
for(int i = 0; i < st.length; i++){
st[i] = new int[]{Integer.MAX_VALUE, 0};
}
for(int i = n - 1; i >=0; i--){
int pos = lower(dolls, dolls[i][0]);
if(pos == -1){
setPos(i, new int[]{dolls[i][1], 1});
}else{
int [] best = getMin(pos, n);
setPos(i, new int[]{best[0] - (dolls[i][0] - dolls[i][1]), best[1]});
}
}
System.out.println(getMin(0, n)[1]);
}
private void setPos(int pos, int [] cur){
for(st[pos += n] = cur; pos > 1; pos>>=1){
st[pos>>1] = combine(st[pos], st[pos | 1]);
}
}
private int [] getMin(int l, int r){
int [] ans = new int[]{Integer.MAX_VALUE, 0};
for(l += n, r += n; l < r; l >>= 1, r >>= 1){
if((l & 1) != 0){
ans = combine(ans, st[l]);
l++;
}
if((r & 1) != 0){
r--;
ans = combine(ans, st[r]);
}
}
return ans;
}
private int [] combine(int [] a, int [] b){
if(a[0] < b[0]){
return a;
}
if(b[0] < a[0]){
return b;
}
return new int[]{a[0], (a[1] + b[1]) % mod};
}
private int lower(int [][] dolls, int val){
int l = 0;
int r = dolls.length - 1;
int ans = -1;
while(l <= r){
int mid = (r + l) / 2;
int cur = dolls[mid][1];
if(cur < val){
l = mid + 1;
}else{
ans = mid;
r = mid - 1;
}
}
return ans;
}
public static void main(String [] args){
new Solution().solve();
}
} | Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | a7486f28b3ce43f6b366394f332ade1a | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes | import java.util.*;
import java.math.*;
public class Solution{
private int mod = (int)Math.pow(10, 9) + 7;
private int [][] st;
private int n;
private void solve(){
Scanner sc = new Scanner(System.in);
this.n = sc.nextInt();
int [][] dolls = new int[n][2];
for(int i = 0; i < n; i++){
int s = sc.nextInt();
int d = sc.nextInt();
dolls[i][0] = s;
dolls[i][1] = d;
}
// nested if outi <= inj
Arrays.sort(dolls, new Comparator<int[]>(){
@Override
public int compare(int [] a, int [] b){
return a[1] - b[1];
}
});
st = new int[n * 2 + 1][2];
for(int i = 0; i < st.length; i++){
st[i] = new int[]{Integer.MAX_VALUE, 0};
}
for(int i = n - 1; i >=0; i--){
int pos = lower(dolls, dolls[i][0]);
if(pos == -1){
setPos(i, new int[]{dolls[i][1], 1});
}else{
int [] best = getMin(pos, n);
setPos(i, new int[]{best[0] - (dolls[i][0] - dolls[i][1]), best[1]});
}
}
System.out.println(getMin(0, n)[1]);
}
private void setPos(int pos, int [] cur){
for(st[pos += n] = cur; pos > 1; pos>>=1){
st[pos>>1] = combine(st[pos], st[pos | 1]);
}
}
private int [] getMin(int l, int r){
int [] ans = new int[]{Integer.MAX_VALUE, 0};
for(l += n, r += n; l < r; l >>= 1, r >>= 1){
if((l & 1) != 0){
ans = combine(ans, st[l]);
l++;
}
if((r & 1) != 0){
r--;
ans = combine(ans, st[r]);
}
}
return ans;
}
private int [] combine(int [] a, int [] b){
if(a[0] < b[0]){
return a;
}
if(b[0] < a[0]){
return b;
}
return new int[]{a[0], (a[1] + b[1]) % mod};
}
private int lower(int [][] dolls, int val){
int l = 0;
int r = dolls.length - 1;
int ans = -1;
while(l <= r){
int mid = (r + l) / 2;
int cur = dolls[mid][1];
if(cur < val){
l = mid + 1;
}else{
ans = mid;
r = mid - 1;
}
}
return ans;
}
public static void main(String [] args){
new Solution().solve();
}
} | Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | a68c6514b9348a4e671c4e8e7dd6062a | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes | import java.lang.*;
import java.math.*;
import java.util.*;
import java.io.*;
public class Main {
class Pair implements Comparable<Pair> {
long in;
long out;
public Pair(long out, long in) {
this.in = in;
this.out = out;
}
public int compareTo(Pair c) {
int t = Long.compare(this.in, c.in);
if (t != 0) return t;
return Long.compare(this.out, c.out);
}
}
class Node {
long mn;
long fq;
public Node(long mn, long fq) {
this.mn = mn;
this.fq = fq;
}
}
void solve() {
int n = ni();
Pair p[] = new Pair[n + 1];
for (int i = 1; i <= n; i++) p[i] = new Pair(nl(), nl());
Arrays.sort(p, 1, n + 1);
// for(int i=1;i<=n;i++) pw.println(p[i].in+" "+p[i].out);
tree = new Node[4 * n + 1];
build(1, 1, n);
Node dp[] = new Node[n + 1];
int l, r, mid, idx = -1;
long mn=Long.MAX_VALUE;
for (int i = 1; i <= n; i++) {
l = 1;
r = i - 1;
idx = -1;
while (l <= r) {
mid = (l + r) >> 1;
if (p[mid].out <= p[i].in) {
idx = mid;
l = mid + 1;
} else r = mid - 1;
}
if (idx == -1) {
dp[i] = new Node(p[i].in, 1);
} else {
Node nd = query(1, 1, idx, 1, n);
dp[i] = new Node(nd.mn + p[i].in, nd.fq);
}
update(1, 1, n, i, new Node(dp[i].mn - p[i].out, dp[i].fq));
}
for(int i=n;i>=1;i--){
if(p[i].out<=p[n].in) continue;
mn=Math.min(mn,dp[i].mn);
}
long ans = 0;
for(int i=n;i>=1;i--) {
if (p[i].out <= p[n].in || mn != dp[i].mn) continue;
ans = add(ans, dp[i].fq);
}
// for(int i=1;i<=n;i++) pw.println(dp[i].mn+" "+dp[i].fq);
pw.println(ans);
}
Node tree[];
void build(int id, int l, int r) {
if (l == r) {
tree[id] = new Node(Long.MAX_VALUE, 1);
} else {
int mid = (l + r) >> 1;
build(2 * id, l, mid);
build(2 * id + 1, mid + 1, r);
merge(id);
}
}
void update(int id, int l, int r, int idx, Node p) {
if (l == r) {
tree[id] = new Node(p.mn, p.fq);
} else {
int mid = (l + r) >> 1;
if (idx <= mid) update(2 * id, l, mid, idx, p);
else update(2 * id + 1, mid + 1, r, idx, p);
merge(id);
}
}
Node query(int id, int x, int y, int l, int r) {
if (l > r) return new Node(Long.MAX_VALUE, 1);
if (r < x || l > y) return new Node(Long.MAX_VALUE, 1);
if (x <= l && r <= y) return tree[id];
int mid = (l + r) >> 1;
Node p1 = query(2 * id, x, y, l, mid);
Node p2 = query(2 * id + 1, x, y, mid + 1, r);
Node p = null;
if (p1.mn == p2.mn) p = new Node(p1.mn, add(p1.fq, p2.fq));
else if (p1.mn < p2.mn) p = new Node(p1.mn, p1.fq);
else p = new Node(p2.mn, p2.fq);
return p;
}
void merge(int id) {
if (tree[2 * id].mn == tree[2 * id + 1].mn) {
tree[id] = new Node(tree[2 * id].mn, add(tree[2 * id].fq, tree[2 * id + 1].fq));
} else if (tree[2 * id].mn < tree[2 * id + 1].mn) {
tree[id] = new Node(tree[2 * id].mn, tree[2 * id].fq);
} else tree[id] = new Node(tree[2 * id + 1].mn, tree[2 * id + 1].fq);
}
long add(long x, long y) {
x += y;
if (x >= M) x -= M;
return x;
}
long M = (long) 1e9 + 7;
InputStream is;
PrintWriter pw;
String INPUT = "";
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
pw = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
pw.flush();
if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new Main().run();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++) map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) {
if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o));
}
} | Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | f9087f232d1fd7dd5b3c83c3c241b597 | train_003.jsonl | 1563806100 | There are famous Russian nesting dolls named matryoshkas sold in one of the souvenir stores nearby, and you'd like to buy several of them. The store has $$$n$$$ different matryoshkas. Any matryoshka is a figure of volume $$$out_i$$$ with an empty space inside of volume $$$in_i$$$ (of course, $$$out_i > in_i$$$).You don't have much free space inside your bag, but, fortunately, you know that matryoshkas can be nested one inside another. Formally, let's call a set of matryoshkas nested if we can rearrange dolls in such a way, that the first doll can be nested inside the second one, the second doll β inside the third one and so on. Matryoshka $$$i$$$ can be nested inside matryoshka $$$j$$$ if $$$out_i \le in_j$$$. So only the last doll will take space inside your bag.Let's call extra space of a nested set of dolls as a total volume of empty space inside this structure. Obviously, it's equal to $$$in_{i_1} + (in_{i_2} - out_{i_1}) + (in_{i_3} - out_{i_2}) + \dots + (in_{i_k} - out_{i_{k-1}})$$$, where $$$i_1$$$, $$$i_2$$$, ..., $$$i_k$$$ are the indices of the chosen dolls in the order they are nested in each other.Finally, let's call a nested subset of the given sequence as big enough if there isn't any doll from the sequence that can be added to the nested subset without breaking its nested property.You want to buy many matryoshkas, so you should choose a big enough nested subset to buy it. But you will be disappointed if too much space in your bag will be wasted, so you want to choose a big enough subset so that its extra space is minimum possible among all big enough subsets. Now you wonder, how many different nested subsets meet these conditions (they are big enough, and there is no big enough subset such that its extra space is less than the extra space of the chosen subset). Two subsets are considered different if there exists at least one index $$$i$$$ such that one of the subsets contains the $$$i$$$-th doll, and another subset doesn't.Since the answer can be large, print it modulo $$$10^9 + 7$$$. | 256 megabytes | /**
* Created by Aminul on 7/23/2019.
*/
import org.omg.CORBA.INTERNAL;
import sun.reflect.generics.tree.Tree;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import static java.lang.Math.*;
public class E_3 {
static final long mod = (long) 1e9 + 7, inf = (long)2e9;
public static void main(String[] args) throws Exception {
FastReader in = new FastReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = in.nextInt();
Pair[] pairs = new Pair[n];
long minOut = Long.MAX_VALUE, maxIn = 0;
TreeSet<Integer> set = new TreeSet<>();
for (int i = 0; i < n; i++) {
int out = in.nextInt(), inn = in.nextInt();
set.add(inn);
set.add(out);
pairs[i] = new Pair(inn, out);
minOut = min(minOut, out);
maxIn = max(maxIn, inn);
}
int N = set.size(), idx = 1;
HashMap<Integer, Integer> map = new HashMap<>();
for(int i : set) {
map.put(i, idx++);
}
SegTree segTree = new SegTree(N);
Arrays.sort(pairs);
for (int i = n - 1; i >= 0; i--) {
int x = pairs[i].in, out = pairs[i].out;
int Xorg = map.get(x), Yorg = map.get(out);
if (out > maxIn) {
Node tmp = segTree.query(Xorg, Xorg);
if(tmp.cost == inf) {
tmp.cost = x;
tmp.count = 0;
}
tmp.count++;
segTree.update(Xorg, tmp);
// debug(i, pairs[i], Xorg, tmp);
} else {
Node ceilVal = segTree.query(Yorg, N);
ceilVal.cost += (x - out);
Node tmp = segTree.query(Xorg, Xorg);
//if(tmp.cost == inf) tmp.count = 0;
if (tmp == null || tmp.cost == inf || tmp.cost > ceilVal.cost) tmp = ceilVal;
else if (tmp.cost == ceilVal.cost) {
tmp.count += ceilVal.count;
if (tmp.count >= mod) tmp.count -= mod;
}
// debug(i, pairs[i], Xorg, tmp, ceilVal);
segTree.update(Xorg, tmp);
}
//debug(pairs[i], " ", map);
}
long minCost = Long.MAX_VALUE, cnt = 0, last = 0;
for (int i = 0; i < n; i++) {
int x = pairs[i].in, out = pairs[i].out;
if(x <= last) continue;
last = x;
int Xorg = map.get(x), Yorg = map.get(out);
if (x >= minOut) {
break;
}
Node tmp = segTree.query(Xorg, Xorg);
if (tmp.cost == minCost) {
cnt += tmp.count;
if (cnt >= mod) cnt -= mod;
//debug(tmp, cnt);
} else if (tmp.cost < minCost) {
minCost = tmp.cost;
cnt = tmp.count;
}
}
pw.println(cnt);
pw.close();
}
static void debug(Object... obj) {
System.err.println(Arrays.deepToString(obj));
}
static class Node {
long cost, count;
Node() {
}
Node(long Cost, long Count) {
cost = Cost;
count = Count;
}
void setValues(long Cost, long Count) {
cost = Cost;
count = Count;
}
@Override
public String toString() {
return cost + " " + count;
}
Node copy() {
return new Node(cost, count);
}
}
static class Pair implements Comparable<Pair> {
int in, out;
Pair(int IN, int OUT) {
in = IN;
out = OUT;
}
public int compareTo(Pair p) {
if (in == p.in) return out - p.out;
return in - p.in;
}
public String toString() {
return in + " " + out;
}
}
static int arr[];
static class SegTree{
int n ;
Node seg[];
int DEFAULT_VALUE = 0; // change here
SegTree(int N){
n = N;
seg = new Node[4*n];
for (int i = 0; i < seg.length; i++) {
seg[i] = new Node((int)2e9, 0);
}
}
void update(int pos, Node val){
update(1, 1, n, pos, val);
}
void update(int p, int s, int e, int pos, Node val){
if(s == pos && e == pos){
seg[p] = val;
return;
}
if(s > pos || s > e || e < pos) return;
int m = (s+e)/2, l = 2*p, r = 2*p+1;
update(l, s, m, pos, val);
update(r, m+1, e, pos, val);
if(seg[p] == null) seg[p] = new Node();
if(seg[l].cost == seg[r].cost) {
seg[p].cost = seg[l].cost;
seg[p].count = seg[l].count + seg[r].count;
if(seg[p].count >= mod) {
seg[p].count -= mod;
}
} else if(seg[l].cost < seg[r].cost) seg[p].setValues(seg[l].cost, seg[l].count);
else seg[p].setValues(seg[r].cost, seg[r].count);
}
Node query(int l, int r){
return query(1, 1, n, l, r);
}
Node query(int p, int s, int e, int a, int b){
if(s >= a && e <= b){
if(seg[p] == null) return null;
return seg[p].copy();
}
if(s > e || s > b || e < a) return null;
int m = (s+e)/2, l = 2*p, r = 2*p+1;
Node x = query(l, s, m, a, b), y = query(r, m+1,e , a, b);
if(x == null) return y;
if(y == null) return x;
if(x.cost < y.cost) return x;
if(y.cost < x.cost) return y;
x.count += y.count;
if(x.count >= mod) x.count -= mod;
return x;
}
}
static class FastReader {
InputStream is;
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
public FastReader(InputStream is) {
this.is = is;
}
public int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
public boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
public String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public String nextLine() {
int c = skip();
StringBuilder sb = new StringBuilder();
while (!isEndOfLine(c)) {
sb.appendCodePoint(c);
c = readByte();
}
return sb.toString();
}
public int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = (num << 3) + (num << 1) + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = (num << 3) + (num << 1) + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
public char[] next(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
public char readChar() {
return (char) skip();
}
}
} | Java | ["7\n4 1\n4 2\n4 2\n2 1\n5 4\n6 4\n3 2"] | 2 seconds | ["6"] | NoteThere are $$$6$$$ big enough nested subsets with minimum possible extra space in the example: $$$\{1, 5\}$$$: we can't add any other matryoshka and keep it nested; it's extra space is $$$1$$$; $$$\{1, 6\}$$$; $$$\{2, 4, 5\}$$$; $$$\{2, 4, 6\}$$$; $$$\{3, 4, 5\}$$$; $$$\{3, 4, 6\}$$$. There are no more "good" subsets because, for example, subset $$$\{6, 7\}$$$ is not big enough (we can add the $$$4$$$-th matryoshka to it) or subset $$$\{4, 6, 7\}$$$ has extra space equal to $$$2$$$. | Java 8 | standard input | [
"dp",
"combinatorics",
"shortest paths",
"sortings",
"data structures",
"binary search"
] | d8c2cb03579142f45d46f1fe22a9b8c0 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β the number of matryoshkas. The next $$$n$$$ lines contain a description of each doll: two integers $$$out_i$$$ and $$$in_i$$$ ($$$1 \le in_i < out_i \le 10^9$$$) β the outer and inners volumes of the $$$i$$$-th matryoshka. | 2,300 | Print one integer β the number of big enough nested subsets such that extra space of each of these subsets is minimum possible. Since the answer can be large, print it modulo $$$10^9 + 7$$$. | standard output | |
PASSED | 8a6cc48f844b7ee50b1c22c2111aa6ec | train_003.jsonl | 1522850700 | Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak,βi,βj; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
import java.lang.*;
public class Main {
private static FastReader sc = new FastReader(System.in);
private static OutputWriter out = new OutputWriter(System.out);
public static void main(String[] args) throws Exception {
int n = sc.nextInt();
int[][][] arr = new int[4][n][n];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
arr[i][j][k] = Character.getNumericValue(sc.nextCharacter());
}
}
}
int[] zeroFirst = new int[4];
for (int i = 0; i < 4; i++) {
int cnt = 0;
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
if (j % 2 == k % 2 && arr[i][j][k] != 0) cnt++;
else if (j % 2 != k % 2 && arr[i][j][k] != 1) cnt++;
}
}
zeroFirst[i] = cnt;
}
int min = Integer.MAX_VALUE;
min = Math.min(min, calc(0, 1, 2, 3, zeroFirst, n));
min = Math.min(min, calc(0, 2, 1, 3, zeroFirst, n));
min = Math.min(min, calc(0, 3, 2, 1, zeroFirst, n));
System.out.println(min);
}
private static int calc(int a, int b, int c, int d, int[] zeroFirst, int n) {
int a1 = zeroFirst[a] + zeroFirst[b] + 2 * n * n - zeroFirst[c] - zeroFirst[d];
int a2 = zeroFirst[c] + zeroFirst[d] + 2 * n * n - zeroFirst[a] - zeroFirst[b];
return Math.min(a1, a2);
}
}
class FastReader {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c == ',') {
c = read();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String nextLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String nextLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return nextLine();
} else {
return readLine0();
}
}
public BigInteger nextBigInteger() {
try {
return new BigInteger(nextString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char nextCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1)
read();
return value == -1;
}
public String next() {
return nextString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
} | Java | ["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"] | 1 second | ["1", "2"] | null | Java 8 | standard input | [
"implementation",
"bitmasks",
"brute force"
] | dc46c6cb6b4b9b5e7e6e5b4b7d034874 | The first line contains odd integer n (1ββ€βnββ€β100) β the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line. | 1,400 | Print one number β minimum number of squares Magnus should recolor to be able to obtain a valid chessboard. | standard output | |
PASSED | 6a2fc348d6ea9904a6a26feb27a00ae1 | train_003.jsonl | 1522850700 | Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak,βi,βj; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Codechef
{ static PrintWriter out=new PrintWriter(System.out);static FastScanner in = new FastScanner(System.in);static class FastScanner {BufferedReader br;StringTokenizer stok;FastScanner(InputStream is) {br = new BufferedReader(new InputStreamReader(is));}
String next() throws IOException {while (stok == null || !stok.hasMoreTokens()) {String s = br.readLine();if (s == null) {return null;}
stok = new StringTokenizer(s);}return stok.nextToken();}
int ni() throws IOException {return Integer.parseInt(next());}long nl() throws IOException {return Long.parseLong(next());}double nd() throws IOException {return Double.parseDouble(next());}char nc() throws IOException {return (char) (br.read());}String ns() throws IOException {return br.readLine();}
int[] nia(int n) throws IOException{int a[] = new int[n];for (int i = 0; i < n; i++)a[i] = ni();return a;}long[] nla(int n) throws IOException {long a[] = new long[n];for (int i = 0; i < n; i++)a[i] = nl();return a;}
double[] nda(int n)throws IOException {double a[] = new double[n];for (int i = 0; i < n; i++)a[i] = nd();return a;}int [][] imat(int n,int m) throws IOException{int mat[][]=new int[n][m];for(int i=0;i<n;i++){for(int j=0;j<m;j++)mat[i][j]=ni();}return mat;}
}
static long mod=Long.MAX_VALUE;
public static void main (String[] args) throws java.lang.Exception
{ int i,j;
HashMap<Integer,Long> hm=new HashMap<Integer,Long>();
/* if(hm.containsKey(z))
hm.put(z,hm.get(z)+1);
else
hm.put(z,1);
*/
ArrayList<Integer> arr=new ArrayList<Integer>();
HashSet<Integer> set=new HashSet<Integer>();
PriorityQueue<Integer> pq=new PriorityQueue<Integer>();
int n=in.ni();
int temp[][]=new int[4][2];
for(int k=0;k<4;k++)
{ int count1=0,count2=0;
for(i=0;i<n;i++)
{ String s=in.next();
for(j=0;j<n;j++)
{ //out.print(s.charAt(j)+" ");
if((i+j)%2!=s.charAt(j)-'0')
count1++;
if((i+j+1)%2!=s.charAt(j)-'0')
count2++;
}
//out.println();
temp[k][0]=count1;
temp[k][1]=count2;
}
//out.println();
}
//for(i=0;i<4;i++)
// out.println(temp[i][0]+" "+temp[i][1]);
int ans=100000000;
set.add(1);set.add(2);set.add(3);set.add(0);
for(i=0;i<4;i++)
{ for(j=i+1;j<4;j++)
{ int max=temp[i][0]+temp[j][0];
for(int c:set)
{
if(c!=i && c!=j)
max+=temp[c][1];
}
ans=Math.min(ans,max);
}
}
out.println(ans);
out.close();
}
static class pair implements Comparable<pair>{
int x, y;
public pair(int x, int y){this.x = x; this.y = y;}
@Override
public int compareTo(pair arg0)
{ if(x<arg0.x) return -1;
else if(x==arg0.x)
{ if(y<arg0.y) return -1;
else if(y>arg0.y) return 1;
else return 0;
}
else return 1;
}
}
static long gcd(long a,long b)
{ if(b==0)
return a;
return gcd(b,a%b);
}
static long exponent(long a,long n)
{ long ans=1;
while(n!=0)
{ if(n%2==1)
ans=(ans*a)%mod;
a=(a*a)%mod;
n=n>>1;
}
return ans;
}
static int binarySearch(int a[], int item, int low, int high)
{ if (high <= low)
return (item > a[low])? (low + 1): low;
int mid = (low + high)/2;
if(item == a[mid])
return mid+1;
if(item > a[mid])
return binarySearch(a, item, mid+1, high);
return binarySearch(a, item, low, mid-1);
}
static void merge(int arr[], int l, int m, int r) {
int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; int R[] = new int [n2];
for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else{ arr[k] = R[j]; j++; } k++; } while (i < n1){ arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; }
}
static void Sort(int arr[], int l, int r) {if (l < r) { int m = (l+r)/2; Sort(arr, l, m); Sort(arr , m+1, r); merge(arr, l, m, r); } }
static void sort(int a[])
{Sort(a,0,a.length-1);}
} | Java | ["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"] | 1 second | ["1", "2"] | null | Java 8 | standard input | [
"implementation",
"bitmasks",
"brute force"
] | dc46c6cb6b4b9b5e7e6e5b4b7d034874 | The first line contains odd integer n (1ββ€βnββ€β100) β the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line. | 1,400 | Print one number β minimum number of squares Magnus should recolor to be able to obtain a valid chessboard. | standard output | |
PASSED | b5f6bef137dd8078132379fb18a3fedc | train_003.jsonl | 1522850700 | Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak,βi,βj; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.StringTokenizer;
public class Main {
private static int N;
private static int[][] standard1, standard2, board;
private static ArrayList<int[]> permutations = new ArrayList<int[]>();
private static int[][][] pieces;
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(f.readLine());
N = Integer.parseInt(st.nextToken());
standard1 = new int[2 * N][2 * N];
standard2 = new int[2 * N][2 * N];
pieces = new int[4][N][N];
for (int i = 0; i < 2 * N; i++) {
for (int k = 0; k < 2 * N; k++) {
if (i % 2 == 0) {
if (k % 2 == 0) {
standard1[i][k] = 0;
standard2[i][k] = 1;
} else {
standard1[i][k] = 1;
standard2[i][k] = 0;
}
} else {
if (k % 2 == 0) {
standard1[i][k] = 1;
standard2[i][k] = 0;
} else {
standard1[i][k] = 0;
standard2[i][k] = 1;
}
}
}
}
generate(new int[4], 0);
for (int k = 0; k < 4; k++) {
for (int i = 0; i < N; i++) {
String str = f.readLine();
for (int j = 0; j < N; j++) {
pieces[k][i][j] = Integer.parseInt(str.substring(j, j + 1));
}
}
if (k != 3) {
f.readLine();
}
}
int res = Integer.MAX_VALUE;
for (int[] array : permutations) {
createBoard(array);
res = Math.min(res, check());
}
System.out.println(res);
}
public static void createBoard(int[] array) {
board = new int[2 * N][2 * N];
int[][] b0 = pieces[array[0]];
int[][] b1 = pieces[array[1]];
int[][] b2 = pieces[array[2]];
int[][] b3 = pieces[array[3]];
for (int i = 0; i < N; i++) {
for (int k = 0; k < N; k++) {
board[i][k] = b0[i][k];
board[i][k + N] = b1[i][k];
board[i + N][k] = b2[i][k];
board[i + N][k + N] = b3[i][k];
}
}
}
public static int check() {
int res1 = 0;
int res2 = 0;
for (int i = 0; i < 2 * N; i++) {
for (int k = 0; k < 2 * N; k++) {
if (board[i][k] != standard1[i][k]) {
res1++;
}
if (board[i][k] != standard2[i][k]) {
res2++;
}
}
}
return Math.min(res1, res2);
}
public static void generate(int[] array, int index) {
if (index == 4) {
int[] copy = array.clone();
HashSet<Integer> set = new HashSet<Integer>();
for (int i : copy)
set.add(i);
if (set.size() < 4)
return;
permutations.add(copy);
return;
}
for (int i = 0; i < 4; i++) {
array[index] = i;
generate(array, index + 1);
}
}
} | Java | ["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"] | 1 second | ["1", "2"] | null | Java 8 | standard input | [
"implementation",
"bitmasks",
"brute force"
] | dc46c6cb6b4b9b5e7e6e5b4b7d034874 | The first line contains odd integer n (1ββ€βnββ€β100) β the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line. | 1,400 | Print one number β minimum number of squares Magnus should recolor to be able to obtain a valid chessboard. | standard output | |
PASSED | a3891c241d0fa8695f316fd05313ed6d | train_003.jsonl | 1522850700 | Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak,βi,βj; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Main {
private static int N;
private static int[][] standard1, standard2, board;
private static ArrayList<int[]> permutations = new ArrayList<int[]>();
private static int[][][] pieces;
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(f.readLine());
N = Integer.parseInt(st.nextToken());
standard1 = new int[2 * N][2 * N];
standard2 = new int[2 * N][2 * N];
pieces = new int[4][N][N];
for (int i = 0; i < 2 * N; i++) {
for (int k = 0; k < 2 * N; k++) {
if (i % 2 == 0) {
if (k % 2 == 0) {
standard1[i][k] = 0;
standard2[i][k] = 1;
} else {
standard1[i][k] = 1;
standard2[i][k] = 0;
}
} else {
if (k % 2 == 0) {
standard1[i][k] = 1;
standard2[i][k] = 0;
} else {
standard1[i][k] = 0;
standard2[i][k] = 1;
}
}
}
}
permutations.add(new int[] { 0, 1, 2, 3 });
permutations.add(new int[] { 0, 1, 3, 2 });
permutations.add(new int[] { 0, 2, 1, 3 });
permutations.add(new int[] { 0, 2, 3, 1 });
permutations.add(new int[] { 0, 3, 1, 2 });
permutations.add(new int[] { 0, 3, 2, 1 });
permutations.add(new int[] { 1, 0, 2, 3 });
permutations.add(new int[] { 1, 0, 3, 2 });
permutations.add(new int[] { 1, 2, 0, 3 });
permutations.add(new int[] { 1, 2, 3, 0 });
permutations.add(new int[] { 1, 3, 0, 2 });
permutations.add(new int[] { 1, 3, 2, 0 });
permutations.add(new int[] { 2, 0, 1, 3 });
permutations.add(new int[] { 2, 0, 3, 1 });
permutations.add(new int[] { 2, 1, 0, 3 });
permutations.add(new int[] { 2, 1, 3, 0 });
permutations.add(new int[] { 2, 3, 0, 1 });
permutations.add(new int[] { 2, 3, 1, 0 });
permutations.add(new int[] { 3, 0, 1, 2 });
permutations.add(new int[] { 3, 0, 2, 1 });
permutations.add(new int[] { 3, 1, 0, 2 });
permutations.add(new int[] { 3, 1, 2, 0 });
permutations.add(new int[] { 3, 2, 0, 1 });
permutations.add(new int[] { 3, 2, 1, 0 });
for (int k = 0; k < 4; k++) {
for (int i = 0; i < N; i++) {
String str = f.readLine();
for (int j = 0; j < N; j++) {
pieces[k][i][j] = Integer.parseInt(str.substring(j, j + 1));
}
}
if (k != 3) {
f.readLine();
}
}
int res = Integer.MAX_VALUE;
for (int[] array : permutations) {
createBoard(array);
res = Math.min(res, check(board));
}
System.out.println(res);
}
public static void createBoard(int[] array) {
board = new int[2 * N][2 * N];
int[][] b0 = pieces[array[0]];
int[][] b1 = pieces[array[1]];
int[][] b2 = pieces[array[2]];
int[][] b3 = pieces[array[3]];
for (int i = 0; i < N; i++) {
for (int k = 0; k < N; k++) {
board[i][k] = b0[i][k];
board[i][k + N] = b1[i][k];
board[i + N][k] = b2[i][k];
board[i + N][k + N] = b3[i][k];
}
}
}
public static int check(int[][] board) {
int res1 = 0;
int res2 = 0;
for (int i = 0; i < 2 * N; i++) {
for (int k = 0; k < 2 * N; k++) {
if (board[i][k] != standard1[i][k]) {
res1++;
}
if (board[i][k] != standard2[i][k]) {
res2++;
}
}
}
return Math.min(res1, res2);
}
public static void printArray(int[] array) {
for (int i : array) {
System.out.print(i + " ");
}
System.out.println();
}
public static void printMatrix(int[][] matrix) {
for (int[] is : matrix) {
printArray(is);
}
}
} | Java | ["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"] | 1 second | ["1", "2"] | null | Java 8 | standard input | [
"implementation",
"bitmasks",
"brute force"
] | dc46c6cb6b4b9b5e7e6e5b4b7d034874 | The first line contains odd integer n (1ββ€βnββ€β100) β the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line. | 1,400 | Print one number β minimum number of squares Magnus should recolor to be able to obtain a valid chessboard. | standard output | |
PASSED | 03eed3291f350be7ff57ba1509f18d0e | train_003.jsonl | 1522850700 | Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak,βi,βj; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them. | 256 megabytes | import java.util.*;
public class Main {
static final int maxn = 110;
static final int dead = 0x7f7f7f7f;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int[] cout=new int[5];
int n=in.nextInt();
String temp;
for(int i=1;i<=4;i++){
for(int j=1;j<=n;j++) {
temp=in.next();
for(int k=0;k<=n-1;k++) {
if(temp.charAt(k)=='0'&&((j-1)*n+k+1)%2==1)
cout[i]++;
else if(temp.charAt(k)=='1'&&((j-1)*n+k+1)%2==0)
cout[i]++;
}
}
}
int mi=dead;
int sum=cout[1]+cout[2]+cout[3]+cout[4];
for(int i=1;i<4;i++) {
for(int j=i+1;j<=4;j++) {
mi=Math.min(sum-cout[i]-cout[j]+n*n-cout[i]+n*n-cout[j], mi);
}
}
System.out.println(mi);
}
} | Java | ["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"] | 1 second | ["1", "2"] | null | Java 8 | standard input | [
"implementation",
"bitmasks",
"brute force"
] | dc46c6cb6b4b9b5e7e6e5b4b7d034874 | The first line contains odd integer n (1ββ€βnββ€β100) β the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line. | 1,400 | Print one number β minimum number of squares Magnus should recolor to be able to obtain a valid chessboard. | standard output | |
PASSED | 770e53aa2e238c365c73d513d80269e7 | train_003.jsonl | 1522850700 | Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak,βi,βj; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them. | 256 megabytes | import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
FastReader fr =new FastReader();
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
int n = fr.nextInt();
int[][] a = new int[4][2];
for (int k = 0; k < 4; k ++){
boolean bol = true;
for (int i = 0; i < n; i ++){
String s = fr.next();
for (int j = 0; j < n; j ++){
if ((s.charAt(j) == '1')&&(bol)) a[k][0]++;
if ((s.charAt(j) == '0')&&(!bol)) a[k][0]++;
if ((s.charAt(j) == '1')&&(!bol)) a[k][1]++;
if ((s.charAt(j) == '0')&&(bol)) a[k][1]++;
bol = !bol;
}
}
}
int[] bred = new int[6];
bred[0] = a[0][0] + a[1][0] + a[2][1] + a[3][1];
bred[1] = a[0][0] + a[1][1] + a[2][0] + a[3][1];
bred[2] = a[0][0] + a[1][1] + a[2][1] + a[3][0];
bred[3] = a[0][1] + a[1][0] + a[2][1] + a[3][0];
bred[4] = a[0][1] + a[1][0] + a[2][0] + a[3][1];
bred[5] = a[0][1] + a[1][1] + a[2][0] + a[3][0];
Arrays.sort(bred);
out.print(bred[0]);
out.close();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"] | 1 second | ["1", "2"] | null | Java 8 | standard input | [
"implementation",
"bitmasks",
"brute force"
] | dc46c6cb6b4b9b5e7e6e5b4b7d034874 | The first line contains odd integer n (1ββ€βnββ€β100) β the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line. | 1,400 | Print one number β minimum number of squares Magnus should recolor to be able to obtain a valid chessboard. | standard output | |
PASSED | 44ff8616e65123add58c0416052b87f2 | train_003.jsonl | 1522850700 | Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak,βi,βj; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them. | 256 megabytes | import java.util.*;
import java.io.*;
public class hell {
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] argv){
FastReader s = new FastReader();
int n = s.nextInt();
int[][] grid1 = new int[n][n];
int[][] grid2 = new int[n][n];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if((i+j)%2==0)
{
grid1[i][j]=1;
}
else
{
grid2[i][j]=1;
}
}
}
int[] cnt1 = new int[4];
int[] cnt2 = new int[4];
for(int k=0;k<4;k++) {
for (int i = 0; i < n; i++) {
String c = s.next();
for (int j = 0; j < n; j++) {
int x = (int)(c.charAt(j)-'0');
if(x!=grid1[i][j])
cnt1[k]++;
if(x!=grid2[i][j])
cnt2[k]++;
}
}
}
int ans = 1000000000;
ans = Math.min(ans,cnt1[0]+cnt1[1]+cnt2[2]+cnt2[3]);
ans = Math.min(ans,cnt1[0]+cnt1[2]+cnt2[1]+cnt2[3]);
ans = Math.min(ans,cnt1[0]+cnt1[3]+cnt2[1]+cnt2[2]);
ans = Math.min(ans,cnt1[1]+cnt1[2]+cnt2[0]+cnt2[3]);
ans = Math.min(ans,cnt1[1]+cnt1[3]+cnt2[0]+cnt2[2]);
ans = Math.min(ans,cnt1[2]+cnt1[3]+cnt2[0]+cnt2[1]);
System.out.println(ans);
}
}
| Java | ["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"] | 1 second | ["1", "2"] | null | Java 8 | standard input | [
"implementation",
"bitmasks",
"brute force"
] | dc46c6cb6b4b9b5e7e6e5b4b7d034874 | The first line contains odd integer n (1ββ€βnββ€β100) β the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line. | 1,400 | Print one number β minimum number of squares Magnus should recolor to be able to obtain a valid chessboard. | standard output | |
PASSED | e115fb6cb5effc07733e8125a10c8e7f | train_003.jsonl | 1522850700 | Magnus decided to play a classic chess game. Though what he saw in his locker shocked him! His favourite chessboard got broken into 4 pieces, each of size n by n, n is always odd. And what's even worse, some squares were of wrong color. j-th square of the i-th row of k-th piece of the board has color ak,βi,βj; 1 being black and 0 being white. Now Magnus wants to change color of some squares in such a way that he recolors minimum number of squares and obtained pieces form a valid chessboard. Every square has its color different to each of the neightbouring by side squares in a valid board. Its size should be 2n by 2n. You are allowed to move pieces but not allowed to rotate or flip them. | 256 megabytes | import java.util.ArrayList;
import java.util.Scanner;
public class Codeforces {
public static void main(String[] args) {
TaskC Solver = new TaskC();
Solver.Solve();
}
private static class TaskC {
private void Solve() {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
Block blocks[] = new Block[4];
for (int i = 0; i < 4; i++) {
blocks[i] = new Block(n, i);
for (int j = 0; j < n; j++) {
String S = in.next();
for (int k = 0; k < n; k++)
blocks[i].field[j][k] = S.charAt(k) - '0';
}
}
System.out.println(Compute(blocks, n));
}
private static int Compute(Block blocks[], int n) {
ArrayList <String> opt = new ArrayList();
opt.add("1234");
opt.add("1243");
opt.add("1324");
opt.add("1342");
opt.add("1423");
opt.add("1432");
opt.add("2134");
opt.add("2143");
opt.add("2314");
opt.add("2341");
opt.add("2413");
opt.add("2431");
opt.add("3124");
opt.add("3142");
opt.add("3214");
opt.add("3241");
opt.add("3412");
opt.add("3421");
opt.add("4123");
opt.add("4132");
opt.add("4213");
opt.add("4231");
opt.add("4312");
opt.add("4321");
int min = 1000000000;
for (int i = 0; i < 24; i++) {
Block bl[] = new Block[4];
for (int j = 0; j < 4; j++)
bl[j] = blocks[opt.get(i).charAt(j) - '1'];
int result = Treatment(bl, n);
min = Math.min(min, result);
}
return min;
}
private static int Treatment(Block bl[], int n) {
int size = 2 * n;
int ar[][] = new int [size][size];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
ar[i][j] = bl[0].field[i][j];
for (int i = 0; i < n; i++)
for (int j = n; j < size; j++)
ar[i][j] = bl[1].field[i][j - n];
for (int i = n; i < size; i++)
for (int j = 0; j < n; j++)
ar[i][j] = bl[2].field[i - n][j];
for (int i = n; i < size; i++)
for (int j = n; j < size; j++)
ar[i][j] = bl[3].field[i - n][j - n];
int curColor1, curColor2, ans1 = 0, ans2 = 0;
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++) {
if ((i + j) % 2 == 0) {
curColor1 = 1;
curColor2 = 0;
}
else {
curColor1 = 0;
curColor2 = 1;
}
if (ar[i][j] != curColor1)
ans1++;
if (ar[i][j] != curColor2)
ans2++;
}
return Math.min(ans1, ans2);
}
private static class Block {
private int field[][], size;
private int num;
public Block(int size, int num) {
this.size = size;
this.num = num;
field = new int [size][size];
}
}
}
} | Java | ["1\n0\n\n0\n\n1\n\n0", "3\n101\n010\n101\n\n101\n000\n101\n\n010\n101\n011\n\n010\n101\n010"] | 1 second | ["1", "2"] | null | Java 8 | standard input | [
"implementation",
"bitmasks",
"brute force"
] | dc46c6cb6b4b9b5e7e6e5b4b7d034874 | The first line contains odd integer n (1ββ€βnββ€β100) β the size of all pieces of the board. Then 4 segments follow, each describes one piece of the board. Each consists of n lines of n characters; j-th one of i-th line is equal to 1 if the square is black initially and 0 otherwise. Segments are separated by an empty line. | 1,400 | Print one number β minimum number of squares Magnus should recolor to be able to obtain a valid chessboard. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.