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 | 2d9f7badda8b61d1558cf3dd4edacc3d | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes | import java.util.*;
public class Solution{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int q = sc.nextInt();
for(int i=0; i<q; i++){
sc.nextLine();
long a = sc.nextLong();
long b = sc.nextLong();
long n = sc.nextLong();
long s = sc.nextLong();
if(s%n > b){
System.out.println("No");
}
else{
if(a*n >= s - b){
System.out.println("Yes");
}
else{
System.out.println("No");
}
}
}
}
} | Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | c38e678051735f0aabd0114417d12b19 | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes |
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
long t = sc.nextLong();
for(long i=0;i<t;i++)
{
long a = sc.nextLong();
long b = sc.nextLong();
long n = sc.nextLong();
long s = sc.nextLong();
long sum = 0;
sum = (a*n)+b;
if(s <= sum)
{
if(s%n <= b)
{
System.out.println("Yes");
}
else
{
System.out.println("No");
}
}
else
{
System.out.println("No");
}
}
}
} | Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | 9516a8261df371cd818b2369553da96f | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.util.Map;
import java.util.HashMap;
import java.lang.Math;
public class s {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
for(int qw=0;qw<t;qw++)
{
long a=sc.nextLong();
long b=sc.nextLong();
long n=sc.nextLong();
long s=sc.nextLong();
long na=s/n<a?s/n:a;
s=s-(na*n);
if(s>=0 && s<=b){
System.out.println("YES");
}
else
{
System.out.println("NO");
}
}
}
}
| Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | 69f017f2cc87b9bc53d0e8b1f2b09950 | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int q=scanner.nextInt();
for (int i = 0; i <q ; i++) {
Long a=scanner.nextLong();
Long b=scanner.nextLong();
Long n=scanner.nextLong();
Long S=scanner.nextLong();
if(a*n+b<S) {System.out.println("NO");continue;}
else if(S%n>b){
System.out.println("NO");
continue;
}
System.out.println("YES");
}
}
}
| Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | 53f3835c4f7285ea2a094ad9e0621b7b | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes | import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
long t=sc.nextLong();
while (t-->0)
{
long ans=0;
long a=sc.nextLong();
long b=sc.nextLong();
long n=sc.nextLong();
long s=sc.nextLong();
ans=a*n+b;
if (ans<s)
System.out.println("No");
else
{
long x=s/n;
if (x>a)
x=a;
long left=s-(x*n);
if (left<=b)
System.out.println("Yes");
else
System.out.println("No");
}
}
}
}
| Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | 40206f47ad6011e138183a952ed6e299 | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes |
import java.util.ArrayList;
import java.util.Scanner;
public class TaskA {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<String> stringBuilder = new ArrayList<>();
String requestsCount = scanner.nextLine();
for (int i = 0; i < Integer.parseInt(requestsCount); i++) {
String s = scanner.nextLine();
stringBuilder.add(findAnswer(s));
}
for (String s : stringBuilder) {
System.out.println(s);
}
}
private static String findAnswer(String string) {
String[] arguments = string.split(" ");
int a = Integer.parseInt(arguments[0]);
int b = Integer.parseInt(arguments[1]);
int n = Integer.parseInt(arguments[2]);
int s = Integer.parseInt(arguments[3]);
int countA = s/n;
int countB = s % n;
if (countB>b){
//монет 1 не хватает
return "NO";
}
else if (a>=countA){
//монет А хватает
return "YES";
}
else if ((a*n+b)>=s){
//монет А не хватает, добираем 1
return "YES";
}
else {
return "NO";
}
}
}
| Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | e3539b6b0a8ff17626710a9af09b6772 | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes | /******************************************************************************
Online Java Compiler.
Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute it.
*******************************************************************************/
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int q=sc.nextInt();
for(int i=0;i<q;i++)
{
int a=sc.nextInt();
int b=sc.nextInt();
int n=sc.nextInt();
int S=sc.nextInt();
int x=S/n;
if(x>a)
{
x=a;
}
int y=S-(n*x);
if(x<=a && y<=b)
{
System.out.println("YES");
}
else
{
System.out.println("NO");
}
}
}
}
| Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | df9a8a2a803454d8b1206bf86f8659da | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes | // package july2020;
import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
public class cf_subs {
static FastReader scn = new FastReader();
static OutputStream out = new BufferedOutputStream(System.out);
// @SuppressWarnings("unchecked")
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
int tc =scn.nextInt();
// int tc =1;
Here:
while(tc-->0) {
int a=scn.nextInt(),b=scn.nextInt(),n=scn.nextInt(),s=scn.nextInt();
int mul = Math.min(a,s/n);
if(s-mul*n<=b) {
out.write("YES\n".getBytes());
}else {
out.write("NO\n".getBytes());
}
}
out.close();
}
static int lowerBound(int[] a, int x) {
int l = -1, r = a.length;
while (r - l > 1) {
int c = (l + r) / 2;
if (a[c] < x) {
//if (a[c] > x) {
l = c;
} else {
r = c;
}
}
return r;
}
static int upperBound(int[] a, int x) {
int l = -1, r = a.length;
while (r - l > 1) {
int c = (l + r) / 2;
if (a[c] <= x) {
l = c;
} else {
r = c;
}
}
return r;
}
static int lowerBound(long[] a, long x) {
int l = -1, r = a.length;
while (r - l > 1) {
int c = (l + r) / 2;
if (a[c] < x) {
l = c;
} else {
r = c;
}
}
return r;
}
static int upperBound(long[] a, long x) {
int l = -1, r = a.length;
while (r - l > 1) {
int c = (l + r) / 2;
if (a[c] <= x) {
l = c;
} else {
r = c;
}
}
return r;
}
static int lowerBound(double[] a, double x) {
int l = -1, r = a.length;
while (r - l > 1) {
int c = (l + r) / 2;
if (a[c] < x) {
l = c;
} else {
r = c;
}
}
return r;
}
static int upperBound(double[] a, double x) {
int l = -1, r = a.length;
while (r - l > 1) {
int c = (l + r) / 2;
if (a[c] <= x) {
l = c;
} else {
r = c;
}
}
return r;
}
static <T> int lowerBound(List<T> ls, T x) throws RuntimeException {
if (ls.size() == 0)
return -1;
if (ls.get(0) instanceof Integer) {
return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Integer) t1).compareTo((Integer) t2) >= 0 ? 1 : -1);
} else if (ls.get(0) instanceof Long) {
return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Long) t1).compareTo((Long) t2) >= 0 ? 1 : -1);
} else if (ls.get(0) instanceof Double) {
return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Double) t1).compareTo((Double) t2) >= 0 ? 1 : -1);
} else {
System.err.println(
String.format("%s:Arey Maa chudi padi hai", Thread.currentThread().getStackTrace()[1].getMethodName()));
throw new RuntimeException();
}
}
static <T> int upperBound(List<T> ls, T x) throws RuntimeException {
if (ls.size() == 0)
return -1;
if (ls.get(0) instanceof Integer) {
return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Integer) t1).compareTo((Integer) t2) > 0 ? 1 : -1);
} else if (ls.get(0) instanceof Long) {
return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Long) t1).compareTo((Long) t2) > 0 ? 1 : -1);
} else if (ls.get(0) instanceof Double) {
return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Double) t1).compareTo((Double) t2) > 0 ? 1 : -1);
} else {
System.err.println(
String.format("%s:Arey Maa chudi padi hai", Thread.currentThread().getStackTrace()[1].getMethodName()));
throw new RuntimeException();
}
}
static <T> int rupperBound(List<T> ls, T x) throws RuntimeException {
if (ls.size() == 0)
return -1;
if (ls.get(0) instanceof Integer) {
return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Integer) t1).compareTo((Integer) t2) < 0 ? 1 : -1);
} else if (ls.get(0) instanceof Long) {
return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Long) t1).compareTo((Long) t2) < 0 ? 1 : -1);
} else if (ls.get(0) instanceof Double) {
return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Double) t1).compareTo((Double) t2) < 0 ? 1 : -1);
} else {
System.err.println(
String.format("%s:Arey maa chudi padi hai", Thread.currentThread().getStackTrace()[1].getMethodName()));
throw new RuntimeException();
}
}
static <T> int rlowerBound(List<T> ls, T x) {
if (ls.size() == 0)
return -1;
if (ls.get(0) instanceof Integer) {
return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Integer) t1).compareTo((Integer) t2) <= 0 ? 1 : -1);
} else if (ls.get(0) instanceof Long) {
return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Long) t1).compareTo((Long) t2) <= 0 ? 1 : -1);
} else if (ls.get(0) instanceof Double) {
return ~Collections.binarySearch(ls, x, (t1, t2) -> ((Double) t1).compareTo((Double) t2) <= 0 ? 1 : -1);
} else {
System.err.println(
String.format("%s:Arey maa chudi padi hai", Thread.currentThread().getStackTrace()[1].getMethodName()));
throw new RuntimeException();
}
}
public static int[] merge(int[] one,int[] two){
int[] res = new int[one.length+two.length];
int i = 0;
int j = 0;
int k = 0;
while(i<one.length&&j<two.length){
if(one[i]<two[j]){
res[k] = one[i];
i++;
k++;
}
else{
res[k] = two[j];
j++;
k++;
}
}
if(i==one.length){
while(j<two.length){
res[k] = two[j];
j++;
k++;
}
}
else{
while(i<one.length){
res[k] = one[i];
k++;
i++;
}
}
return res;
}
public static int[] mergesort(int[] arr, int l, int r){
if(l==r){
int[] br = new int[1];
br[0] = arr[l];
return br;
}
int mid = (l+r)/2;
int[] fh = mergesort(arr,l,mid);
int[] sh = mergesort(arr,mid+1,r);
return merge(fh,sh);
}
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 | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | b4d28b6ad735f505d76af0d4e6356526 | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes | import java.util.*;
public class nfdngg
{public static void main(String args[])
{Scanner sc= new Scanner(System.in);
int z=sc.nextInt();
for(int i=0;i<z;i++)
{long t=0;
long a=sc.nextLong();long b=sc.nextLong();long n=sc.nextLong();long s=sc.nextLong();
long p=s/n;
if(p<a)
p=p;
if(p>=a)
p=a;
t=s-p*n;
if(b>=t)
System.out.println("YES");
if(b<t)
System.out.println("NO");
}}} | Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | e1ec5bd6fb627ceef1c113e6ebbf5849 | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class cd_payment{
public static void main(String[] args){
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try{
int test = Integer.parseInt(br.readLine());
PrintWriter pr = new PrintWriter(System.out,true);
for(int i=0;i<test;i++){
StringTokenizer st = new StringTokenizer(br.readLine());
long a = Integer.parseInt(st.nextToken());
long b = Integer.parseInt(st.nextToken());
long n = Integer.parseInt(st.nextToken());
long s = Integer.parseInt(st.nextToken());
if(s > ((a*n) + b)){
pr.print("NO");
pr.println();
continue;
}
if((s % n) > b){
pr.print("NO");
pr.println();
}
else{
pr.print("YES");
pr.println();
}
}
br.close();
pr.close();
//System.out.printf("%d %d %d %d", a, b, n, s);
//System.out.println();
}
catch(IOException e){
e.printStackTrace();
}
}
} | Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | ffee2bec7705c91add9c55903aa7a7e3 | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
int q, a, a1 , b, n, S, S1;
Scanner s = new Scanner(System.in);
q = s.nextInt();
while(q-->0){
a = s.nextInt();
b = s.nextInt();
n = s.nextInt();
S = s.nextInt();
a1 = S/n;
if(a1>a){
S1 = S - a*n;
if(S1>b)
System.out.println("NO");
else
System.out.println("YES");
}
else{
if((S-(a1*n))>b)
System.out.println("NO");
else
System.out.println("YES");
}
}
}
}
| Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | 798b65e860ce127d957a3cd08e439681 | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes | import java.io.*;
import java.util.StringTokenizer;
public class P1256A {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(in, out);
out.close();
}
static class Task {
public void solve(InputReader in, PrintWriter out) {
int q = in.nextInt();
for (int i = 0; i < q; i++) {
int a = in.nextInt(), b = in.nextInt(), n = in.nextInt(), S = in.nextInt();
//xn+y=S; 0<=x<=a & 0<=y<=b
// xn = S-y => n | S'=S-y
// Solution = (x, y), (x-1, y+n), (x-2, y+2n)
int S1 = S - (S % n);
int y = S - S1;
int x = S1 / n;
if (x > a) {
x = a;
y = S - a * n;
}
if (0 <= x && x <= a && y >= 0 && y <= b) {
out.println("Yes");
}else {
out.println("No");
}
}
}
}
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 String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) { arr[i] = nextInt(); }
return arr;
}
public long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) { arr[i] = nextLong(); }
return arr;
}
}
}
| Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | dcab68c2b4edbfac06ef2b771a966a41 | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes | //package practice;
import java.util.Scanner;
/*
* @author Parvez
*/
public class NewClass
{public static void main(String[] args)
{Scanner sc = new Scanner(System.in);
int n;
n=sc.nextInt();
for(int i=0;i<n;i++){
long a=sc.nextInt();
long b=sc.nextInt();
long c=sc.nextInt();
long d=sc.nextInt();
if(d%c<=b && a*c+b>=d){
System.out.println("YES");
}else
System.out.println("NO");
}
}}
| Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | b92f12c9a0573c9b988b2cdbc1647fdc | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes | /* Code by detestmaths*/
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.lang.System.*;
public class Main {
public static void main(String[] args) throws IOException {
// FastScanner in = new FastScanner("dance.in");
// PrintWriter out = new PrintWriter("dance.out");
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int t = in.nextInt();
while (t-- > 0) {
long a = in.nextLong();
long b = in.nextLong();
long n = in.nextLong();
long s = in.nextLong();
if(a * n + b < s || s % n > b)out.println("NO");
else out.println("YES");
}
out.close();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st = new StringTokenizer("");
public FastScanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public FastScanner(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
public String next() throws IOException {
if (!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 double nextDouble() throws IOException {
return Double.parseDouble(next());
}
} | Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | 2af64efb7b28b7b8230cf88e02b885ca | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes | import java.util.*;
public class problem {
public static void main(String[] args)throws Exception{
Scanner infile = new Scanner(System.in);
int N=infile.nextInt();
for(int i=1;i<=N;i++)
solution(infile);
infile.close();
}
static void solution(Scanner infile){
long a = (long) infile.nextInt();
long b=(long)infile.nextInt();
long n= (long)infile.nextInt();
long S=(long)infile.nextInt();
if(S%n<=b&&a*n+b>=S)
System.out.println("YES");
else
System.out.println("NO");
}
}
| Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | 7adcb7bdf5bb4a84930a51d2c20d530f | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes | import java.util.*;
public class MyClass {
public static void main(String args[]) {
Scanner sc= new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int a = sc.nextInt();
int b = sc.nextInt();
int n = sc.nextInt();
int s = sc.nextInt();
if(s/n <=a)
s=s%n;
else
s-=a*n;
System.out.println(s <= b ? "YES" : "NO");
}
}
} | Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | 228857ac9fe6e2d42173fcdd0fd2186a | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class Main{
public static void main(String[]args){
Scanner scanner=new Scanner(System.in);
int q=scanner.nextInt();
while (q!=0){
q--;
long a=scanner.nextLong();
long b=scanner.nextLong();
long n=scanner.nextLong();
long S=scanner.nextLong();
if (a*n>S){
if (n>S){
n=0;
} else {
long k=S/n;
n*=k;
}
} else {
n*=a;
}
if (n+b>=S){
System.out.println("yes");
} else {
System.out.println("no");
}
}
}
}
| Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | 3f2dd2261377e51465a3e59572ae665f | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class 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;
}
}
// SHIVAM GUPTA :
// ASCII = 48 + i ;
static Set<Character> set1 ; static Set<Character> set2 ;
public static boolean isPossibleTriangle(int a ,int b , int c)
{
if( a + b > c && c+b > a && a +c > b)
{
return true ;
}
return false ;
}
public static int gcd(int a, int b )
{
if(b==0)return a ;
else return gcd(b,a%b) ;
}
public static int lcm(int a, int b ,int c , int d )
{
int temp = lcm(a,b , c) ;
int ans = lcm(temp ,d ) ;
return ans ;
}
public static int lcm(int a, int b ,int c )
{
int temp = lcm(a,b) ;
int ans = lcm(temp ,c) ;
return ans ;
}
public static int lcm(int a , int b )
{
int gc = gcd(a,b);
return (a*b)/gc ;
}
public static void main (String[] args) throws java.lang.Exception
{
FastReader scn = new FastReader() ;
int t = scn.nextInt() ;
for(int i1 = 1; i1<= t ; i1++)
{
long a = scn.nextInt() ;long b = scn.nextInt() ;
long n = scn.nextInt() ;long s = scn.nextInt() ;
long temp = a* n + b ;
if((s%n <= b ) && (temp >= s))
{
out.println("yes") ;
}
else{
out.println("no") ;
}
}
out.flush() ;
}
}
| Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | 9ec493497f1a67e886adb5cad91f3ab3 | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class 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;
}
}
// SHIVAM GUPTA :
// ASCII = 48 + i ;
static Set<Character> set1 ; static Set<Character> set2 ;
public static boolean isPossibleTriangle(int a ,int b , int c)
{
if( a + b > c && c+b > a && a +c > b)
{
return true ;
}
return false ;
}
public static int gcd(int a, int b )
{
if(b==0)return a ;
else return gcd(b,a%b) ;
}
public static int lcm(int a, int b ,int c , int d )
{
int temp = lcm(a,b , c) ;
int ans = lcm(temp ,d ) ;
return ans ;
}
public static int lcm(int a, int b ,int c )
{
int temp = lcm(a,b) ;
int ans = lcm(temp ,c) ;
return ans ;
}
public static int lcm(int a , int b )
{
int gc = gcd(a,b);
return (a*b)/gc ;
}
public static void main (String[] args) throws java.lang.Exception
{
FastReader scn = new FastReader() ;
int t = scn.nextInt() ;
for(int i1 = 1; i1<= t ; i1++)
{
long a = scn.nextInt() ;long b = scn.nextInt() ;
long n = scn.nextInt() ;long s = scn.nextInt() ;
// long temp = a* n + b ;
if((s%n <= b ) && (a*n+b >= s))
{
out.println("yes") ;
}
else{
out.println("no") ;
}
}
out.flush() ;
}
}
| Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | 2c04a0ae6e0fe248e244ec12d3536ffa | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class paymentwithoutChange {
public static void main(String[] args) {
Scanner s = new Scanner (System.in);
int t = s.nextInt();
while (t-->0)
{
long a = s.nextLong() , b = s.nextLong() , n = s.nextLong() , S = s.nextLong();
if (a*n+b<S)
System.out.println("NO");
else
{
if ( S<=b||(S-n*a>=0 && S-n*a<=b) ||(S/n <=a && S%n <=b))
System.out.println("YES");
else
System.out.println("NO");
}
}
}
}
| Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | 9583dbaa55436b6815c91b71280f8871 | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes |
import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Cf131 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 Cf131(),"Main",1<<27).start();
}
static class Pair
{
int z;
int o;
Pair(int z,int o)
{
this.z=z;
this.o=o;
}
}
static class Edge implements Comparable<Edge>
{
int end, wght;
public Edge(int end, int wght)
{
this.end = end;
this.wght = wght;
}
public int compareTo(Edge edge)
{
return this.wght - edge.wght;
}
}
public void run()
{
InputReader sc = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int t = sc.nextInt();
while(t-->0){
long a = sc.nextLong();
long b = sc.nextLong();
long n = sc.nextLong();
long s = sc.nextLong();
long q = s/n;
long r = s%n;
if(q<=a){
if(r<=b)w.println("yes");
else w.println("no");
}
else{
long dif = (q-a)*n;
if(r+dif<=b)w.println("yes");
else w.println("no");
}
}
w.flush();
w.close();
}
} | Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | c5b59d900081f3f4bef2d75fff849d3c | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int rounds = sc.nextInt();
while (rounds != 0) {
long a = sc.nextLong(); //a * n
long b = sc.nextLong(); //1
long n = sc.nextLong();
long s = sc.nextLong();
if (s%n > b || a*n + b < s) {
System.out.println("NO");
} else {
System.out.println("YES");
}
rounds--;
}
}
} | Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | 1cbea1c34784f820b2f73f8c6b90f1e5 | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class CF_1256A {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int q = input.nextInt();
for(int i=0; i<q; i++){
long a = input.nextLong();
long b = input.nextLong();
long n = input.nextLong();
long S = input.nextLong();
long c = S%n;
if(c>b)System.out.println("No");
else{
long T = (a*n)+b;
if(T>=S)System.out.println("Yes");
else System.out.println("No");
}
}
}
}
| Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | c3f21a6a271ddffaf83378ce7b695946 | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = Integer.parseInt(input.nextLine());
String[] numbers = new String[4];
for(int i = 0;i < n;i++){
numbers = input.nextLine().split("\\s");
if(isPossible(Long.parseLong(numbers[0]),Long.parseLong(numbers[1]),Long.parseLong(numbers[2]),Long.parseLong(numbers[3]))){
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
public static boolean isPossible(long a,long b,long n,long S) {
if( S / n <= a && S % n <= b ) {
return true;
} else if ( a * n < S && (S - a * n) <= b ){
return true;
} else if ( b >= S ){
return true;
}
return false;
}
}
| Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | 096c2f4e01a41956c893991219d039b1 | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = Integer.parseInt(input.nextLine());
String[] numbers = new String[4];
for(int i = 0;i < n;i++){
numbers = input.nextLine().split("\\s");
if(isPossible(Long.parseLong(numbers[0]),Long.parseLong(numbers[1]),Long.parseLong(numbers[2]),Long.parseLong(numbers[3]))){
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
public static boolean isPossible(long a,long b,long n,long S) {
if( a * n + b < S ) {
return false;
} else if ( S % n > b ){
return false;
}
return true;
}
}
| Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | 88bc6230690d62398b5dc4be2d7050e1 | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 256 megabytes | import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int q = scanner.nextInt();
int a;
int b;
int n;
int S;
for (int i = 0; i < q; i++) {
a = scanner.nextInt();
b = scanner.nextInt();
n = scanner.nextInt();
S = scanner.nextInt();
System.out.println(solve(a, b, n, S) ? "YES" : "NO");
}
}
private static boolean solve(int a, int b, int n, int S) {
int mult = S / n;
if (mult > a) {
mult = a;
}
S -= mult * n;
if ( (S == 0) || (S <= b) ) {
return true;
} else {
return false;
}
}
}
| Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | 1dda0a6c6dd203ec6fbd39acd21fcbb5 | train_004.jsonl | 1572873300 | You have $$$a$$$ coins of value $$$n$$$ and $$$b$$$ coins of value $$$1$$$. You always pay in exact change, so you want to know if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ ($$$0 \le x \le a$$$) coins of value $$$n$$$ and $$$y$$$ ($$$0 \le y \le b$$$) coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$.You have to answer $$$q$$$ independent test cases. | 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){
String inp[]=br.readLine().split(" ");
long a=Integer.parseInt(inp[0]);
long b=Integer.parseInt(inp[1]);
long n=Integer.parseInt(inp[2]);
long s=Integer.parseInt(inp[3]);
if(a*n+b<s){
bw.write("No\n");
}
else if(a*n+b==s){
bw.write("Yes\n");
}
else{
long div=s/n;
if(div<=a && s%n<=b){
bw.write("Yes\n");
}
else if(div > a && div-a<=b ){
bw.write("Yes\n");
}
else{
bw.write("No\n");
}
}
t--;
}
bw.flush();
}
} | Java | ["4\n1 2 3 4\n1 2 3 6\n5 2 6 27\n3 3 5 18"] | 1 second | ["YES\nNO\nNO\nYES"] | null | Java 11 | standard input | [
"math"
] | e2434fd5f9d16d59e646b6e69e37684a | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 10^4$$$) — the number of test cases. Then $$$q$$$ test cases follow. The only line of the test case contains four integers $$$a$$$, $$$b$$$, $$$n$$$ and $$$S$$$ ($$$1 \le a, b, n, S \le 10^9$$$) — the number of coins of value $$$n$$$, the number of coins of value $$$1$$$, the value $$$n$$$ and the required total value. | 1,000 | For the $$$i$$$-th test case print the answer on it — YES (without quotes) if there exist such $$$x$$$ and $$$y$$$ that if you take $$$x$$$ coins of value $$$n$$$ and $$$y$$$ coins of value $$$1$$$, then the total value of taken coins will be $$$S$$$, and NO otherwise. You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES will all be recognized as positive answer). | standard output | |
PASSED | ed206c585b5dfb175049ce66644fe66a | train_004.jsonl | 1400914800 | Nanami is an expert at playing games. This day, Nanami's good friend Hajime invited her to watch a game of baseball. Unwilling as she was, she followed him to the stadium. But Nanami had no interest in the game, so she looked around to see if there was something that might interest her. That's when she saw the digital board at one end of the stadium.The digital board is n pixels in height and m pixels in width, every pixel is either light or dark. The pixels are described by its coordinate. The j-th pixel of the i-th line is pixel (i, j). The board displays messages by switching a combination of pixels to light, and the rest to dark. Nanami notices that the state of the pixels on the board changes from time to time. At certain times, certain pixels on the board may switch from light to dark, or from dark to light.Nanami wonders, what is the area of the biggest light block such that a specific pixel is on its side. A light block is a sub-rectangle of the board, in which all pixels are light. Pixel (i, j) belongs to a side of sub-rectangle with (x1, y1) and (x2, y2) as its upper-left and lower-right vertex if and only if it satisfies the logical condition: ((i = x1 or i = x2) and (y1 ≤ j ≤ y2)) or ((j = y1 or j = y2) and (x1 ≤ i ≤ x2)).Nanami has all the history of changing pixels, also she has some questions of the described type, can you answer them? | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class B {
int N, M;
int[][] t;
int[][][] closest0;
int hclosest0(int r, int c, int step) {
return step>0? closest0[r][c][1]: closest0[r][c][0];
}
int vclosest0(int r, int c, int step) {
return step>0? closest0[r][c][3]: closest0[r][c][2];
}
void init(int[][] t) {
this.t=t;
N=t.length; M=t[0].length;
closest0=new int[N][M][4];
for (int i=0; i<N; i++) {
update_row(i);
}
for (int i=0; i<M; i++) {
update_col(i);
}
}
void update_row(int r) {
int c0=-1;
for (int i=0; i<M; i++) {
if(t[r][i]==0) {
c0=i;
}
closest0[r][i][0]=c0;
}
c0=M;
for (int i=M-1; i>=0; i--) {
if(t[r][i]==0) {
c0=i;
}
closest0[r][i][1]=c0;
}
}
void update_col(int c) {
int c0=-1;
for (int i=0; i<N; i++) {
if(t[i][c]==0) {
c0=i;
}
closest0[i][c][2]=c0;
}
c0=N;
for (int i=N-1; i>=0; i--) {
if(t[i][c]==0) {
c0=i;
}
closest0[i][c][3]=c0;
}
}
void update(int r, int c) {
t[r][c]^=1;
update_row(r);
update_col(c);
}
void solve(int[][] t, int[][] q) {
init(t);
int[] row=new int[M], col=new int[N];
int[] min=new int[Math.max(N, M)];
for (int i=0; i<q.length; i++) {
int qr=q[i][1]-1;
int qc=q[i][2]-1;
if(q[i][0]==1) {
update(qr, qc);
} else {
int maxs=0;
for (int c=0; c<M; c++) {
row[c]=vclosest0(qr, c, 1)-qr;
}
maxs=Math.max(maxs, maxs(qc, row, min));
for (int c=0; c<M; c++) {
row[c]=qr-vclosest0(qr, c, -1);
}
maxs=Math.max(maxs, maxs(qc, row, min));
for (int r=0; r<N; r++) {
col[r]=hclosest0(r, qc, 1)-qc;
}
maxs=Math.max(maxs, maxs(qr, col, min));
for (int r=0; r<N; r++) {
col[r]=qc-hclosest0(r, qc, -1);
}
maxs=Math.max(maxs, maxs(qr, col, min));
System.out.println(maxs);
}
}
}
int maxs(int i, int[] a, int[] min) {
int lo=i, hi=lo, ret=0; min[hi-lo]=a[lo];
while(lo>0||hi+1<a.length) {
if((lo>0&&hi+1<a.length&&a[lo-1]>=a[hi+1])||hi+1==a.length) {
lo--;
min[hi-lo]=Math.min(min[hi-lo-1], a[lo]);
} else /*if(l>0&&r+1<M&&row[l-1]<row[r+1])*/ {
hi++;
min[hi-lo]=Math.min(min[hi-lo-1], a[hi]);
}
}
for (int j=0; j<a.length; j++) {
if(ret<min[j]*(j+1)) {
ret=min[j]*(j+1);
}
}
return ret;
}
static StringBuilder sb=new StringBuilder();
static void parse(String l, int[] here) {
sb.setLength(0);
int len=l.length(), j=0;
for (int i=0; i<len; i++) {
char c=l.charAt(i);
if(c==' ') {
here[j++]=Integer.parseInt(sb.toString());
sb.setLength(0);
} else {
sb.append(c);
}
}
if(sb.length()>0) {
here[j++]=Integer.parseInt(sb.toString());
}
}
static void run_stream(InputStream ins) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String[] nmq=br.readLine().split(" ");
int n=Integer.parseInt(nmq[0]);
int m=Integer.parseInt(nmq[1]);
int k=Integer.parseInt(nmq[2]);
int[][] t=new int[n][m];
for (int i=0; i<n; i++) {
parse(br.readLine(), t[i]);
}
int[][] q=new int[k][3];
for (int i=0; i<k; i++) {
parse(br.readLine(), q[i]);
}
new B().solve(t,q);
}
public static void main(String[] args) throws IOException {
run_stream(System.in);
}
}
| Java | ["3 4 5\n0 1 1 0\n1 0 0 1\n0 1 1 0\n2 2 2\n2 1 2\n1 2 2\n1 2 3\n2 2 2", "3 3 4\n1 1 1\n1 1 1\n1 1 1\n2 2 2\n1 2 2\n2 1 1\n2 2 1"] | 1 second | ["0\n2\n6", "6\n3\n3"] | NoteConsider the first sample.The first query specifies pixel (2, 2), which is dark itself, so there are no valid light blocks, thus the answer is 0.The second query specifies pixel (1, 2). The biggest light block is the block with (1, 2) as its upper-left vertex and (1, 3) as its lower-right vertex.The last query specifies pixel (2, 2), which became light in the third operation. The biggest light block is the block with (1, 2) as its upper-left vertex and (3, 3) as its lower-right vertex. | Java 7 | standard input | [
"dp",
"two pointers",
"dsu",
"implementation",
"divide and conquer"
] | 895288258973317696185910fca8e32e | The first line contains three space-separated integers n, m and q (1 ≤ n, m, q ≤ 1000) — the height and width of the digital board, and the number of operations. Then follow n lines, each line containing m space-separated integers. The j-th integer of the i-th line is ai, j — the initial state of pixel (i, j). If ai, j = 0, pixel (i, j) is initially dark. If ai, j = 1, pixel (i, j) is initially light. Then follow q lines, each line containing three space-separated integers op, x, and y (1 ≤ op ≤ 2; 1 ≤ x ≤ n; 1 ≤ y ≤ m), describing an operation. If op = 1, the pixel at (x, y) changes its state (from light to dark or from dark to light). If op = 2, Nanami queries the biggest light block with pixel (x, y) on its side. | 2,000 | For each query, print a single line containing one integer — the answer to Nanami's query. | standard output | |
PASSED | ed88bc732e44752680b2a71437a68cce | train_004.jsonl | 1308582000 | Today the North Pole hosts an Olympiad in a sport called... toy igloo skyscrapers' building!There are n walruses taking part in the contest. Each walrus is given a unique number from 1 to n. After start each walrus begins to build his own igloo skyscraper. Initially, at the moment of time equal to 0, the height of the skyscraper i-th walrus is equal to ai. Each minute the i-th walrus finishes building bi floors.The journalists that are reporting from the spot where the Olympiad is taking place, make q queries to the organizers. Each query is characterized by a group of three numbers li, ri, ti. The organizers respond to each query with a number x, such that:1. Number x lies on the interval from li to ri inclusive (li ≤ x ≤ ri).2. The skyscraper of the walrus number x possesses the maximum height among the skyscrapers of all walruses from the interval [li, ri] at the moment of time ti.For each journalists' query print the number of the walrus x that meets the above-given criteria. If there are several possible answers, print any of them. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.fill;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.sort;
public class Main {
public static void main(String[] args) throws IOException {
new Thread(null, new Runnable() {
public void run() {
try {
try {
if (new File("input.txt").exists())
System.setIn(new FileInputStream("input.txt"));
} catch (SecurityException e) {}
new Main().run();
} catch (IOException e) {
e.printStackTrace();
}
}
}, "1", 1L << 24).start();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
long INF = Long.MAX_VALUE / 7L;
int N;
int Q;
long[] a;
long[] b;
long[][] time;
int[][] index;
long[] tmpt;
int[] tmpi;
void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
N = nextInt();
Q = nextInt();
a = new long [N];
b = new long [N];
for (int i = 0; i < N; i++) {
a[i] = nextInt();
b[i] = nextInt();
}
/* build RMQ */
time = new long [2 * N][];
index = new int [2 * N][];
for (int i = 0; i < N; i++) {
time[N + i] = new long [] { 0L };
index[N + i] = new int [] { i };
}
tmpt = new long [2 * N];
tmpi = new int [2 * N];
for (int v = N - 1; v > 0; v--) {
int sz = 0;
int left = 2 * v;
int right = left + 1;
long[] lt = time[left];
long[] rt = time[right];
int[] li = index[left];
int[] ri = index[right];
int lsz = li.length;
int rsz = ri.length;
int lpnt = 0;
int rpnt = 0;
long ct = 0L;
while (ct < INF) {
int cli = li[lpnt];
int cri = ri[rpnt];
long lval = calc(cli, ct);
long rval = calc(cri, ct);
int nind = lval > rval || lval == rval && b[cli] > b[cri] ? cli : cri;
if (sz == 0 || tmpi[sz - 1] != nind) {
tmpt[sz] = ct;
tmpi[sz] = nind;
sz++;
}
long its = b[cli] == b[cri] ? INF : its(cli, cri); if (its <= ct) its = INF;
long ntl = lpnt == lsz - 1 ? INF : lt[lpnt + 1];
long ntr = rpnt == rsz - 1 ? INF : rt[rpnt + 1];
ct = min(min(ntl, ntr), its);
if (lpnt < lsz - 1 && ct == lt[lpnt + 1]) lpnt++;
if (rpnt < rsz - 1 && ct == rt[rpnt + 1]) rpnt++;
}
time[v] = Arrays.copyOf(tmpt, sz);
index[v] = Arrays.copyOf(tmpi, sz);
}
// for (int v = 1; v < 2 * N; v++) {
// System.out.println();
// System.out.println("v = " + v);
// System.out.println(Arrays.toString(time[v]));
// System.out.println(Arrays.toString(index[v]));
// }
for (int q = 0; q < Q; q++) {
int l = nextInt() - 1;
int r = nextInt() - 1;
long t = nextInt();
out.println(get(l, r, t) + 1);
}
out.close();
}
long its(int i, int j) {
return (long) ceil((a[i] - a[j]) / (double) (b[j] - b[i]));
}
long calc(int i, long t) {
return a[i] + t * b[i];
}
int get(int l, int r, long t) {
int ret = -1;
long max = -1L;
l += N;
r += N;
while (l <= r) {
if ((l & 1) == 1) {
int mi = get(l, t);
long lv = a[mi] + t * b[mi];
if (max < lv) {
max = lv;
ret = mi;
}
}
if ((r & 1) == 0) {
int mi = get(r, t);
long rv = a[mi] + t * b[mi];
if (max < rv) {
max = rv;
ret = mi;
}
}
l = (l + 1) >> 1;
r = (r - 1) >> 1;
}
return ret;
}
int get(int v, long t) {
int ind = binarySearch(time[v], t);
if (ind < 0) ind = -(ind + 1);
if (ind == time[v].length) ind--;
if (time[v][ind] > t) ind--;
return index[v][ind];
}
/***************************************************************
* Input
**************************************************************/
String nextToken() throws IOException {
while (!st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextLine() throws IOException {
st = new StringTokenizer("");
return in.readLine();
}
boolean EOF() throws IOException {
while (!st.hasMoreTokens()) {
String s = in.readLine();
if (s == null)
return true;
st = new StringTokenizer(s);
}
return false;
}
}
| Java | ["5 4\n4 1\n3 5\n6 2\n3 5\n6 5\n1 5 2\n1 3 5\n1 1 0\n1 5 0", "5 4\n6 1\n5 1\n2 5\n4 3\n6 1\n2 4 1\n3 4 5\n1 4 5\n1 2 0"] | 3 seconds | ["5\n2\n1\n5", "3\n3\n3\n1"] | null | Java 6 | standard input | [
"data structures",
"geometry"
] | b2434600256e4a1ff0c180d86512e0b2 | The first line contains numbers n and q (1 ≤ n, q ≤ 105). Next n lines contain pairs of numbers ai, bi (1 ≤ ai, bi ≤ 109). Then follow q queries i the following format li, ri, ti, one per each line (1 ≤ li ≤ ri ≤ n, 0 ≤ ti ≤ 106). All input numbers are integers. | 2,500 | For each journalists' query print the number of the walrus x that meets the criteria, given in the statement. Print one number per line. | standard output | |
PASSED | 3d4faa351dad0312b27bc930e6236539 | train_004.jsonl | 1294329600 | Autocomplete is a program function that enables inputting the text (in editors, command line shells, browsers etc.) completing the text by its inputted part. Vasya is busy working on a new browser called 'BERowser'. He happens to be working on the autocomplete function in the address line at this very moment. A list consisting of n last visited by the user pages and the inputted part s are known. Your task is to complete s to make it an address of one of the pages from the list. You have to find the lexicographically smallest address having a prefix s. | 256 megabytes | import java.util.Scanner;
public class Solution{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String s = sc.next(), str = "";
int n = sc.nextInt();
for(int i=0; i<n; i++){
String st = sc.next();
if(st.indexOf(s)==0 ){
if(str == "") str = st;
else if(str.compareTo(st)>0)
str = st;
}
}
System.out.print((str == "")? s : str);
}
} | Java | ["next\n2\nnextpermutation\nnextelement", "find\n4\nfind\nfindfirstof\nfindit\nfand", "find\n4\nfondfind\nfondfirstof\nfondit\nfand"] | 2 seconds | ["nextelement", "find", "find"] | null | Java 11 | standard input | [
"implementation"
] | 5ad16e23e96de111c4974551b859a5ff | The first line contains the s line which is the inputted part. The second line contains an integer n (1 ≤ n ≤ 100) which is the number of visited pages. Then follow n lines which are the visited pages, one on each line. All the lines have lengths of from 1 to 100 symbols inclusively and consist of lowercase Latin letters only. | 1,100 | If s is not the beginning of any of n addresses of the visited pages, print s. Otherwise, print the lexicographically minimal address of one of the visited pages starting from s. The lexicographical order is the order of words in a dictionary. The lexicographical comparison of lines is realized by the '<' operator in the modern programming languages. | standard output | |
PASSED | a8ed317334503d8de5b1373f8274c676 | train_004.jsonl | 1294329600 | Autocomplete is a program function that enables inputting the text (in editors, command line shells, browsers etc.) completing the text by its inputted part. Vasya is busy working on a new browser called 'BERowser'. He happens to be working on the autocomplete function in the address line at this very moment. A list consisting of n last visited by the user pages and the inputted part s are known. Your task is to complete s to make it an address of one of the pages from the list. You have to find the lexicographically smallest address having a prefix s. | 256 megabytes | import java.util.*;
public class S{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String s = in.next();
int n = in.nextInt();
String arr[] = new String[n];
for(int i = 0; i < n; i++)
arr[i] = in.next();
Arrays.sort(arr);
int len = s.length();
boolean bool = true;
for(int i = 0; i < n; i++){
int len0 = arr[i].length();
if(len0 >= len){
String str = arr[i].substring(0, len);
if(str.equals(s)){
System.out.print(arr[i]);
bool = false;
break;
}
}
}
if(bool){
System.out.print(s);
}
}
} | Java | ["next\n2\nnextpermutation\nnextelement", "find\n4\nfind\nfindfirstof\nfindit\nfand", "find\n4\nfondfind\nfondfirstof\nfondit\nfand"] | 2 seconds | ["nextelement", "find", "find"] | null | Java 11 | standard input | [
"implementation"
] | 5ad16e23e96de111c4974551b859a5ff | The first line contains the s line which is the inputted part. The second line contains an integer n (1 ≤ n ≤ 100) which is the number of visited pages. Then follow n lines which are the visited pages, one on each line. All the lines have lengths of from 1 to 100 symbols inclusively and consist of lowercase Latin letters only. | 1,100 | If s is not the beginning of any of n addresses of the visited pages, print s. Otherwise, print the lexicographically minimal address of one of the visited pages starting from s. The lexicographical order is the order of words in a dictionary. The lexicographical comparison of lines is realized by the '<' operator in the modern programming languages. | standard output | |
PASSED | d52c4a1e646089e9ae2b2ccc9c513bed | train_004.jsonl | 1294329600 | Autocomplete is a program function that enables inputting the text (in editors, command line shells, browsers etc.) completing the text by its inputted part. Vasya is busy working on a new browser called 'BERowser'. He happens to be working on the autocomplete function in the address line at this very moment. A list consisting of n last visited by the user pages and the inputted part s are known. Your task is to complete s to make it an address of one of the pages from the list. You have to find the lexicographically smallest address having a prefix s. | 256 megabytes | import java.util.*;
//warm-up
public class AutoComplete {
static void solve(){
Scanner sc = new Scanner(System.in);
String c = sc.next();
int NOC = sc.nextInt(), i = 0;
String[] a = new String[NOC];
while (NOC-->0) a[i++]=sc.next();
Arrays.sort(a);
for (String b : a) if(b.indexOf(c)==0) { c=b; break; }
System.out.println(c);
sc.close();
}
public static void main(String args[]) {
solve();
}
}
| Java | ["next\n2\nnextpermutation\nnextelement", "find\n4\nfind\nfindfirstof\nfindit\nfand", "find\n4\nfondfind\nfondfirstof\nfondit\nfand"] | 2 seconds | ["nextelement", "find", "find"] | null | Java 11 | standard input | [
"implementation"
] | 5ad16e23e96de111c4974551b859a5ff | The first line contains the s line which is the inputted part. The second line contains an integer n (1 ≤ n ≤ 100) which is the number of visited pages. Then follow n lines which are the visited pages, one on each line. All the lines have lengths of from 1 to 100 symbols inclusively and consist of lowercase Latin letters only. | 1,100 | If s is not the beginning of any of n addresses of the visited pages, print s. Otherwise, print the lexicographically minimal address of one of the visited pages starting from s. The lexicographical order is the order of words in a dictionary. The lexicographical comparison of lines is realized by the '<' operator in the modern programming languages. | standard output | |
PASSED | 8a042ae8912c686a1734c111e83c5510 | train_004.jsonl | 1294329600 | Autocomplete is a program function that enables inputting the text (in editors, command line shells, browsers etc.) completing the text by its inputted part. Vasya is busy working on a new browser called 'BERowser'. He happens to be working on the autocomplete function in the address line at this very moment. A list consisting of n last visited by the user pages and the inputted part s are known. Your task is to complete s to make it an address of one of the pages from the list. You have to find the lexicographically smallest address having a prefix s. | 256 megabytes | import java.io.PrintWriter;
import java.util.Scanner;
public class test {
public static void main(String[]args) {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
String s = sc.nextLine();
int n = sc.nextInt();
String res = null;
for(int i = 0; i<n ; i++) {
String word = sc.next();
if (word.startsWith(s)) {
if (res == null || res.compareTo(word) > 0) {
res = word;
}
}
}
if (res == null) {
res = s;
}
System.out.println(res);
}
}
| Java | ["next\n2\nnextpermutation\nnextelement", "find\n4\nfind\nfindfirstof\nfindit\nfand", "find\n4\nfondfind\nfondfirstof\nfondit\nfand"] | 2 seconds | ["nextelement", "find", "find"] | null | Java 11 | standard input | [
"implementation"
] | 5ad16e23e96de111c4974551b859a5ff | The first line contains the s line which is the inputted part. The second line contains an integer n (1 ≤ n ≤ 100) which is the number of visited pages. Then follow n lines which are the visited pages, one on each line. All the lines have lengths of from 1 to 100 symbols inclusively and consist of lowercase Latin letters only. | 1,100 | If s is not the beginning of any of n addresses of the visited pages, print s. Otherwise, print the lexicographically minimal address of one of the visited pages starting from s. The lexicographical order is the order of words in a dictionary. The lexicographical comparison of lines is realized by the '<' operator in the modern programming languages. | standard output | |
PASSED | b0bd3b5af004c1a275d80abb4a84e4d2 | train_004.jsonl | 1294329600 | Autocomplete is a program function that enables inputting the text (in editors, command line shells, browsers etc.) completing the text by its inputted part. Vasya is busy working on a new browser called 'BERowser'. He happens to be working on the autocomplete function in the address line at this very moment. A list consisting of n last visited by the user pages and the inputted part s are known. Your task is to complete s to make it an address of one of the pages from the list. You have to find the lexicographically smallest address having a prefix s. | 256 megabytes | import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
public class A {
static Scanner scan=new Scanner(System.in);
static int cnt=0;
static int M=(int)1e9+7;
static boolean ispresent(String sub,String s) {
String substring="";
for(int i=0;i<s.length();i++) {
if(substring.equals(sub)) {
return true;
}
else substring+=s.charAt(i);
}
if(substring.equals(sub))
return true;
return false;
}
static String minlex(String ar[]) {
String s=ar[0];
for(int i=1;i<ar.length;i++) {
if(ar[i]==null)
break;
if(s.compareTo(ar[i])>0)
s=ar[i];
}
return s;
}
public static void main(String[] args) throws IOException {
String sub=scan.next();
int n=scan.nextInt();
String []sar=new String[n];
int k=0;
for(int i=0;i<n;i++) {
String s=scan.next();
if(ispresent(sub, s))
sar[k++]=s;
}
if(minlex(sar)==null)
System.out.println(sub);
else
System.out.println(minlex(sar));
}
}
| Java | ["next\n2\nnextpermutation\nnextelement", "find\n4\nfind\nfindfirstof\nfindit\nfand", "find\n4\nfondfind\nfondfirstof\nfondit\nfand"] | 2 seconds | ["nextelement", "find", "find"] | null | Java 11 | standard input | [
"implementation"
] | 5ad16e23e96de111c4974551b859a5ff | The first line contains the s line which is the inputted part. The second line contains an integer n (1 ≤ n ≤ 100) which is the number of visited pages. Then follow n lines which are the visited pages, one on each line. All the lines have lengths of from 1 to 100 symbols inclusively and consist of lowercase Latin letters only. | 1,100 | If s is not the beginning of any of n addresses of the visited pages, print s. Otherwise, print the lexicographically minimal address of one of the visited pages starting from s. The lexicographical order is the order of words in a dictionary. The lexicographical comparison of lines is realized by the '<' operator in the modern programming languages. | standard output | |
PASSED | 9b0658450010e08528a9b62eae455441 | train_004.jsonl | 1294329600 | Autocomplete is a program function that enables inputting the text (in editors, command line shells, browsers etc.) completing the text by its inputted part. Vasya is busy working on a new browser called 'BERowser'. He happens to be working on the autocomplete function in the address line at this very moment. A list consisting of n last visited by the user pages and the inputted part s are known. Your task is to complete s to make it an address of one of the pages from the list. You have to find the lexicographically smallest address having a prefix s. | 256 megabytes | import java.util.*;
import java.math.*;
public class sdf{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.next();
int n = in.nextInt();
String[] ars = new String[n];
for(int i = 0; i < n; i++)
ars[i] = in.next();
for(int i = 0; i < n; i++)
if(str.equals(ars[i])){
System.out.println(str);
System.exit(0);
}
boolean unic = false;
for(int i = 0; i < n; i++)
if(ars[i].length() >= str.length() && ars[i].substring(0, str.length()).equals(str)){
unic = true;
break;
}
if(!unic){
System.out.println(str);
System.exit(0);
}
ArrayList<String> arr = new ArrayList<>();
for(int i = 0; i < n; i++)
if(ars[i].length() >= str.length() && ars[i].substring(0, str.length()).equals(str))
arr.add(ars[i]);
String[] res = new String[arr.size()];
for(int i = 0; i < res.length; i++)
res[i] = arr.get(i);
Arrays.sort(res);
System.out.println(res[0]);
}} | Java | ["next\n2\nnextpermutation\nnextelement", "find\n4\nfind\nfindfirstof\nfindit\nfand", "find\n4\nfondfind\nfondfirstof\nfondit\nfand"] | 2 seconds | ["nextelement", "find", "find"] | null | Java 11 | standard input | [
"implementation"
] | 5ad16e23e96de111c4974551b859a5ff | The first line contains the s line which is the inputted part. The second line contains an integer n (1 ≤ n ≤ 100) which is the number of visited pages. Then follow n lines which are the visited pages, one on each line. All the lines have lengths of from 1 to 100 symbols inclusively and consist of lowercase Latin letters only. | 1,100 | If s is not the beginning of any of n addresses of the visited pages, print s. Otherwise, print the lexicographically minimal address of one of the visited pages starting from s. The lexicographical order is the order of words in a dictionary. The lexicographical comparison of lines is realized by the '<' operator in the modern programming languages. | standard output | |
PASSED | 1a7ae0b3726589673e43aaa97826bcb9 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.StringTokenizer;
public class A
{
public static void main(String[] args) throws IOException
{
PrintWriter out = new PrintWriter(new File("output.txt"));
// PrintWriter out = new PrintWriter(System.out);
InputA in = new InputA();
int n = in.nextInt();
ArrayList<ArrayList<Integer>> L = new ArrayList<ArrayList<Integer>>(5001);
for(int i = 0 ; i < 5001 ; i++)
L.add(new ArrayList<Integer>());
for (int i = 1; i <= 2 * n; i++)
L.get(in.nextInt()).add(i);
boolean valid = true;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < L.size() && valid; i++)
{
if (L.get(i).size() % 2 == 0)
for (int j = 0; j + 1 < L.get(i).size(); j += 2)
sb.append(L.get(i).get(j) + " " + L.get(i).get(j + 1) + "\n");
else
valid = false;
}
if (!valid)
out.println(-1);
else
out.print(sb.toString());
out.close();
}
}
class InputA
{
BufferedReader bf;
StringTokenizer st;
public InputA() throws IOException
{
// bf = new BufferedReader(new InputStreamReader(System.in));
bf = new BufferedReader(new FileReader(new File("input.txt")));
st = new StringTokenizer(bf.readLine());
}
public String next() throws IOException
{
while (!st.hasMoreTokens() && bf.ready())
{
st = new StringTokenizer(bf.readLine());
}
return st.hasMoreTokens() ? st.nextToken() : null;
}
public boolean hasNext() throws IOException
{
while (!st.hasMoreTokens() && bf.ready())
{
st = new StringTokenizer(bf.readLine());
}
return st.hasMoreTokens();
}
public int nextInt() throws IOException
{
while (!st.hasMoreTokens() && bf.ready())
{
st = new StringTokenizer(bf.readLine());
}
return st.hasMoreTokens() ? new Integer(st.nextToken()) : 0;
}
public long nextLong() throws IOException
{
while (!st.hasMoreTokens() && bf.ready())
{
st = new StringTokenizer(bf.readLine());
}
return st.hasMoreTokens() ? new Long(st.nextToken()) : 0l;
}
}
| Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | 681126088d233a2cff92a958557a9c41 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Scanner;
import java.util.StringTokenizer;
public class A
{
public static void main(String[] args) throws IOException
{
PrintWriter out = new PrintWriter(new File("output.txt"));
// PrintWriter out = new PrintWriter(System.out);
// Scanner in = new Scanner(new File("input.txt"));
InputA in = new InputA();
int n = in.nextInt();
Hashtable<Integer, Integer> h = new Hashtable<Integer, Integer>();
Hashtable<Integer, Integer> h2 = new Hashtable<Integer, Integer>();
ArrayList<Integer> a = new ArrayList<Integer>();
ArrayList<Integer> b = new ArrayList<Integer>();
for(int i = 0 ; i < 2 * n ; i++)
{
int e = in.nextInt();
if(h.containsKey(e))
{
if(h.get(e) == 1){
h.put(e, 2);
a.add(h2.get(e));
b.add(i + 1);
}
else
{
h.put(e , 1);
h2.put(e, i + 1);
}
}
else{
h.put(e, 1);
h2.put(e , i + 1);
}
}
if(a.size() + b.size() != 2 * n)
{
out.println(-1);
}
else{
for(int i = 0 ; i < n ; i++)
{
out.println(a.get(i) + " " + b.get(i));
}
}
out.close();
}
}
class InputA
{
BufferedReader bf;
StringTokenizer st;
public InputA() throws IOException
{
// bf = new BufferedReader(new InputStreamReader(System.in));
bf = new BufferedReader(new FileReader(new File("input.txt")));
st = new StringTokenizer(bf.readLine());
}
public String next() throws IOException
{
while (!st.hasMoreTokens() && bf.ready())
{
st = new StringTokenizer(bf.readLine());
}
return st.hasMoreTokens() ? st.nextToken() : null;
}
public boolean hasNext() throws IOException
{
while (!st.hasMoreTokens() && bf.ready())
{
st = new StringTokenizer(bf.readLine());
}
return st.hasMoreTokens();
}
public int nextInt() throws IOException
{
while (!st.hasMoreTokens() && bf.ready())
{
st = new StringTokenizer(bf.readLine());
}
return st.hasMoreTokens() ? new Integer(st.nextToken()) : 0;
}
public long nextLong() throws IOException
{
while (!st.hasMoreTokens() && bf.ready())
{
st = new StringTokenizer(bf.readLine());
}
return st.hasMoreTokens() ? new Long(st.nextToken()) : 0l;
}
}
| Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | 36208ea214fe0dd3b511290b7f54d735 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.util.*;
import java.io.*;
public class search {
public static void main(String[] args) throws IOException {
BufferedReader rd=new BufferedReader(new FileReader(new File("input.txt")));
PrintWriter out= new PrintWriter(new FileWriter("output.txt"));
int n=Integer.parseInt(rd.readLine());
ArrayList<Integer>[] list = new ArrayList[5001];
for (int i = 0; i < list.length; i++) {
list[i]=new ArrayList<Integer>();
}
StringTokenizer tok;
tok=new StringTokenizer(rd.readLine());
for (int i = 0; i < 2*n; i++) {
int a=Integer.parseInt(tok.nextToken());
list[a].add(i+1);
}
for (int i = 0; i <= 5000; i++) {
if(list[i].size()%2==1) {out.println(-1); out.flush();return;}
}
for (int i = 0; i <= 5000; i++) {
if(list[i].size()!=0){
for (int j = 0; j < list[i].size(); j+=2) {
out.println(list[i].get(j)+" "+list[i].get(j+1));
}
}
}
out.flush();
}
static int [] days=new int []{31,28,31,30,31,30, 31,31 ,30, 31, 30, 31};
}
| Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | 1ca16a68e1dde554c7e3eeb1e4f1ab66 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*cf254a
* @author zulkan
*/
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import static java.lang.System.*;
import java.math.BigInteger;
import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.List;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
public class cf254a {
static BufferedReader br;
static Scanner sc;
static PrintWriter out;
public static void initA() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
//br = new BufferedReader(new FileReader("input.txt"));
sc = new Scanner(System.in);
//out = new PrintWriter("output.txt");
out = new PrintWriter(System.out);
} catch (Exception e) {
}
}
public static void initB() {
try {
br = new BufferedReader(new FileReader("input.txt"));
sc = new Scanner(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
}
}
public static String getString() {
try {
return br.readLine();
} catch (Exception e) {
}
return "";
}
public static Integer getInt() {
try {
return Integer.parseInt(br.readLine());
} catch (Exception e) {
}
return 0;
}
public static Integer[] getIntArr() {
try {
StringTokenizer temp = new StringTokenizer(br.readLine());
int n = temp.countTokens();
Integer temp2[] = new Integer[n];
for (int i = 0; i < n; i++) {
temp2[i] = Integer.parseInt(temp.nextToken());
}
return temp2;
} catch (Exception e) {
}
return null;
}
public static int getMax(Integer[] ar) {
int t = ar[0];
for (int i = 0; i < ar.length; i++) {
if (ar[i] > t) {
t = ar[i];
}
}
return t;
}
public static void print(Object a) {
out.println(a);
}
public static int nextInt() {
return sc.nextInt();
}
public static double nextDouble() {
return sc.nextDouble();
}
public static BigInteger getFact(long in) {
BigInteger ot = new BigInteger("1");
for (Integer i = 1; i <= in; i++) {
ot = ot.multiply(new BigInteger(i.toString()));
}
return ot;
}
public static String gbase(int a, int base) {
StringBuilder out = new StringBuilder();
int temp = a;
while (temp > 0) {
//out = temp % base + out;
out.insert(0, temp % base);
temp /= base;
}
return out.toString();
}
public static void main(String[] ar) {
initB();
int n = getInt() * 2;
Integer arr[] = getIntArr();
HashMap<Integer, ArrayList> data = new HashMap<Integer, ArrayList>();
for (int i = 0; i < n; i++) {
if (!data.containsKey(arr[i])) {
//print('x');
ArrayList temp = new ArrayList();
temp.add(i + 1);
data.put(arr[i], temp);
} else {
//print('w');
ArrayList temp = data.get(arr[i]);
temp.add(i + 1);
data.put(arr[i], temp);
}
}
String xx = "";
for (ArrayList temp : data.values()) {
if (temp.size() % 2 != 0) {
//print(temp.size() + " : " + temp);
print(-1);
out.flush();
return;
}
}
for (ArrayList temp : data.values()) {
for (int i = 0; i < temp.size(); i += 2) {
print(temp.get(i) + " " + temp.get(i + 1));
}
}
out.flush();
}
}
| Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | 2a64102fcdea514bba22d268b160fc61 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.util.*;
import java.io.*;
public class a {
public static void main(String[] args) throws Exception {
// Scanner sc = new Scanner(new BufferedReader(new FileReader("input.txt")));
// PrintWriter out = new PrintWriter(System.out, true);
// Scanner sc = new Scanner(new FileReader("input.txt"));
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
// int n = sc.nextInt();
int n = Integer.parseInt(br.readLine());
int[] first = new int[n];
int[] second = new int[n];
int[] last = new int[5001];
int j = 0;
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < 2 * n; ++i) {
int number = Integer.parseInt(st.nextToken());
if (last[number] == 0) {
last[number] = i + 1;
} else {
first[j] = last[number];
second[j++] = i + 1;
last[number] = 0;
}
}
if (j != n)
out.println(-1);
else {
for (int i = 0; i < n; ++i) {
out.println(first[i] + " " + second[i]);
}
}
out.close();
}
} | Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | 5d21972eb800c058417aea5b72ad31f4 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.util.*;
import java.io.*;
public class a {
public static void main(String[] args) throws Exception {
// Scanner sc = new Scanner(new BufferedReader(new FileReader("input.txt")));
// PrintWriter out = new PrintWriter(System.out, true);
// Scanner sc = new Scanner(new FileReader("input.txt"));
InputStream inputStream;
try {
inputStream = new FileInputStream("input.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
InputReader in = new InputReader(inputStream);
BufferedInputStream br = new BufferedInputStream(new FileInputStream("input.txt"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
// int n = sc.nextInt();
// int n = Integer.parseInt(br.readLine());
int n = in.readInt();
int[] first = new int[n];
int[] second = new int[n];
int[] last = new int[5001];
int j = 0;
// StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < 2 * n; ++i) {
int number = in.readInt();
if (last[number] == 0) {
last[number] = i + 1;
} else {
first[j] = last[number];
second[j++] = i + 1;
last[number] = 0;
}
}
if (j != n)
out.println(-1);
else {
for (int i = 0; i < n; ++i) {
out.println(first[i] + " " + second[i]);
}
}
out.close();
}
}
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 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);
}
} | Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | 3ab6f9ea7c3ca18edffad7fbd4118b95 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.FileInputStream;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;
public class Main {
public static void main(String[] args) {
InputStream inputStream;
try {
inputStream = new FileInputStream("input.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
OutputStream outputStream;
try {
outputStream = new FileOutputStream("output.txt");
} catch (IOException e) {
throw new RuntimeException(e);
}
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int count = in.readInt();
int[] first = new int[count];
int[] second = new int[count];
int[] last = new int[5001];
int j = 0;
for (int i = 0; i < 2 * count; i++) {
int number = in.readInt();
if (last[number] == 0)
last[number] = i + 1;
else {
first[j] = last[number];
second[j++] = i + 1;
last[number] = 0;
}
}
if (j != count)
out.printLine(-1);
else {
for (int i = 0; i < count; i++) {
out.printLine(first[i], second[i]);
}
}
}
}
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 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);
}
}
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();
}
} | Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | 85abf98b4734e520218953fd6a3433ca | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.util.*;
import java.io.*;
public class a {
public static void main(String[] args) throws Exception {
// Scanner sc = new Scanner(new BufferedReader(new FileReader("input.txt")));
// PrintWriter out = new PrintWriter(System.out, true);
// Scanner sc = new Scanner(new FileReader("input.txt"));
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")), true);
// int n = sc.nextInt();
int n = Integer.parseInt(br.readLine());
int[] first = new int[n];
int[] second = new int[n];
int[] last = new int[5001];
int j = 0;
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < 2 * n; ++i) {
int number = Integer.parseInt(st.nextToken());
if (last[number] == 0) {
last[number] = i + 1;
} else {
first[j] = last[number];
second[j++] = i + 1;
last[number] = 0;
}
}
if (j != n)
out.println(-1);
else {
for (int i = 0; i < n; ++i) {
out.println(first[i] + " " + second[i]);
}
}
}
} | Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | 30019286587b59385a815988b676e68e | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.util.*;
import java.io.*;
public class A
{
static PrintWriter output;
static int n;
public static void main(String[] main) throws IOException
{
long t = System.currentTimeMillis();
BufferedReader input = new BufferedReader(new FileReader(new File("input.txt")));
output = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
n = Integer.parseInt(input.readLine());
number[] numbers = new number[2 * n];
StringTokenizer line = new StringTokenizer(input.readLine());
int numPtr = 0;
while(line.hasMoreTokens())
numbers[numPtr] = new number(numPtr++, Integer.parseInt(line.nextToken()));
Arrays.sort(numbers);
for(int i = 1; i < 2 * n; i += 2)
if(numbers[i].x != numbers[i - 1].x)
{
output.println(-1);
output.close();
return;
}
for(int i = 1; i < 2 * n; i += 2)
output.println((numbers[i - 1].id + 1) + " " + (numbers[i].id + 1));
output.close();
System.out.println((System.currentTimeMillis() - t) / 1000.0);
}
}
class number implements Comparable<number>
{
int id, x;
public number(int id, int x)
{
this.id = id;
this.x = x;
}
public int compareTo(number n)
{
return x - n.x;
}
public String toString()
{
return "" + x;
}
} | Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | 695c0c6530cc975d1572cf129554cd23 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | //package Round_155;
import java.util.*;
import java.io.*;
public class a {
void solve() throws Exception {
int n = in.nextInt();
ArrayList<Integer> l[] = new ArrayList[5001];
for (int i=1; i<=5000; i++)
l[i] = new ArrayList<Integer>();
for (int i = 0; i<2*n; i++){
int x = in.nextInt();
l[x].add(i+1);
}
for (int i=1; i<=5000; i++)
if (l[i].size() % 2 == 1){
out.println(-1);
return;
}
int p =0;
for (int i = 1; i<=5000; i++){
if (l[i].size() == 0) continue;
p++;
for (int j = 0; j<l[i].size(); j+=2){
if (p == n)
out.print(l[i].get(j) + " " + l[i].get(j+1));
else
out.println(l[i].get(j) + " " + l[i].get(j+1));
}
}
}
String input = "input.txt";
String output = "output.txt";
FastScanner in;
PrintWriter out;
void run() {
try {
if (input.length() == 0) {
InputStreamReader ins = new InputStreamReader(System.in);
in = new FastScanner(new BufferedReader(ins));
} else {
FileReader f = new FileReader(input);
in = new FastScanner(new BufferedReader(f));
}
if (output.length() == 0) {
out = new PrintWriter(System.out);
} else
out = new PrintWriter(new File(output));
solve();
out.flush();
out.close();
} catch (Exception ex) {
ex.printStackTrace();
out.close();
}
}
public static void main(String args[]) {
new a().run();
}
class FastScanner {
BufferedReader bf;
StringTokenizer st;
FastScanner(BufferedReader bf) {
this.bf = bf;
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(bf.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
}
| Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | a91fbe9ad4accc33ede6aeadda8eb6e4 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | //package example;
import java.io.*;
import java.util.*;
public class Example {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (Exception e) {
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
public void run() throws Exception {
//in = new BufferedReader(new InputStreamReader(System.in));
//out = new PrintWriter(System.out);
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter(new FileWriter("output.txt"));
solve();
out.flush();
out.close();
in.close();
}
public void solve() throws Exception {
int n = nextInt();
int m = 5001;
ArrayDeque<Integer>[] c = new ArrayDeque[m];
for (int i = 0; i < m; i++) {
c[i] = new ArrayDeque<Integer>();
}
for (int i = 0; i < 2 * n; i++) {
c[nextInt()].add(i + 1);
}
boolean ok = true;
for (int i = 0; i < m; i++) {
if (c[i].size() % 2 == 1) {
ok = false;
break;
}
}
if (ok) {
for (int i = 0; i < m; i++) {
while (!c[i].isEmpty()) {
out.println(c[i].poll() + " " + c[i].poll());
}
}
} else {
out.println(-1);
}
}
public static void main(String[] args) throws Exception {
new Example().run();
}
}
| Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | 2731653d28e27b7bfa8124e241d6b4c7 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.io.*;
import java.util.*;
public class Example {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (Exception e) {
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
public void run() throws Exception {
//in = new BufferedReader(new InputStreamReader(System.in));
//out = new PrintWriter(System.out);
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter(new FileWriter("output.txt"));
solve();
out.flush();
out.close();
in.close();
}
public void solve() throws Exception {
int n = nextInt();
int m = 5001;
ArrayDeque<Integer>[] c = new ArrayDeque[m];
for (int i = 0; i < m; i++) {
c[i] = new ArrayDeque<Integer>();
}
for (int i = 0; i < 2 * n; i++) {
c[nextInt()].add(i + 1);
}
boolean ok = true;
for (int i = 0; i < m; i++) {
if (c[i].size() % 2 == 1) {
ok = false;
break;
}
}
if (ok) {
for (int i = 0; i < m; i++) {
while (!c[i].isEmpty()) {
out.println(c[i].poll() + " " + c[i].poll());
}
}
} else {
out.println(-1);
}
}
public static void main(String[] args) throws Exception {
new Example().run();
}
} | Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | 1aa4abee761fe0e820436df73aef6c4b | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.util.*;
import java.io.*;
public class A {
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream in) {
try {
br = new BufferedReader(new InputStreamReader(in));
} catch (Exception e) {
e.printStackTrace();
}
}
public FastScanner(String in) {
try {
br = new BufferedReader(new FileReader(in));
} catch (Exception e) {
e.printStackTrace();
}
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
FastScanner in;
PrintWriter out;
void run() {
try {
in = new FastScanner("input.txt");
out = new PrintWriter("output.txt");
} catch (Exception e) {
e.printStackTrace();
}
solve();
out.close();
}
void solve() {
int n = in.nextInt();
n *= 2;
Map<Integer, List<Integer>> m = new HashMap<Integer, List<Integer>>();
for (int i = 0; i < n; ++i) {
int a = in.nextInt();
if (!m.containsKey(a)) {
m.put(a, new ArrayList<Integer>());
}
m.get(a).add(i + 1);
}
for (int a : m.keySet()) {
if (m.get(a).size() % 2 != 0) {
out.println(-1);
return;
}
}
for (int a : m.keySet()) {
List<Integer> list = m.get(a);
for (int i = 0; i < list.size(); i += 2) {
out.print(list.get(i));
out.print(" ");
out.println(list.get(i + 1));
}
}
}
public static void main(String[] args) {
new A().run();
}
} | Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | c9e3f1eaeff902716a1e04641b19f3f3 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public Integer nextInt(String s) {
return Integer.valueOf(s);
}
private int N, A[] = new int[5001];
private LinkedList[] list = new LinkedList[5001];
public long max(long a, long b) {
return (a > b) ? a : b;
}
public boolean check() {
for (int i = 1; i <= 5000; i++) {
if (A[i] % 2 > 0)
return false;
}
return true;
}
public void run() {
try {
for (int i = 1; i <= 5000; i++)
list[i] = new LinkedList<Integer>();
BufferedReader bf = new BufferedReader(new FileReader("input.txt"));
PrintWriter out = new PrintWriter("output.txt");
// BufferedReader bf = new BufferedReader(new InputStreamReader(
// System.in));
N = nextInt(bf.readLine());
N *= 2;
StringTokenizer st = new StringTokenizer(bf.readLine());
int sum = 0;
StringBuilder S[] = new StringBuilder[N + 1];
int idx = 1;
for (int i = 1; i <= N; i++) {
int f = nextInt(st.nextToken());
if (A[f] != 0) {
S[idx++] = new StringBuilder(A[f] + " " + i);
A[f] = 0;
sum--;
} else {
sum++;
A[f] = i;
}
}
if (sum != 0)
out.println(-1);
else {
for (int i = 1; i < idx; i++)
out.println(S[i]);
}
out.flush();
out.close();
} catch (IOException e) {
}
}
public static void main(String args[]) {
new Main().run();
}
}
| Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | 6a19a56fd7ef7fbba262ad9364c8d348 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.io.*;
import java.util.*;
public class cardsnum {
public static void main(String[] args) throws Exception {
BufferedReader r = new BufferedReader(new FileReader("input.txt"));
BufferedWriter w = new BufferedWriter(new FileWriter("output.txt"));
List<List<Integer>> list = new ArrayList<List<Integer>>();
for (int i = 0; i < 5000; i++) list.add(new ArrayList<Integer>());
int n = Integer.parseInt(r.readLine());
StringTokenizer st = new StringTokenizer(r.readLine());
for (int i = 0; i < 2 * n; i++) {
int num = Integer.parseInt(st.nextToken());
list.get(num - 1).add(i + 1);
}
for (int i = 0; i < 5000; i++) {
if (list.get(i).size() % 2 != 0) {
w.write("-1\n"); w.close(); System.exit(0);
}
}
for (int i = 0; i < 5000; i++) {
if (list.get(i).size() > 0) {
for (int k = 0; k < list.get(i).size() - 1; k += 2) {
w.write("" + list.get(i).get(k) + " " + list.get(i).get(k + 1) + "\n");
}
}
}
w.close();
System.exit(0);
}
}
| Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | 8b1f23458d7db0d9b01edd529001169e | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class cf254a {
public static void main(String[] args) throws Exception {
FastScanner in = new FastScanner(new FileInputStream("input.txt"));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.txt"))));
int n = in.nextInt();
int MAX = 5010;
Queue<Integer>[] v = new LinkedList[MAX];
for(int i=0; i<MAX; i++)
v[i] = new LinkedList<Integer>();
for(int i=0; i<2*n; i++) {
v[in.nextInt()].add(i+1);
}
boolean ok = true;
for(Queue<Integer> x : v)
if(x.size() % 2 == 1)
ok = false;
if(!ok) out.println("-1");
else for(Queue<Integer> x : v)
while(x.size() > 0)
out.println(x.poll() + " "+ x.poll());
out.close();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
scanLine();
}
public void scanLine() {
try {
st = new StringTokenizer(br.readLine().trim());
} catch(Exception e) {
throw new RuntimeException(e.getMessage());
}
}
public int numTokens() {
if(!st.hasMoreTokens()) {
scanLine();
return numTokens();
}
return st.countTokens();
}
public String next() {
if(!st.hasMoreTokens()) {
scanLine();
return next();
}
return st.nextToken();
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | 115988eeccd73b61b4960084b9f2f673 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.ArrayList;
public class Main {
static class Assert {
static void check(boolean e) {
if (!e) {
throw new Error();
}
}
}
class Scanner {
StreamTokenizer in;
Scanner(InputStream is) {
in = new StreamTokenizer(new InputStreamReader(is));
in.resetSyntax();
in.whitespaceChars(0, 32);
in.wordChars(33, 255);
}
String next() {
try {
in.nextToken();
Assert.check(in.ttype == in.TT_WORD);
return in.sval;
} catch (IOException e) {
return "#";
}
}
int nextInt() {
return Integer.parseInt(next());
}
}
public static void main(String[] args) {
new Main().run();
}
Scanner in;
PrintWriter out;
void run() {
try {
in = new Scanner(new FileInputStream("input.txt"));
out = new PrintWriter("output.txt");
} catch (IOException e) {
throw new Error(e);
}
try {
solve();
} finally {
out.close();
}
}
class Point {
int number;
int index;
Point(int n, int i) {
number = n;
index = i;
}
}
void solve() {
int n = in.nextInt();
int[] b = new int[5001];
ArrayList<Point> a = new ArrayList<Point>();
for (int i = 0; i < 2 * n; i++) {
int curNumber = in.nextInt();
if (b[curNumber] != 0) {
a.add(new Point(i + 1, b[curNumber]));
b[curNumber] = 0;
} else {
b[curNumber] = i + 1;
}
}
if (a.size() != n) {
out.println(-1);
return;
}
for (int i = 0; i < a.size(); i++) {
out.println(a.get(i).index + " " + a.get(i).number);
}
}
} | Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | 15edea20cf87e0e82386b9a4e034f6a4 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Vector;
public class A {
/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(System.out);
in=new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
out=new PrintWriter(new FileOutputStream("output.txt"));
int n=Integer.parseInt(in.readLine());
String[] inp=in.readLine().split(" ");
Vector<Vector<Integer>> mas=new Vector<Vector<Integer>>();
for(int i=0; i<5001; i++){
mas.add(new Vector<Integer>());
}
for(int i=0; i<n*2; i++){
mas.get(Integer.parseInt(inp[i])).add(i+1);
}
boolean check=true;
for(int i=1; i<5001; i++){
if(mas.get(i).size()%2==1){
check=false;
break;
}
}
if(!check){
out.println(-1);
}
else{
for(int i=1; i<5001; i++){
for(int j=0; j<mas.get(i).size(); j+=2){
out.println(mas.get(i).get(j)+" "+mas.get(i).get(j+1));
}
}
}
out.close();
}
} | Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | 1bea4af4d619889b7fda55884c73ed82 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Vector;
public class A {
/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(System.out);
in=new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
out=new PrintWriter(new FileOutputStream("output.txt"));
int n=Integer.parseInt(in.readLine());
String[] inp=in.readLine().split(" ");
Vector<Vector<Integer>> mas=new Vector<Vector<Integer>>(5001);
for(int i=0; i<5001; i++){
mas.add(new Vector<Integer>());
}
for(int i=0; i<n*2; i++){
mas.get(Integer.parseInt(inp[i])).add(i+1);
}
boolean check=true;
for(int i=1; i<5001; i++){
if(mas.get(i).size()%2==1){
check=false;
break;
}
}
if(!check){
out.println(-1);
}
else{
for(int i=1; i<5001; i++){
for(int j=0; j<mas.get(i).size(); j+=2){
out.print(mas.get(i).get(j));
out.print(" ");
out.println(mas.get(i).get(j+1));
}
}
}
out.close();
}
} | Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | 0fd715c8bc4a8687eb6e993fcb49149b | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
public class A {
/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(System.out);
in=new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
out=new PrintWriter(new FileOutputStream("output.txt"));
int n=Integer.parseInt(in.readLine());
String[] inp=in.readLine().split(" ");
List<ArrayList<Integer>> mas = new ArrayList<ArrayList<Integer>>(5001);
for(int i=0; i<5001; i++){
mas.add(new ArrayList<Integer>());
}
for(int i=0; i<n*2; i++){
mas.get(Integer.parseInt(inp[i])).add(i+1);
}
boolean check=true;
for(int i=1; i<5001; i++){
if(mas.get(i).size()%2==1){
check=false;
break;
}
}
if(!check){
out.println(-1);
}
else{
for(int i=1; i<5001; i++){
for(int j=0; j<mas.get(i).size(); j+=2){
out.println(mas.get(i).get(j)+" "+mas.get(i).get(j+1));
}
}
}
out.close();
}
}
| Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | 62829ad0e8e1bb6fd04e71f1a168b54a | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Vector;
public class A {
/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(System.out);
in=new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
out=new PrintWriter(new FileOutputStream("output.txt"));
int n=Integer.parseInt(in.readLine());
String[] inp=in.readLine().split(" ");
Vector<Vector<Integer>> mas=new Vector<Vector<Integer>>(5001);
for(int i=0; i<5001; i++){
mas.add(new Vector<Integer>());
}
for(int i=0; i<n*2; i++){
mas.get(Integer.parseInt(inp[i])).add(i+1);
}
boolean check=true;
for(int i=1; i<5001; i++){
if(mas.get(i).size()%2==1){
check=false;
break;
}
}
if(!check){
out.println(-1);
}
else{
for(int i=1; i<5001; i++){
for(int j=0; j<mas.get(i).size(); j+=2){
out.println(mas.get(i).get(j)+" "+mas.get(i).get(j+1));
}
}
}
out.close();
}
}
| Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | e229a49b25612aa46215505771a179f6 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.awt.Point;
import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import org.omg.PortableInterceptor.INACTIVE;
import static java.lang.Math.*;
public class Start {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
public static void main(String[] args) {
new Start().run();
// Sworn to fight and die
}
public static void mergeSort(int[] a) {
mergeSort(a, 0, a.length - 1);
}
private static void mergeSort(int[] a, int levtIndex, int rightIndex) {
final int MAGIC_VALUE = 50;
if (levtIndex < rightIndex) {
if (rightIndex - levtIndex <= MAGIC_VALUE) {
insertionSort(a, levtIndex, rightIndex);
} else {
int middleIndex = (levtIndex + rightIndex) / 2;
mergeSort(a, levtIndex, middleIndex);
mergeSort(a, middleIndex + 1, rightIndex);
merge(a, levtIndex, middleIndex, rightIndex);
}
}
}
private static void merge(int[] a, int levtIndex, int middleIndex,
int rightIndex) {
int length1 = middleIndex - levtIndex + 1;
int length2 = rightIndex - middleIndex;
int[] levtArray = new int[length1];
int[] rightArray = new int[length2];
System.arraycopy(a, levtIndex, levtArray, 0, length1);
System.arraycopy(a, middleIndex + 1, rightArray, 0, length2);
for (int k = levtIndex, i = 0, j = 0; k <= rightIndex; k++) {
if (i == length1) {
a[k] = rightArray[j++];
} else if (j == length2) {
a[k] = levtArray[i++];
} else {
a[k] = levtArray[i] <= rightArray[j] ? levtArray[i++]
: rightArray[j++];
}
}
}
private static void insertionSort(int[] a, int levtIndex, int rightIndex) {
for (int i = levtIndex + 1; i <= rightIndex; i++) {
int current = a[i];
int j = i - 1;
while (j >= levtIndex && a[j] > current) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = current;
}
}
public void run() {
try {
long t1 = System.currentTimeMillis();
init();
solve();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = " + (t2 - t1));
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(-1);
}
}
class LOL implements Comparable<LOL> {
int x;
int y;
public LOL(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(LOL o) {
return x - o.x; // ---->
// return o.x - x; // <----
// return o.y-y;
}
}
public void solve() throws IOException {
int n = readInt();
n = 2*n;
// LOL [] ololo = new LOL[n];
int t = 5001;
int [] fuu = new int [t];
ArrayList<Integer>[] shiii = new ArrayList[t];
for (int i = 0; i < t; i++){
shiii[i] = new ArrayList<Integer>();
}
for (int i =0; i < n; i++){
int x = readInt();
shiii[x].add(i+1);
// ololo[i] = new LOL(x, i+1);
}
for (int i = 0; i < t; i++){
if (!shiii[i].isEmpty()&& shiii[i].size() % 2 !=0){
out.print(-1);
return;
}
}
for (int i =0; i < t; i++){
int k = 1;
for (Integer ololo : shiii[i]){
if (k % 2 ==0){
out.println(ololo);
}
else
out.print(ololo + " ");
k++;
}
}
// Arrays.sort(ololo);
// ArrayList<Integer> ans = new ArrayList<Integer>();
// for (int i = 0; i < n-1; i++ ){
// if (ololo[i].x == ololo[i+1].x){
// ans.add(ololo[i].y);
// ans.add(ololo[i+1].y);
//
// // out.println(ololo[i].y + " "+ololo[i+1].y );
// i++;
// }
// else {
// out.print(-1);
// return;
// }
// }
// for (int i = 0; i < ans.size()-1; i++){
// out.println(ans.get(i) + " " + ans.get(i+1));
// i++;
// }
}
}
| Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | 816371593975930347c639bacea8e220 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.awt.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
/*
br = new BufferedReader(new FileReader("input.txt"));
pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
*/
public class Main {
private static BufferedReader br;
private static StringTokenizer st;
private static PrintWriter pw;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new FileReader("input.txt"));
pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
LinkedList<Integer>[] list = new LinkedList[5000];
for(int i = 0; i < list.length; i++)
list[i] = new LinkedList<Integer>();
int n = readInt();
for(int i = 1; i <= 2*n; i++) {
list[readInt()-1].add(i);
}
boolean win = true;
for(LinkedList<Integer> out: list) {
if(out.size()%2==1) {
win = false;
break;
}
}
if(!win) {
pw.println(-1);
}
else {
for(LinkedList<Integer> out: list) {
while(!out.isEmpty()) {
pw.println(out.removeFirst() + " " + out.removeFirst());
}
}
}
pw.close();
}
public static void loadArray(int[] in) throws IOException {
for(int i = 0; i < in.length; i++)
in[i] = readInt();
}
private static long readLong() throws IOException {
return Long.parseLong(nextToken());
}
private static double readDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private static int readInt() throws IOException {
return Integer.parseInt(nextToken());
}
private static String nextToken() throws IOException {
while(st == null || !st.hasMoreTokens()) {
if(!br.ready()) {
pw.close();
System.exit(0);
}
st = new StringTokenizer(br.readLine().trim());
}
return st.nextToken();
}
} | Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | af5308e3694bf690acf0c119d0c187f5 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class CardsWithNumbers {
public static void main(String[] args) throws IOException {
// InputReader r = new InputReader(System.in);
InputReader r=new InputReader("input.txt");
PrintWriter out=new PrintWriter(new FileWriter("output.txt"));
int n = r.nextInt();
int[] arr = new int[2 * n];
ArrayList<Integer>[] count = new ArrayList[5010];
for (int i = 0; i < count.length; i++) {
count[i] = new ArrayList<Integer>();
}
for (int i = 0; i < 2 * n; i++) {
arr[i] = r.nextInt();
count[arr[i]].add(i + 1);
}
for (int i = 0; i < 5010; i++)
if (count[i].size() % 2 != 0) {
out.println(-1);
out.close();
return;
}
for (int i = 0; i < 5010; i++) {
int k = 0;
for (int j : count[i]) {
if (k == 0) {
out.print(j);
k = 1;
} else if (k == 1) {
k = 0;
out.println(" " + j);
}
}
}
out.close();
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public InputReader(String f) {
try {
reader = new BufferedReader(new FileReader(f));
tokenizer = null;
} catch (Exception e) {
}
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 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 | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | 08b1c22ce7163a35e55a9471a1dabe5c | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main{
BufferedReader in;
StringTokenizer str = null;
private String next() throws Exception{
if(str == null || !str.hasMoreElements())
str = new StringTokenizer(in.readLine());
return str.nextToken();
}
private int nextInt() throws Exception{
return Integer.parseInt(next());
}
public void run() throws Exception{
in = new BufferedReader(new FileReader("input.txt"));
PrintWriter out = new PrintWriter(new File("output.txt"));
int n = nextInt();
pair []p = new pair[2*n];
int c[] = new int[5001];
for(int i=0;i<2*n;i++){
int x = nextInt();
c[x]++;
p[i] = new pair(x, i+1);
}
for(int i=0;i<c.length;i++){
if (c[i] % 2 == 1){
out.println(-1);
out.close();
return;
}
}
Arrays.sort(p);
for(int i=0;i<2*n;i+=2){
out.println(p[i].idx + " " + p[i+1].idx);
}
out.close();
}
public static void main(String args[]) throws Exception{
new Main().run();
}
}
class pair implements Comparable<pair>{
public int idx;
public int val;
public pair(int val, int idx){
this.idx = idx;
this.val = val;
}
public int compareTo(pair p){
if (this.val < p.val) return -1;
return 1;
}
} | Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | cb7b0306f6bb531712e9a9228ff3e4b5 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;
public class CardsWithNumbers {
public static void main(String[] args) throws IOException {
BufferedWriter w = new BufferedWriter( new FileWriter("output.txt"));
BufferedReader r = new BufferedReader( new FileReader("input.txt"));
int n = Integer.parseInt(r.readLine());
StringTokenizer st = new StringTokenizer(r.readLine());
ArrayList<ArrayList<Integer>> l = new ArrayList<ArrayList<Integer>>(5001);
for(int i=0;i<=5000;i++) l.add(new ArrayList<Integer>());
for(int i=1;i<=2*n;i++) l.get(Integer.parseInt(st.nextToken())).add(i);
int ok = 1;
for(int i=1;i<=5000;i++)
if(l.get(i).size()%2==1){
ok = 0;
break;
}
if(ok==0) w.append(-1+"\n");
else{
for(int i=1;i<=5000;i++)
for(int j=0;j<l.get(i).size();j+=2)
w.append(l.get(i).get(j)+" "+l.get(i).get(j+1)+"\n");
}
w.close();
r.close();
}
} | Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | 61c2299d520daa05fc3987061b2ac1a1 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class A {
static StringTokenizer st;
static BufferedReader in;
static PrintWriter pw;
public static void main(String[] args) throws IOException {
in = new BufferedReader(new FileReader("input.txt"));
pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
int n = nextInt();
ArrayList<Integer>[]L = new ArrayList[5001];
for (int i = 1; i <= 5000; i++) {
L[i] = new ArrayList<Integer>();
}
for (int i = 1; i <= 2*n; i++) {
int k = nextInt();
L[k].add(i);
}
for (int i = 1; i <= 5000; i++) {
if (L[i].size() % 2==1) {
pw.println(-1);
pw.close();
return;
}
}
for (int i = 1; i <= 5000; i++) {
for (int j = 0; j < L[i].size()-1; j += 2) {
pw.println(L[i].get(j)+" "+L[i].get(j+1));
}
}
pw.close();
}
private static int nextInt() throws IOException{
return Integer.parseInt(next());
}
private static long nextLong() throws IOException{
return Long.parseLong(next());
}
private static double nextDouble() throws IOException{
return Double.parseDouble(next());
}
private static String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
}
| Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | e7e94e89249f7b4387383c6205bbf94c | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
public class A {
BufferedReader in;
StringTokenizer str;
PrintWriter out;
String SK;
String next() throws IOException {
while ((str == null) || (!str.hasMoreTokens())) {
SK = in.readLine();
if (SK == null)
return null;
str = new StringTokenizer(SK);
}
return str.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
void solve() throws IOException {
int N = nextInt();
int[] first = new int[N];
int[] second = new int[N];
int[] last = new int[5001];
int j = 0;
for(int i = 0; i < 2*N; i++){
int num = nextInt();
if( last[num] == 0){
last[num] = i+1;
}
else{
first[j] = last[num];
second[j++] = i+1;
last[num] = 0;
}
}
if(j < N){
out.println(-1);
//out.write(-1+"\n");
}
else{
for(int i = 0; i < j; i++){
//out.write((first[i]) + " " + (second[i]) +"\n");
out.println(first[i] + " " + second[i]);
}
}
}
void run() throws IOException {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new A().run();
}
} | Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | de764ee33416c78ed7a0c67c2c33e9b7 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class P_254_A {
static int count[] = new int[5001];
@SuppressWarnings("unchecked")
static LinkedList<Integer> nodes[] = (LinkedList<Integer>[]) new LinkedList[5001];
public static void main(String[] args) throws IOException {
InputReader x = new InputReader(new FileInputStream("input.txt"));
BufferedWriter w = new BufferedWriter(new FileWriter("output.txt"));
long n = x.nextLong();
for (int i = 0; i <= 5000; i++)
nodes[i] = new LinkedList<Integer>();
for (int i = 0; i < 2 * n; i++) {
int c = x.nextInt();
count[c]++;
nodes[c].add(i);
}
for (int i = 0; i < 5001; i++) {
if (count[i] % 2 != 0) {
w.append("-1\n");
w.flush();
w.close();
return;
}
}
for (int i = 0; i < 5001; i++) {
while (count[i] != 0) {
count[i] -= 2;
int s1 = nodes[i].poll();
int s2 = nodes[i].poll();
w.append((s1 + 1) + " " + (s2 + 1) + "\n");
}
}
w.flush();
w.close();
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return 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 | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | f30f740eb760a326a1a7e1ea22236751 | train_004.jsonl | 1355047200 | Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards into pairs so that each pair had equal numbers on the cards. Help Petya do that. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
//public static Scanner scan = new Scanner(System.in);
public static void main(String[] args)
throws Exception {
BufferedReader scan = new BufferedReader(new FileReader("input.txt"));
//BufferedWriter out = new BufferedWriter(new FileWriter("output.txt"));
//FileOutputStream out = new FileOutputStream(new File("output.txt"));
PrintWriter out2 = new PrintWriter(new FileOutputStream("output.txt"));
//System.out.println("passed");
int n1 = Integer.parseInt(scan.readLine());
HashMap<Integer,ArrayList<Integer>> m1 = new HashMap();
String[] l2 = scan.readLine().split(" ");
for (int i=0;i<2*n1;i++){
int k1 = Integer.parseInt(l2[i]);
if (m1.containsKey(k1)){
m1.get(k1).add(i+1);
}
else {
ArrayList<Integer> l1 = new ArrayList();
l1.add(i+1);
m1.put(k1, l1);
}
}
boolean exist = true;
for (Integer e: m1.keySet()){
if (m1.get(e).size()%2==1){
exist=false;
break;
}
}
if (!exist){
//System.out.println(-1);
out2.write(""+-1+"\n");
//out.flush();
}
else {
for (Integer e: m1.keySet()){
ArrayList<Integer> l1 = m1.get(e);
for (int j=0;j<l1.size()/2;j++){
//System.out.println(l1.get(2*j)+" "+l1.get(2*j+1));
out2.write(l1.get(2*j)+" "+l1.get(2*j+1)+"\n");
}
}
}
out2.close();
}
} | Java | ["3\n20 30 10 30 20 10", "1\n1 2"] | 1 second | ["4 2\n1 5\n6 3", "-1"] | null | Java 6 | input.txt | [
"constructive algorithms",
"sortings"
] | 0352429425782d7fe44818594eb0660c | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains the sequence of 2n positive integers a1, a2, ..., a2n (1 ≤ ai ≤ 5000) — the numbers that are written on the cards. The numbers on the line are separated by single spaces. | 1,200 | If it is impossible to divide the cards into pairs so that cards in each pair had the same numbers, print on a single line integer -1. But if the required partition exists, then print n pairs of integers, a pair per line — the indices of the cards that form the pairs. Separate the numbers on the lines by spaces. You can print the pairs and the numbers in the pairs in any order. If there are multiple solutions, print any of them. | output.txt | |
PASSED | 3d6cd72b32cbb4829a98aabf3e2478e2 | train_004.jsonl | 1506263700 | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class ManthanE {
/*
1
2 8 8
[1, 0, 0, 0] 3 0 0 0
[1, 0, 0, 0] 3 10 1 1
[1, 0, 0, 0] 2 0 0 1
[1, 0, 0, 0] 3 11 1 0
[1, 0, 0, 0] 3 0 1 0
[1, 0, 0, 0] 2 10 1 0
[1, 0, 0, 0] 1 0 0 1
[1, 0, 0, 0] 3 10 1 1
[1, 0, 0, 0] 3 1 1 1
[1, 0, 0, 0] 2 11 1 2
[1, 0, 0, 0] 3 1 1 1
[1, 0, 0, 0] 3 10 1 1
[1, 0, 0, 0] 2 0 1 2
[1, 0, 0, 0] 1 10 1 4
[1, 0, 0, 0] 0 0 0 5
[1, 1, 1] 2 0 0 0
[1, 1, 1] 2 10 1 1
[1, 1, 1] 1 0 0 1
[1, 1, 1] 2 11 1 0
[1, 1, 1] 2 0 1 0
[1, 1, 1] 1 10 1 0
[1, 1, 1] 0 0 0 1
4
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
dp = new Long[2][11][64][1<<10];
int q = scan.nextInt();
for(int qq = 0; qq < q; qq++) {
b = scan.nextInt();
long l = scan.nextLong()-1, r = scan.nextLong();
System.out.println(solve(r)-solve(l));
}
}
static int b;
static int[] num;
static Long[][][][] dp;
static long go(int at, int m, int mask, int z) {
if(at == num.length) return mask==0&&z==1?1:0;
if(dp[z][b][at][mask] != null && m == 0) return dp[z][b][at][mask];
long res = 0;
int lim = b-1;
if(m == 1) lim = num[at];
for(int i = 0; i <= lim; i++) {
int nmask = mask;
if(z == 1 || i != 0) nmask ^= 1<<i;
res += go(at+1, i==num[at]?m:0, nmask, i!=0?1:z);
}
// System.out.println(Arrays.toString(num)+" "+at+" "+Integer.toBinaryString(mask)+" "+z+" "+res+" "+lim+" "+m);
if(m == 0) dp[z][b][at][mask] = res;
return res;
}
static long solve(long in) {
char[] a = Long.toString(in, b).toCharArray();
num = new int[64];
for(int i = 64-a.length, j = 0; i < 64; i++, j++) num[i] = a[j]-'0';
return go(0, 1, 0, 0);
}
}
| Java | ["2\n2 4 9\n3 1 10", "2\n2 1 100\n5 1 100"] | 2 seconds | ["1\n2", "21\n4"] | NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 2df506710dfbc401e5c71ff7ae63746d | First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018). | 2,200 | You have to output q lines, each containing a single integer, the answer to the corresponding query. | standard output | |
PASSED | ac5c7144056b434942888aa3a0ae7bf3 | train_004.jsonl | 1506263700 | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers. | 256 megabytes | import java.io.*;
import java.util.*;
/*
2
10 1 1000000000000000000
2 1 1000000000000000000
2105532412794693
307846415898858838
*/
public class e {
static long[][][][] memo;
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
memo = new long[11][1 << 10][80][2];
for(long[][][] mem0 : memo)
for(long[][] mem1 : mem0)
for(long[] mem2 : mem1)
Arrays.fill(mem2, -1);
int q = in.nextInt();
for(int i=0;i<q;i++) {
base = in.nextInt();
long l = in.nextLong(), r = in.nextLong();
out.println(solve(r) - solve(l-1));
}
out.close();
}
static long solve(long x) {
if(x == 0)
return 0;
upperBound = genUpperBound(base, x);
int mask = 0;
long ans = 0;
for(int match=0;match<upperBound.length;match++) {
for(int cur=0;cur<upperBound[match];cur++) {
int cmask = mask ^ (1 << cur);
if(match == 0 && cur == 0)
cmask ^= 1 << cur;
int zeroAllowed = match > 0 || cur != 0 ? 1 : 0;
ans += go(base, cmask, upperBound.length-match-1, zeroAllowed);
}
mask ^= 1 << upperBound[match];
}
if(mask == 0) {
ans++;
}
return ans;
}
static long go(int base, int mask, int countLeft, int zerosCount) {
if(countLeft == 0) {
if(zerosCount == 0)
return 0;
return mask == 0 ? 1 : 0;
}
if(memo[base][mask][countLeft][zerosCount] != -1)
return memo[base][mask][countLeft][zerosCount];
long ans = 0;
for(int i=0;i<base;i++) {
int nz = zerosCount;
if(i > 0)
nz = 1;
int nmask = mask;
if(i != 0 || zerosCount == 1)
nmask ^= (1 << i);
ans += go(base, nmask, countLeft-1, nz);
}
return memo[base][mask][countLeft][zerosCount] = ans;
}
static int[] genUpperBound(int b, long x) {
ArrayList<Integer> list = new ArrayList<>();
while(x != 0) {
list.add((int)(x%b));
x /= b;
}
int[] res = new int[list.size()];
for(int i=0;i<list.size();i++) {
res[i] = list.get(res.length-1-i);
}
return res;
}
static int[] upperBound;
static int base;
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream i) {
br = new BufferedReader(new InputStreamReader(i));
st = null;
}
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 int[] nextIntArray(int n) throws IOException {
int[] arr = new int[n];
for(int i=0;i<n;i++)
arr[i] = nextInt();
return arr;
}
public long[] nextLongArray(int n) throws IOException {
long[] arr = new long[n];
for(int i=0;i<n;i++)
arr[i] = nextInt();
return arr;
}
public String[] nextStringArray(int n) throws IOException {
String[] arr = new String[n];
for(int i=0;i<n;i++)
arr[i] = next();
return arr;
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
}
| Java | ["2\n2 4 9\n3 1 10", "2\n2 1 100\n5 1 100"] | 2 seconds | ["1\n2", "21\n4"] | NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 2df506710dfbc401e5c71ff7ae63746d | First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018). | 2,200 | You have to output q lines, each containing a single integer, the answer to the corresponding query. | standard output | |
PASSED | edf2c9456ca06af424904c69dad2b5be | train_004.jsonl | 1506263700 | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers. | 256 megabytes | import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
public class E {
static final int[] baseSize = {-1, -1, 60, 38, 30, 26, 24, 22, 20, 19, 19};
static long[][][][] memo;
static long[][] comb;
static long count(int b, int idx, int n, int msk)
{
if(idx == b)
return n == 0 ? 1 : 0;
if(memo[b][idx][n][msk] != -1)
return memo[b][idx][n][msk];
long ret = 0;
int one = (msk >> idx) & 1;
for(int take = one; take <= n; take += 2)
ret += comb[n][take] * count(b, idx + 1, n - take, msk);
return memo[b][idx][n][msk] = ret;
}
static void init()
{
comb = new long[70][70];
comb[0][0] = 1;
for(int i = 1; i < 70; ++i)
{
comb[i][0] = 1;
for(int j = 1; j <= i; ++j)
comb[i][j] = comb[i - 1][j] + comb[i - 1][j - 1];
}
memo = new long[11][][][];
memo[0] = memo[1] = new long[0][0][0];
for(int b = 2; b <= 10; ++b)
memo[b] = new long[baseSize[b]][baseSize[b]][1 << b];
for(long[][][] x: memo)
for(long[][] y: x)
for(long[] z: y)
Arrays.fill(z, -1);
}
static long solve(int b, long L)
{
long ans = 0;
String s = Long.toString(L, b);
int msk = 0;
for(int i = 0; i < s.length(); ++i)
{
for(int d = i == 0 ? 1 : 0; d < s.charAt(i) - '0'; ++d)
ans += count(b, 0, s.length() - i - 1, msk ^ (1 << d));
if(i > 0)
ans += count(b, 0, i, 0) - count(b, 0, i - 1, 1);
msk ^= 1 << s.charAt(i) - '0';
}
if(msk == 0)
++ans;
return ans;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
init();
int q = sc.nextInt();
StringBuilder sb = new StringBuilder();
while(q-->0)
{
int b = sc.nextInt();
long l = sc.nextLong(), r = sc.nextLong();
long ans = solve(b, r) - solve(b, l - 1);
sb.append(ans + "\n");
}
out.print(sb);
out.close();
}
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(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 double nextDouble() throws IOException { return Double.parseDouble(next()); }
public boolean ready() throws IOException {return br.ready();}
}
} | Java | ["2\n2 4 9\n3 1 10", "2\n2 1 100\n5 1 100"] | 2 seconds | ["1\n2", "21\n4"] | NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 2df506710dfbc401e5c71ff7ae63746d | First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018). | 2,200 | You have to output q lines, each containing a single integer, the answer to the corresponding query. | standard output | |
PASSED | 0632aec01248cb157ac87d84b1b0efe3 | train_004.jsonl | 1506263700 | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers. | 256 megabytes | import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
public class E {
static final int[] baseSize = {-1, -1, 60, 38, 30, 26, 24, 22, 20, 19, 19};
static long[][][] memo;
static long[][] comb;
static long count(int b, int n, int msk)
{
if(n == 0)
return msk == 0 ? 1 : 0;
if(memo[b][n][msk] != -1)
return memo[b][n][msk];
long ret = 0;
for(int d = 0; d < b; ++d)
ret += count(b, n - 1, msk ^ (1 << d));
return memo[b][n][msk] = ret;
}
static void init()
{
memo = new long[11][][];
memo[0] = memo[1] = new long[0][0];
for(int b = 2; b <= 10; ++b)
memo[b] = new long[baseSize[b]][1 << b];
for(long[][] x: memo)
for(long[] y: x)
Arrays.fill(y, -1);
}
static long solve(int b, long L)
{
long ans = 0;
String s = Long.toString(L, b);
int msk = 0;
for(int i = 0; i < s.length(); ++i)
{
for(int d = i == 0 ? 1 : 0; d < s.charAt(i) - '0'; ++d)
ans += count(b, s.length() - i - 1, msk ^ (1 << d));
if(i > 0)
ans += count(b, i, 0) - count(b, i - 1, 1);
msk ^= 1 << s.charAt(i) - '0';
}
if(msk == 0)
++ans;
return ans;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
init();
int q = sc.nextInt();
StringBuilder sb = new StringBuilder();
while(q-->0)
{
int b = sc.nextInt();
long l = sc.nextLong(), r = sc.nextLong();
long ans = solve(b, r) - solve(b, l - 1);
sb.append(ans + "\n");
}
out.print(sb);
out.close();
}
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(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 double nextDouble() throws IOException { return Double.parseDouble(next()); }
public boolean ready() throws IOException {return br.ready();}
}
} | Java | ["2\n2 4 9\n3 1 10", "2\n2 1 100\n5 1 100"] | 2 seconds | ["1\n2", "21\n4"] | NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 2df506710dfbc401e5c71ff7ae63746d | First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018). | 2,200 | You have to output q lines, each containing a single integer, the answer to the corresponding query. | standard output | |
PASSED | 3eeb7818345299d54dd29239ebc8a2ee | train_004.jsonl | 1506263700 | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers. | 256 megabytes | import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
public class E {
static final int[] baseSize = {-1, -1, 60, 38, 30, 26, 24, 22, 20, 19, 19};
static long[][][][] memo;
static long[][] comb;
static long count(int b, int idx, int n, int msk)
{
if(idx == b)
return n == 0 ? 1 : 0;
if(memo[b][idx][n][msk] != -1)
return memo[b][idx][n][msk];
long ret = 0;
int one = (msk >> idx) & 1;
for(int take = one; take <= n; take += 2)
ret += comb[n][take] * count(b, idx + 1, n - take, msk);
return memo[b][idx][n][msk] = ret;
}
static void init()
{
comb = new long[70][70];
comb[0][0] = 1;
for(int i = 1; i < 70; ++i)
{
comb[i][0] = 1;
for(int j = 1; j <= i; ++j)
comb[i][j] = comb[i - 1][j] + comb[i - 1][j - 1];
}
memo = new long[11][][][];
memo[0] = memo[1] = new long[0][0][0];
for(int b = 2; b <= 10; ++b)
memo[b] = new long[baseSize[b]][baseSize[b]][1 << b];
for(long[][][] x: memo)
for(long[][] y: x)
for(long[] z: y)
Arrays.fill(z, -1);
}
static long solve(int b, long L)
{
long ans = 0;
String s = Long.toString(L, b);
// System.err.println(L + " " + s);
long add = 0;
for(int i = 1; i < s.length(); ++i)
for(int d = 1; d < b; ++d)
add += count(b, 0, i - 1, 1 << d);
// System.err.println(count(3, 0, 1, 1 << 1));
// System.err.println(Arrays.toString(added));
int msk = 0;
for(int i = 0; i < s.length(); ++i)
{
// mismatch at i
for(int d = i == 0 ? 1 : 0; d < s.charAt(i) - '0'; ++d)
ans += count(b, 0, s.length() - i - 1, msk ^ (1 << d));
if(i == 0)
ans += add;
msk ^= 1 << s.charAt(i) - '0';
}
// System.err.println("");
if(msk == 0)
++ans;
return ans;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
// for(int i = 2; i <= 10; ++i)
// {
// String s = Long.toString((long)1e18, i);
// System.err.println(s + " " + s.length());
// }
init();
int q = sc.nextInt();
StringBuilder sb = new StringBuilder();
while(q-->0)
{
int b = sc.nextInt();
long l = sc.nextLong(), r = sc.nextLong();
// for(int i = l; i <= r; ++i)
// System.err.println(Integer.toString(i, b));
long ans = solve(b, r) - solve(b, l - 1);
// System.err.println(solve(b, r));
sb.append(ans + "\n");
}
out.print(sb);
out.close();
}
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(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 double nextDouble() throws IOException { return Double.parseDouble(next()); }
public boolean ready() throws IOException {return br.ready();}
}
} | Java | ["2\n2 4 9\n3 1 10", "2\n2 1 100\n5 1 100"] | 2 seconds | ["1\n2", "21\n4"] | NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 2df506710dfbc401e5c71ff7ae63746d | First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018). | 2,200 | You have to output q lines, each containing a single integer, the answer to the corresponding query. | standard output | |
PASSED | 7cb92206d181f44f44bd498a82e6fa09 | train_004.jsonl | 1506263700 | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers. | 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.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jialin Ouyang (Jialin.Ouyang@gmail.com)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
QuickScanner in = new QuickScanner(inputStream);
QuickWriter out = new QuickWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
static class TaskE {
static int MAXB = 10;
static int MAXL = 64;
static int MAXMASK = 1 << MAXB;
long[][][] anyCnt;
long[][] positiveCnt;
int totalLength;
int[] digits;
public void solve(int testNumber, QuickScanner in, QuickWriter out) {
init();
for (int remQ = in.nextInt(); remQ > 0; --remQ) {
int b = in.nextInt();
long l = in.nextLong();
long r = in.nextLong();
out.println(calc(b, r) - calc(b, l - 1));
}
}
void init() {
anyCnt = new long[MAXB + 1][MAXL][MAXMASK];
for (int b = 2; b <= MAXB; ++b) {
anyCnt[b][0][0] = 1;
for (int length = 1; length < MAXL; ++length)
for (int mask = (1 << b) - 1; mask >= 0; --mask) {
long sum = 0;
for (int digit = 0; digit < b; ++digit) {
sum += anyCnt[b][length - 1][mask ^ (1 << digit)];
}
anyCnt[b][length][mask] = sum;
}
}
positiveCnt = new long[MAXB + 1][MAXL];
for (int b = 2; b <= MAXB; ++b)
for (int length = 1; length < MAXL; ++length) {
long sum = 0;
for (int digit = 1; digit < b; ++digit) {
sum += anyCnt[b][length - 1][1 << digit];
}
positiveCnt[b][length] = sum;
}
}
long calc(int base, long x) {
if (x == 0) return 0;
if (digits == null) {
digits = new int[MAXL];
}
for (totalLength = 0; x > 0; x /= base) {
digits[totalLength++] = (int) (x % base);
}
long res = 0;
for (int length = 1; length < totalLength; ++length) {
res += positiveCnt[base][length];
}
int mask = 0;
for (int i = totalLength - 1; i >= 0; --i) {
for (int digit = i + 1 == totalLength ? 1 : 0; digit < digits[i]; ++digit) {
res += anyCnt[base][i][mask ^ (1 << digit)];
}
mask ^= 1 << digits[i];
}
return res + (mask == 0 ? 1 : 0);
}
}
static class QuickScanner {
private static final int BUFFER_SIZE = 1024;
private InputStream stream;
private byte[] buffer;
private int currentPosition;
private int numberOfChars;
public QuickScanner(InputStream stream) {
this.stream = stream;
this.buffer = new byte[BUFFER_SIZE];
this.currentPosition = 0;
this.numberOfChars = 0;
}
public int nextInt() {
int c = nextNonSpaceChar();
boolean positive = true;
if (c == '-') {
positive = false;
c = nextChar();
}
int res = 0;
do {
if (c < '0' || '9' < c) throw new RuntimeException();
res = res * 10 + c - '0';
c = nextChar();
} while (!isSpaceChar(c));
return positive ? res : -res;
}
public long nextLong() {
int c = nextNonSpaceChar();
boolean positive = true;
if (c == '-') {
positive = false;
c = nextChar();
}
long res = 0;
do {
if (c < '0' || '9' < c) throw new RuntimeException();
res = res * 10 + c - '0';
c = nextChar();
} while (!isSpaceChar(c));
return positive ? res : -res;
}
public int nextNonSpaceChar() {
int res = nextChar();
for (; isSpaceChar(res) || res < 0; res = nextChar()) ;
return res;
}
public int nextChar() {
if (numberOfChars == -1) {
throw new RuntimeException();
}
if (currentPosition >= numberOfChars) {
currentPosition = 0;
try {
numberOfChars = stream.read(buffer);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (numberOfChars <= 0) {
return -1;
}
}
return buffer[currentPosition++];
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\t' || isEndOfLineChar(c);
}
public boolean isEndOfLineChar(int c) {
return c == '\n' || c == '\r' || c < 0;
}
}
static class QuickWriter {
private final PrintWriter writer;
public QuickWriter(OutputStream outputStream) {
this.writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public QuickWriter(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 println(Object... objects) {
print(objects);
writer.print('\n');
}
public void close() {
writer.close();
}
}
}
| Java | ["2\n2 4 9\n3 1 10", "2\n2 1 100\n5 1 100"] | 2 seconds | ["1\n2", "21\n4"] | NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 2df506710dfbc401e5c71ff7ae63746d | First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018). | 2,200 | You have to output q lines, each containing a single integer, the answer to the corresponding query. | standard output | |
PASSED | eba3adecf99cd90cbd8475f42cef1dea | train_004.jsonl | 1506263700 | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers. | 256 megabytes | import java.io.*;
import java.util.*;
public class A {
private FastScanner in;
private PrintWriter out;
long[][][] dp;
int[] val = new int[66];
long getAnswer(int base, long value) {
if (value == 0) {
return 0;
}
// long pValue = value;
int valSz = 0;
while (value != 0) {
val[valSz++] = (int) (value % base);
value /= base;
}
long result = 0;
for (int len = 1; len < valSz; len++) {
result += dp[base][len][0] - dp[base][len - 1][1];
}
int xor = 0;
for (int next = 1; next < val[valSz - 1]; next++) {
result += dp[base][valSz - 1][xor ^ (1 << next)];
}
for (int sameLen = 1; sameLen <= valSz; sameLen++) {
xor ^= 1 << val[valSz - sameLen];
if (sameLen == valSz) {
if (xor == 0) {
result++;
}
} else {
for (int next = 0; next < val[valSz - sameLen - 1]; next++) {
result += dp[base][valSz - sameLen - 1][xor ^ (1 << next)];
}
}
}
// System.err.println("answer for " + base + " " + pValue + " is " + result);
return result;
}
private void solve() {
// base, len, mask
dp = new long[11][][];
for (int base = 2; base <= 10; base++) {
long[][] cur = new long[62][1 << base];
cur[0][0] = 1;
for (int len = 0; len + 1 < cur.length; len++) {
for (int mask = 0; mask < cur[0].length; mask++) {
long now = cur[len][mask];
if (now == 0) {
continue;
}
for (int use = 0; use < base; use++) {
cur[len + 1][mask ^ (1 << use)] += now;
}
}
}
dp[base] = cur;
}
int q = in.nextInt();
for (int i = 0; i < q; i++) {
int base = in.nextInt();
long left = in.nextLong();
long right = in.nextLong();
out.println(getAnswer(base, right) - getAnswer(base, left - 1));
}
}
private void run() {
try {
in = new FastScanner(new File("A.in"));
out = new PrintWriter(new File("A.out"));
solve();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private void runIO() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
private class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] args) {
new A().runIO();
}
} | Java | ["2\n2 4 9\n3 1 10", "2\n2 1 100\n5 1 100"] | 2 seconds | ["1\n2", "21\n4"] | NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 2df506710dfbc401e5c71ff7ae63746d | First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018). | 2,200 | You have to output q lines, each containing a single integer, the answer to the corresponding query. | standard output | |
PASSED | 318ae6f9fe54bc24d9b73fcb0cb05f22 | train_004.jsonl | 1506263700 | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers. | 256 megabytes | import java.util.*;
import java.io.IOException;
public class Test {
long readLong() {
long 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[] ds = new int[64];
long[][][] dp = new long[11][65][1234];
int getDigits(long v, int b, int[] ds) {
int lp = ds.length;
while (v > 0) {
lp--;
ds[lp] = (int)(v % b);
v /= b;
}
return lp;
}
long solve(long n, int b) {
int p = getDigits(n, b, ds);
long ans = 0;
for (int i = 1; ds.length - i > p; i++) ans += dp[b][i][0] - dp[b][i - 1][1];
int mask = 0;
for (int i = p; i < ds.length; i++) {
for (int d = 0; d < ds[i]; d++) {
if (i == p && d == 0) continue;
ans += dp[b][ds.length - i - 1][mask ^ (1 << d)];
}
mask ^= (1 << ds[i]);
}
return ans;
}
void start() {
for (int b = 2; b <= 10; b++) {
dp[b][0][0] = 1;
for (int p = 1; p <= 64; p++) {
for (int t = 0; t < (1 << b); t++) {
for (int d = 0; d < b; d++)
dp[b][p][t] += dp[b][p - 1][t ^ (1 << d)];
}
}
}
long q = readLong();
while (q > 0) {
q--;
int b = (int)readLong();
long l = readLong(), r = readLong();
System.out.println(solve(r + 1, b) - solve(l, b));
}
}
public static void main(String[] args) {
new Test().start();
}
} | Java | ["2\n2 4 9\n3 1 10", "2\n2 1 100\n5 1 100"] | 2 seconds | ["1\n2", "21\n4"] | NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 2df506710dfbc401e5c71ff7ae63746d | First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018). | 2,200 | You have to output q lines, each containing a single integer, the answer to the corresponding query. | standard output | |
PASSED | 8aedf80f1a4d5bb8457816aea5e98c0c | train_004.jsonl | 1506263700 | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ProblemE2 {
BufferedReader rd;
long[][][][] dp = new long[11][61][10][1024];
ProblemE2() throws IOException {
rd = new BufferedReader(new InputStreamReader(System.in));
compute();
}
private void compute() throws IOException {
startDp();
int q = pint();
StringBuilder buf = new StringBuilder();
for(int i=0;i<q;i++) {
long[] a = longarr();
long b = a[0];
long l = a[1];
long r = a[2];
if(i > 0) {
buf.append('\n');
}
buf.append(solve((int)b,l,r));
}
out(buf);
}
private long solve(int base, long l, long r) {
return countLe(base, r) - countLe(base, l-1);
}
private long countLe(int base, long x) {
String s = Long.toString(x, base);
int len = s.length();
long res = 0;
for(int i=1;i<len;i++) {
for(int d=1;d<=base-1;d++) {
res += dp[base][i][d][0];
}
}
int state = 0;
for(int i=0;i<len;i++) {
int firstDigit = s.charAt(i)-'0';
int limit = firstDigit;
if(i == len-1) {
limit++;
}
int start;
if(i == 0) {
start = 1;
} else {
start = 0;
}
for(int digit=start;digit<limit;digit++) {
res += dp[base][len - i][digit][state];
}
state = flip(state, firstDigit);
}
return res;
}
private void startDp() {
for(int base=2;base <= 10;base++) {
for(int len=1;len <= 60;len++) {
for(int firstDigit=0;firstDigit<base;firstDigit++) {
int s = 1<<base;
for(int state=0;state<s;state++) {
long res = 0;
int newState = flip(state, firstDigit);
if(len == 1) {
res = newState == 0 ? 1 : 0;
} else {
for(int nextDigit = 0;nextDigit<base;nextDigit++) {
res += dp[base][len-1][nextDigit][newState];
}
}
dp[base][len][firstDigit][state] = res;
}
}
}
}
}
private int flip(int state, int digit) {
int f = 1<<digit;
int newState;
if((state & f) > 0) {
newState = state - f;
} else {
newState = state + f;
}
return newState;
}
private int pint() throws IOException {
return pint(rd.readLine());
}
private int pint(String s) {
return Integer.parseInt(s);
}
private long[] longarr() throws IOException {
return longarr(rd.readLine());
}
private long[] longarr(String s) {
String[] q = split(s);
int n = q.length;
long[] a = new long[n];
for(int i=0;i<n;i++) {
a[i] = Long.parseLong(q[i]);
}
return a;
}
private String[] split(String s) {
if(s == null) {
return new String[0];
}
int n = s.length();
int start = -1;
int end = 0;
int sp = 0;
boolean lastWhitespace = true;
for(int i=0;i<n;i++) {
char c = s.charAt(i);
if(isWhitespace(c)) {
lastWhitespace = true;
} else {
if(lastWhitespace) {
sp++;
}
if(start == -1) {
start = i;
}
end = i;
lastWhitespace = false;
}
}
if(start == -1) {
return new String[0];
}
String[] res = new String[sp];
int last = start;
int x = 0;
lastWhitespace = true;
for(int i=start;i<=end;i++) {
char c = s.charAt(i);
boolean w = isWhitespace(c);
if(w && !lastWhitespace) {
res[x++] = s.substring(last,i);
} else if(!w && lastWhitespace) {
last = i;
}
lastWhitespace = w;
}
res[x] = s.substring(last,end+1);
return res;
}
private boolean isWhitespace(char c) {
return c==' ' || c=='\t';
}
private static void out(Object x) {
System.out.println(x);
}
public static void main(String[] args) throws IOException {
new ProblemE2();
}
}
| Java | ["2\n2 4 9\n3 1 10", "2\n2 1 100\n5 1 100"] | 2 seconds | ["1\n2", "21\n4"] | NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 2df506710dfbc401e5c71ff7ae63746d | First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018). | 2,200 | You have to output q lines, each containing a single integer, the answer to the corresponding query. | standard output | |
PASSED | 7f4d36949a8c7b608fe8c020e0e6cabd | train_004.jsonl | 1506263700 | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers. | 256 megabytes | import sun.dc.pr.PRError;
import java.io.*;
import java.util.*;
public class Solution {
static MyScanner sc;
private static PrintWriter out;
static long M = 1000000007;
public static void main(String[] s) throws Exception {
StringBuilder stringBuilder = new StringBuilder();
//
// stringBuilder.append("5 9\n" +
// "mahmoud mahmoudbadawy drmahmoud drevil mahmoud\n" +
// "1 1 5\n" +
// "1 1 2\n" +
// "1 2 3\n" +
// "2 3 mahmoud\n" +
// "2 4 mahmoud\n" +
// "2 2 mahmouu\n" +
// "1 1 5\n" +
// "1 2 3\n" +
// "1 1 1\n");
if (stringBuilder.length() == 0) {
sc = new MyScanner(System.in);
} else {
sc = new MyScanner(new BufferedReader(new StringReader(stringBuilder.toString())));
}
out = new PrintWriter(new OutputStreamWriter(System.out));
initData();
solveT();
out.flush();
}
static long[][][] tt = new long[11][65][];
static long[][][] tt2 = new long[11][65][];
private static void initData() {
for (int k = 2; k <= 10; k++) {
tt[k][0] = new long[(1 << k)];
tt2[k][0] = new long[(1 << k)];
tt[k][0][0] = 1;
for (int r = 1; r < 65; r++) {
tt[k][r] = new long[(1 << k)];
tt2[k][r] = new long[(1 << k)];
for (int i = 0; i < k; i++) {
for (int t = 0; t < (1 << k); t++) {
tt[k][r][t ^ (1 << i)] += tt[k][r - 1][t];
}
}
for (int i = 1; i < k; i++) {
for (int t = 0; t < (1 << k); t++) {
tt2[k][r][t ^ (1 << i)] += tt[k][r - 1][t];
}
}
}
}
}
private static void solve() throws IOException {
int n = sc.nextInt();
long l = sc.nextLong();
long k = sc.nextLong();
String f = Long.toString(l - 1, n);
String r = Long.toString(k, n);
// long m = 0;
// for (long x = l ; x <= k ; x++) {
// if(iss(Long.toString(x, n))) {
// m++;
// }
// }
// out.print( m + " ");
out.println(count(tt[n], tt2[n], r) - count(tt[n], tt2[n], f));
}
private static boolean iss(String s) {
boolean [] p = new boolean[10];
for (char x : s.toCharArray()) {
p[x - '0'] = !p[x - '0'];
}
for (boolean r : p) {
if (r) return false;
}
return true;
}
private static long count(long[][] longs, long[][] longs1, String f) {
StringBuilder x = new StringBuilder();
long res = 0;
for (int c = 0; c < f.length(); c++) {
res += longs1[c][0];
}
return res + count(longs, f, 0, true);
}
private static long count(long[][] longs, String f, int i, boolean fO) {
if (f.length() == 0) return i == 0 ? 1: 0;
long res = 0;
int o = f.length();
int r = fO ? '1' : '0';
for (; r < f.charAt(0); r++) {
res += longs[o - 1][i ^ (1 << (r - '0'))];
}
res += count(longs, f.substring(1, f.length()), i ^ (1 << (f.charAt(0) - '0')), false);
return res;
}
private static void solveT() throws IOException {
int t = sc.nextInt();
while (t-- > 0) {
solve();
}
}
private static long gcd(long l, long l1) {
if (l > l1) return gcd(l1, l);
if (l == 0) return l1;
return gcd(l1 % l, l);
}
private static long pow(long a, long b, long m) {
if (b == 0) return 1;
if (b == 1) return a;
long pp = pow(a, b / 2, m);
pp *= pp;
pp %= m;
return (pp * (b % 2 == 0 ? 1 : a)) % m;
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
MyScanner(BufferedReader br) {
this.br = br;
}
public MyScanner(InputStream in) {
this(new BufferedReader(new InputStreamReader(in)));
}
void findToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
String next() {
findToken();
return st.nextToken();
}
Integer[] nab(int n) {
Integer[] k = new Integer[n];
for (int i = 0; i < n; i++) {
k[i] = sc.fi();
}
return k;
}
int[] na(int n) {
int[] k = new int[n];
for (int i = 0; i < n; i++) {
k[i] = sc.fi();
}
return k;
}
long[] nl(int n) {
long[] k = new long[n];
for (int i = 0; i < n; i++) {
k[i] = sc.nextLong();
}
return k;
}
int nextInt() {
return Integer.parseInt(next());
}
int fi() {
String t = next();
int cur = 0;
boolean n = t.charAt(0) == '-';
for (int a = n ? 1 : 0; a < t.length(); a++) {
cur = cur * 10 + t.charAt(a) - '0';
}
return n ? -cur : cur;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["2\n2 4 9\n3 1 10", "2\n2 1 100\n5 1 100"] | 2 seconds | ["1\n2", "21\n4"] | NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 2df506710dfbc401e5c71ff7ae63746d | First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018). | 2,200 | You have to output q lines, each containing a single integer, the answer to the corresponding query. | standard output | |
PASSED | 6bf3b32c838679f1b9d87764da32b226 | train_004.jsonl | 1506263700 | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class CF855E {
//http://codeforces.com/contest/855/problem/E
static long dp[][][]; //base, ind, mask
static int b;
static int hi[];
static int len;
public static void main(String[] args) {
dp = new long[11][64][(int) (Math.pow(2, 10)+1)];
for(long a[][] : dp)
for(long b[] : a)
Arrays.fill(b, -1);
FastScanner in = new FastScanner();
int T = in.nextInt();
for(int runs = 1; runs <= T; runs++)
{
b = in.nextInt();
long l = in.nextLong()-1;
long l2 = in.nextLong();
String s = Long.toString(l, b);
String s2 = Long.toString(l2, b);
//System.out.println("base: "+b+" l/r:"+s+" "+s2);
len = s.length();
hi = new int[len];
for(int i = 0; i < len; i++)
hi[i] = Integer.valueOf(s.charAt(i)+"");
long n1 = digit(0, len, true, false);
len = s2.length();
hi = new int[len];
for(int i = 0; i < len; i++)
hi[i] = Integer.valueOf(s2.charAt(i)+"");
long n2 = digit(0, len, true, false);
System.out.println(n2-n1);
}
}
static long digit(int mask, int ind, boolean bnd, boolean st)
{
if(ind == 0) return ((mask == 0 && st)? 1 : 0);
if(!bnd && st && dp[b][ind][mask] != -1) return dp[b][ind][mask];
if(bnd)
{
long res = 0;
for(int i = 0; i <= hi[len-ind]; i++)
{
res += digit(m(mask,i,st), ind-1, i == hi[len-ind]?true:false, st||(i > 0) );
}
return res;
}
else
{
long res = 0;
for(int i = 0; i < b; i++)
{
res += digit(m(mask,i,st), ind-1, false, st||(i > 0));
}
if(st) return dp[b][ind][mask] = res;
else return res;
}
}
static int m(int mask, int i, boolean st)
{
if(st == false && i == 0) return mask;
int newM = (mask ^ (1 << i));
return newM;
}
static class FastScanner{
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try{
br = new BufferedReader(new FileReader(s));
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(){
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while(st == null ||!st.hasMoreElements()){
try {
st = new StringTokenizer(br.readLine());}
catch(IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
String next() {
return nextToken();
}
}
}
| Java | ["2\n2 4 9\n3 1 10", "2\n2 1 100\n5 1 100"] | 2 seconds | ["1\n2", "21\n4"] | NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 2df506710dfbc401e5c71ff7ae63746d | First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018). | 2,200 | You have to output q lines, each containing a single integer, the answer to the corresponding query. | standard output | |
PASSED | a1af5fdeb274e2c42dc068b8ee05f543 | train_004.jsonl | 1506263700 | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers. | 256 megabytes | import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class E855 {
int n;
int[] num;
long[][][][] memo;
long dp(boolean bounded, boolean started, int base, int ind, int mask) {
if(ind == 65) return mask == 0 ? 1 : 0;
if(!bounded && memo[started ? 1 : 0][base][ind][mask] != -1) return memo[started ? 1 : 0][base][ind][mask];
int max = (bounded ? num[ind] : base - 1);
long ans = 0;
for(int i = 0; i <= max; ++i) {
boolean newStarted = started | i != 0;
ans += dp(bounded && i == max, newStarted, base, ind + 1, newStarted ? mask ^ (1 << i) : mask);
}
if(bounded) return ans;
else return memo[started ? 1 : 0][base][ind][mask] = ans;
// return ans;
}
void init(long k, int base) {
char[] digits = Long.toString(k, base).toCharArray();
n = digits.length;
for(int i = 0, j = 65 - n; i < n; ++i, ++j) {
num[j] = digits[i] - '0';
}
}
public void solve(Scanner in, PrintWriter out) {
int q = in.nextInt();
num = new int[65];
memo = new long[2][11][70][1 << 10];
for(long[][][] a : memo) {
for(long[][] b : a) {
for(long[] c : b) {
Arrays.fill(c, -1);
}
}
}
for(int qq = 1; qq <= q; ++qq) {
int base = in.nextInt();
long lower = in.nextLong() - 1;
init(lower, base);
// System.out.println(Arrays.toString(num));
long lowAns = dp(true, false, base, 65 - n, 0);
long higher = in.nextLong();
init(higher, base);
// System.out.println(Arrays.toString(num));
long highAns = dp(true, false, base, 65 - n, 0);
// System.out.println(highAns);
out.println(highAns - lowAns);
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
new E855().solve(in, out);
in.close();
out.close();
}
}
| Java | ["2\n2 4 9\n3 1 10", "2\n2 1 100\n5 1 100"] | 2 seconds | ["1\n2", "21\n4"] | NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 2df506710dfbc401e5c71ff7ae63746d | First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018). | 2,200 | You have to output q lines, each containing a single integer, the answer to the corresponding query. | standard output | |
PASSED | 4bdfc30a083063bf92dd75f186e19a0a | train_004.jsonl | 1506263700 | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers. | 256 megabytes | import java.io.*;
import java.util.*;
public class C {
static char[] a;
static long[][][][][] memo;
static int[] E, O, cntLess;
static long dp(int idx, int even, int odd, int eq, int first, int zero) {
if (idx == a.length)
return odd == 0 && first == 0 && zero == 0 ? 1 : 0;
if (memo[eq][first][zero][even][idx] != -1)
return memo[eq][first][zero][even][idx];
int curr = a[idx] - '0';
long ans = 0;
if (eq == 1) {
// for (int d = 1; d <= curr; d++) {
// int p = (msk & (1 << d)) == 0 ? 0 : 1;
// ans += dp(idx + 1, even + (p == 0 ? -1 : 1), odd + (p == 0 ? 1 : -1), curr == d ? 1 : 0, 0,
// msk ^ 1 << d, zero);
//
// }
// put curr if!=0
if (curr != 0) {
ans += dp(idx + 1, E[idx], O[idx], 1, 0, zero);
}
int c;
c = cntLess[idx];
if (c > 0)
ans += c * dp(idx + 1, even - 1, odd + 1, 0, 0, zero);
c = curr > 1 ? curr - 1 - c : 0;
if (c > 0)
ans += c * dp(idx + 1, even + 1, odd - 1, 0, 0, zero);
} else {
// put even
if (even > 0)
ans += even * dp(idx + 1, even - 1, odd + 1, 0, 0, zero);
// put odd
if (odd > 0)
ans += odd * dp(idx + 1, even + 1, odd - 1, 0, 0, zero);
}
// put zero
ans += dp(idx + 1, even, odd, (eq == 1 && curr == 0) ? 1 : 0, first, first == 0 ? zero ^ 1 : 0);
return memo[eq][first][zero][even][idx] = ans;
}
static long solve(long x, int b) {
a = Long.toString(x, b).toCharArray();
int n = a.length;
E = new int[n];
cntLess = new int[n];
O = new int[n];
int msk = 0;
E[0] = b - 1;
for (int i = 0; i < n; i++) {
int y = a[i] - '0';
if (y != 0) {
int p = (msk & 1 << y) == 0 ? 0 : 1;
if (p == 1)
E[i]++;
else {
E[i]--;
}
msk ^= 1 << y;
}
if (i > 0) {
E[i] += E[i - 1];
}
for (int d = 1; d < y; d++) {
if ((msk & 1 << d) == 0)
cntLess[i]++;
}
O[i] = b - 1 - E[i];
}
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
for (int k = 0; k < 2; k++)
for (int l = 0; l < b; l++)
for (int len = 0; len < a.length; len++)
memo[i][j][k][l][len] = -1;
return dp(0, b - 1, 0, 1, 1, 0);
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
memo = new long[2][2][2][11][70];
int q = sc.nextInt();
while (q-- > 0) {
int b = sc.nextInt();
long l = sc.nextLong(), r = sc.nextLong();
out.println(solve(r, b) - solve(l - 1, b));
}
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();
}
}
static void sort(int[] a) {
shuffle(a);
Arrays.sort(a);
}
static void shuffle(int[] a) {
int n = a.length;
Random rand = new Random();
for (int i = 0; i < n; i++) {
int tmpIdx = rand.nextInt(n);
int tmp = a[i];
a[i] = a[tmpIdx];
a[tmpIdx] = tmp;
}
}
} | Java | ["2\n2 4 9\n3 1 10", "2\n2 1 100\n5 1 100"] | 2 seconds | ["1\n2", "21\n4"] | NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 2df506710dfbc401e5c71ff7ae63746d | First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018). | 2,200 | You have to output q lines, each containing a single integer, the answer to the corresponding query. | standard output | |
PASSED | 143a89739e4272358ec921f8e878fc3d | train_004.jsonl | 1506263700 | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers. | 256 megabytes | import java.io.*;
import java.util.*;
public class C {
static char[] a;
static long[][][][][] memo;
static int[] E, O, cntLess;
static long dp(int idx, int even, int odd, int eq, int first, int zero) {
if (idx == a.length)
return odd == 0 && first == 0 && zero == 0 ? 1 : 0;
if (memo[eq][first][zero][even][idx] != -1)
return memo[eq][first][zero][even][idx];
int curr = a[idx] - '0';
long ans = 0;
if (eq == 1) {
// for (int d = 1; d <= curr; d++) {
// int p = (msk & (1 << d)) == 0 ? 0 : 1;
// ans += dp(idx + 1, even + (p == 0 ? -1 : 1), odd + (p == 0 ? 1 : -1), curr == d ? 1 : 0, 0,
// msk ^ 1 << d, zero);
//
// }
// put curr if!=0
if (curr != 0) {
ans += dp(idx + 1, E[idx], O[idx], 1, 0, zero);
}
int c;
c = cntLess[idx];
if (c > 0)
ans += c * dp(idx + 1, even - 1, odd + 1, 0, 0, zero);
c = curr > 1 ? curr - 1 - c : 0;
if (c > 0)
ans += c * dp(idx + 1, even + 1, odd - 1, 0, 0, zero);
} else {
// put even
if (even > 0)
ans += even * dp(idx + 1, even - 1, odd + 1, 0, 0, zero);
// put odd
if (odd > 0)
ans += odd * dp(idx + 1, even + 1, odd - 1, 0, 0, zero);
}
// put zero
ans += dp(idx + 1, even, odd, (eq == 1 && curr == 0) ? 1 : 0, first, first == 0 ? zero ^ 1 : 0);
return memo[eq][first][zero][even][idx] = ans;
}
static long solve(long x, int b) {
a = Long.toString(x, b).toCharArray();
int n = a.length;
E = new int[n];
cntLess = new int[n];
O = new int[n];
int msk = 0;
E[0] = b - 1;
for (int i = 0; i < n; i++) {
int y = a[i] - '0';
if (y != 0) {
int p = (msk & 1 << y) == 0 ? 0 : 1;
if (p == 1)
E[i]++;
else {
E[i]--;
}
msk ^= 1 << y;
}
if (i > 0) {
E[i] += E[i - 1];
}
for (int d = 1; d < y; d++) {
if ((msk & 1 << d) == 0)
cntLess[i]++;
}
O[i] = b - 1 - E[i];
}
for (int i = 0; i < 2; i++) {
long[][][][] x1 = memo[i];
for (int j = 0; j < 2; j++) {
long[][][] x2 = x1[j];
for (int k = 0; k < 2; k++) {
long[][] x3 = x2[k];
for (int l = 0; l < b; l++) {
long[] x4 = x3[l];
for (int len = 0; len < a.length; len++)
x4[len] = -1;
}
}
}
}
return dp(0, b - 1, 0, 1, 1, 0);
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
memo = new long[2][2][2][11][70];
int q = sc.nextInt();
while (q-- > 0) {
int b = sc.nextInt();
long l = sc.nextLong(), r = sc.nextLong();
out.println(solve(r, b) - solve(l - 1, b));
}
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();
}
}
static void sort(int[] a) {
shuffle(a);
Arrays.sort(a);
}
static void shuffle(int[] a) {
int n = a.length;
Random rand = new Random();
for (int i = 0; i < n; i++) {
int tmpIdx = rand.nextInt(n);
int tmp = a[i];
a[i] = a[tmpIdx];
a[tmpIdx] = tmp;
}
}
} | Java | ["2\n2 4 9\n3 1 10", "2\n2 1 100\n5 1 100"] | 2 seconds | ["1\n2", "21\n4"] | NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 2df506710dfbc401e5c71ff7ae63746d | First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018). | 2,200 | You have to output q lines, each containing a single integer, the answer to the corresponding query. | standard output | |
PASSED | c9d7e962a143473e8ffd22896a4a1bf2 | train_004.jsonl | 1506263700 | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
dp = new Long[2][11][64][1<<10];
int q = scan.nextInt();
for(int qq = 0; qq < q; qq++) {
b = scan.nextInt();
long l = scan.nextLong()-1, r = scan.nextLong();
System.out.println(solve(r)-solve(l));
}
}
static int b;
static int[] num;
static Long[][][][] dp;
static long go(int at, int m, int mask, int z) {
if(at == num.length) return mask==0&&z==1?1:0;
if(dp[z][b][at][mask] != null && m == 0) return dp[z][b][at][mask];
long res = 0;
int lim = b-1;
if(m == 1) lim = num[at];
for(int i = 0; i <= lim; i++) {
int nmask = mask;
if(z == 1 || i != 0) nmask ^= 1<<i;
res += go(at+1, i==num[at]?m:0, nmask, i!=0?1:z);
}
if(m == 0) dp[z][b][at][mask] = res;
return res;
}
static long solve(long in) {
char[] a = Long.toString(in, b).toCharArray();
num = new int[64];
for(int i = 64-a.length, j = 0; i < 64; i++, j++) num[i] = a[j]-'0';
return go(0, 1, 0, 0);
}
} | Java | ["2\n2 4 9\n3 1 10", "2\n2 1 100\n5 1 100"] | 2 seconds | ["1\n2", "21\n4"] | NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 2df506710dfbc401e5c71ff7ae63746d | First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018). | 2,200 | You have to output q lines, each containing a single integer, the answer to the corresponding query. | standard output | |
PASSED | 87236c64a3af72ca60bd65caecb5b994 | train_004.jsonl | 1506263700 | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers. | 256 megabytes | import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.System.exit;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class E {
static long data[][][] = new long[11][][];
static {
for (int base = 2; base <= 10; base++) {
long cData[][] = data[base] = new long[64][];
for (int len = 0; len < 64; len++) {
long ccData[] = cData[len] = new long[len + 1];
if (len == 0) {
ccData[0] = 1;
} else {
for (int cnt = len % 2; cnt <= len && cnt <= base; cnt += 2) {
long v = 0;
if (cnt > 0) {
v = cnt * cData[len - 1][cnt - 1];
}
if (cnt < base && cnt < len) {
v += (base - cnt) * cData[len - 1][cnt + 1];
}
ccData[cnt] = v;
}
}
}
}
}
static long get(int b, long l) {
int cnt = 0;
long pow = 1;
long ans = 0;
while (true) {
if (pow * b / b != pow || pow * b > l) {
break;
}
// System.err.println("Q1 " + cnt + " " + 1);
if (cnt >= 1) {
ans += (b - 1) * data[b][cnt][1];
}
pow *= b;
++cnt;
}
int set = 0;
boolean init = true;
while (cnt >= 0) {
for (int i = init ? 1 : 0; i < l / pow; i++) {
set ^= 1 << i;
int c = Integer.bitCount(set);
// System.err.println("Q2 " + cnt + " " + c);
if (c <= cnt) {
ans += data[b][cnt][c];
}
set ^= 1 << i;
}
int i = (int) (l / pow);
// System.err.println("P " + cnt + " " + i);
set ^= 1 << i;
l -= i * pow;
pow /= b;
--cnt;
init = false;
}
return ans;
}
static void solve() throws Exception {
int q = scanInt();
// int q = 100000;
for (int qq = 0; qq < q; qq++) {
int b = scanInt();
long l = scanLong();
long r = scanLong();
// int b = 2;
// long l = 1000000000000000000L, r = 1000000000000000000L;
out.println(get(b, r + 1) - get(b, l));
}
}
static int scanInt() throws IOException {
return parseInt(scanString());
}
static long scanLong() throws IOException {
return parseLong(scanString());
}
static String scanString() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
static BufferedReader in;
static PrintWriter out;
static StringTokenizer tok;
public static void main(String[] args) {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
exit(1);
}
}
} | Java | ["2\n2 4 9\n3 1 10", "2\n2 1 100\n5 1 100"] | 2 seconds | ["1\n2", "21\n4"] | NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 2df506710dfbc401e5c71ff7ae63746d | First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018). | 2,200 | You have to output q lines, each containing a single integer, the answer to the corresponding query. | standard output | |
PASSED | f131b78ef0398a21a957da34b5d7e7ad | train_004.jsonl | 1506263700 | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers. | 256 megabytes | import java.io.*;
import java.util.*;
public class slither {
public static void main(String[] args) {
FastScanner scan=new FastScanner();
PrintWriter out=new PrintWriter(System.out);
dp=new long[64][11][2][1<<10];
for(long[][][] d:dp) for(long[][] dd:d) for(long[] ddd:dd) Arrays.fill(ddd,-1);
int t=scan.nextInt();
for(int tt=0;tt<t;tt++) {
b=scan.nextInt();
long x=scan.nextLong(), y=scan.nextLong();
l=Long.toString(x-1,b);
r=Long.toString(y,b);
long l1=go(conv(r),0,0,0,0);
// System.out.println("nxt");
long l2=go(conv(l),0,0,0,0);
// System.out.println(l1+" "+l2);
out.println(l1-l2);
}
out.close();
}
public static int[] conv(String x) {
int[] res=new int[64];
for(int i=63;i>=0&&x.length()-(64-i)>=0;i--) {
res[i]=(int)(x.charAt(x.length()-(64-i))-'0');
}
return res;
}
static int b;
public static long go(int[] num, int at, int lower, int start, int mask) {
if(at==num.length) {
return mask==0L&&start==1?1L:0L;
}
if(dp[at][b][start][mask]!=-1&&lower==1) {
return dp[at][b][start][mask];
}
long res=0L;
int end=b-1;
if(lower==0) end=num[at];
for(int i=0;i<=end;i++) {
int nstart=start;
if(i>0) nstart=1;
int nlower=lower;
if(i<end) nlower=1;
int nmask=mask;
if(nstart==1) nmask^=(1<<i);
res+=go(num,at+1,nlower,nstart,nmask);
}
if(lower==1) dp[at][b][start][mask]=res;
return res;
}
static long[][][][] dp;
static String l,r;
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
return st.nextToken();
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
public String nextLine() {
String line = "";
if(st.hasMoreTokens()) line = st.nextToken();
else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
while(st.hasMoreTokens()) line += " "+st.nextToken();
return line;
}
}
} | Java | ["2\n2 4 9\n3 1 10", "2\n2 1 100\n5 1 100"] | 2 seconds | ["1\n2", "21\n4"] | NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 2df506710dfbc401e5c71ff7ae63746d | First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018). | 2,200 | You have to output q lines, each containing a single integer, the answer to the corresponding query. | standard output | |
PASSED | df9884d0be8bab93c0fedc01e198a8da | train_004.jsonl | 1506263700 | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.io.Writer;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Niyaz Nigmatullin
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
static class TaskE {
static final int MAXN = 62;
static long[][][] dp = new long[11][][];
static long solve(int b, long n) {
if (n == 0) {
return 0;
}
int[] d = new int[MAXN];
int cn = 0;
while (n > 0) {
d[cn++] = (int) (n % b);
n /= b;
}
long ans = 0;
int curMask = 0;
long[][] f = dp[b];
for (int length = 1; length < cn; length++) {
for (int first = 1; first < b; first++) {
ans += f[length - 1][1 << first];
}
}
for (int i = cn - 1; i >= 0; i--) {
for (int cur = 0; cur < d[i]; cur++) {
if (i == cn - 1 && cur == 0) continue;
ans += f[i][curMask ^ (1 << cur)];
}
curMask ^= 1 << d[i];
}
return ans;
}
public void solve(int testNumber, FastScanner in, FastPrinter out) {
for (int digits = 2; digits <= 10; digits++) {
long[][] f = new long[MAXN][1 << digits];
f[0][0] = 1;
long N = 1000000000000000000L;
int log = 0;
while (N > 0) {
N /= digits;
log++;
}
for (int i = 0; i < log; i++) {
for (int mask = 0; mask < 1 << digits; mask++) {
long value = f[i][mask];
if (value == 0) continue;
for (int d = 0; d < digits; d++) {
f[i + 1][mask ^ (1 << d)] += f[i][mask];
}
}
}
dp[digits] = f;
}
int q = in.nextInt();
for (int i = 0; i < q; i++) {
int b = in.nextInt();
long l = in.nextLong();
long r = in.nextLong();
out.println(solve(b, r + 1) - solve(b, l));
}
}
}
static class FastScanner extends BufferedReader {
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
// if (isEOF && ret < 0) {
// throw new InputMismatchException();
// }
// isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
static boolean isWhiteSpace(int c) {
return c >= 0 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (c >= 0 && !isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c
+ " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
public long nextLong() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long ret = 0;
while (c >= 0 && !isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c + " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
public String readLine() {
try {
return super.readLine();
} catch (IOException e) {
return null;
}
}
}
static class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
public FastPrinter(Writer out) {
super(out);
}
}
}
| Java | ["2\n2 4 9\n3 1 10", "2\n2 1 100\n5 1 100"] | 2 seconds | ["1\n2", "21\n4"] | NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 2df506710dfbc401e5c71ff7ae63746d | First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018). | 2,200 | You have to output q lines, each containing a single integer, the answer to the corresponding query. | standard output | |
PASSED | d19810987696776786b4cb71cae3b745 | train_004.jsonl | 1506263700 | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class P855E
{
static long[][][] dp;
static char[] num;
static int offset;
public static void main(String[] args)
{
dp = new long[11][64][1 << 10];
for (long[][] a : dp)
for (long[] b : a)
Arrays.fill(b, -1);
FastScanner scan = new FastScanner();
int q = scan.nextInt();
for (int i = 0; i < q; i++)
{
int b = scan.nextInt();
long lo = scan.nextLong();
long hi = scan.nextLong();
System.out.println(count(hi, b) - count(lo-1, b));
}
}
private static long count(long n, int b)
{
num = Long.toString(n, b).toCharArray();
offset = dp[b].length-num.length;
return count(b, offset, false, 0, true);
}
private static long count(int b, int ind, boolean start, int mask, boolean bound)
{
if (ind == dp[b].length)
return mask == 0 ? 1 : 0;
if (!bound && start && dp[b][ind][mask] >= 0)
return dp[b][ind][mask];
long ans = 0;
int max = bound ? num[ind-offset]-'0' : b-1;
for (int i = 0; i <= max; i++)
{
boolean newStart = start || i > 0;
ans += count(b, ind+1, newStart, newStart ? mask ^ (1 << i) : mask, bound && i == max);
}
if (start && !bound)
dp[b][ind][mask] = ans;
return ans;
}
static class FastScanner
{
BufferedReader r;
StringTokenizer t;
FastScanner()
{
r = new BufferedReader(new InputStreamReader(System.in));
t = new StringTokenizer("");
}
String next()
{
while (!t.hasMoreElements())
try
{
t = new StringTokenizer(r.readLine());
} catch (IOException e)
{
e.printStackTrace();
}
return t.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
}
}
| Java | ["2\n2 4 9\n3 1 10", "2\n2 1 100\n5 1 100"] | 2 seconds | ["1\n2", "21\n4"] | NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 2df506710dfbc401e5c71ff7ae63746d | First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018). | 2,200 | You have to output q lines, each containing a single integer, the answer to the corresponding query. | standard output | |
PASSED | 0f50427091582729d42b66faf689d3a7 | train_004.jsonl | 1506263700 | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers. | 256 megabytes | import java.util.*;
import java.io.*;
public class E {
int MAX_B = 10;
int MAX_LEN = 60;
long[][][] dp = new long[MAX_B + 1][][];
void precalc() {
for (int b = 2; b <= MAX_B; b++) {
dp[b] = new long[MAX_LEN + 1][1 << b];
dp[b][0][0] = 1;
for (int l = 0; l < MAX_LEN; l++) {
for (int mask = 0; mask < 1 << b; mask++) {
for (int digit = 0; digit < b; digit++) {
dp[b][l + 1][mask ^ (1 << digit)] += dp[b][l][mask];
}
}
}
}
}
long get(long r, int b) {
if (r == 0) {
return 0;
}
List<Integer> list = new ArrayList<>();
while (r > 0) {
list.add((int) (r % b));
r /= b;
}
long result = 0;
for (int l = 1; l < list.size(); l++) {
for (int digit = 1; digit < b; digit++) {
result += dp[b][l - 1][1 << digit];
}
}
int curMask =0 ;
for (int pos = list.size() - 1; pos >= 0; pos--) {
for (int digit = 0; digit < list.get(pos); digit++) {
if (digit == 0 && pos == list.size() - 1) {
continue;
}
result += dp[b][pos][curMask ^ (1 << digit)];
}
curMask ^= 1 << list.get(pos);
}
if (curMask == 0) {
result++;
}
return result;
}
void solve() {
int q = in.nextInt();
precalc();
for (int i = 0; i < q; i++) {
int b = in.nextInt();
long l = in.nextLong(), r = in.nextLong();
out.println(get(r, b) - get(l - 1, b));
}
}
FastScanner in;
PrintWriter out;
void run() {
in = new FastScanner();
out = new PrintWriter(System.out);
solve();
out.close();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
public static void main(String[] args) {
new E().run();
}
}
| Java | ["2\n2 4 9\n3 1 10", "2\n2 1 100\n5 1 100"] | 2 seconds | ["1\n2", "21\n4"] | NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 2df506710dfbc401e5c71ff7ae63746d | First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018). | 2,200 | You have to output q lines, each containing a single integer, the answer to the corresponding query. | standard output | |
PASSED | f7f0c0a716704d1e06ef53600a8c3c28 | train_004.jsonl | 1506263700 | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers. | 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.Random;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;
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;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
static class TaskE {
final int N = 100;
long[][] C = new long[N][N];
boolean[][][][] was = new boolean[2][11][66][1 << 10];
long[][][][] dp = new long[2][11][66][1 << 10];
public void solve(int testNumber, FastScanner in, PrintWriter out) {
C[0][0] = 1;
for (int i = 1; i < N; i++) {
C[i][0] = 1;
for (int j = 1; j < N; j++) {
C[i][j] = C[i - 1][j] + C[i - 1][j - 1];
}
}
boolean stress = false;
if (stress) {
Random random = new Random(0);
for (int i = 0; i < (int) 1e5; i++) {
int b = random.nextInt(9) + 2;
long r = (long) 1e18 - random.nextInt(1000000);
long l = (long) 1e18 - random.nextInt(1000000);
solve(b, l);
solve(b, r);
if (i < (int) 1e3) {
b = 10;
r = random.nextInt((int) 1e4);
long u = solve(b, r);
long v = dummy(b, r);
if (u != v) {
throw new AssertionError(b + " " + r + " " + u + " " + v);
}
}
}
}
int numQueries = in.nextInt();
for (int queryId = 0; queryId < numQueries; queryId++) {
int b = in.nextInt();
long l = in.nextLong();
long r = in.nextLong();
out.println(solve(b, r) - solve(b, l - 1));
}
}
private long solve(int b, long r) {
if (r == 0) {
return 1;
}
int[] digits = getDigits(b, r);
int n = digits.length;
long res = 1;
for (int numberLen = 1; numberLen < n; numberLen++) {
res += calc(b, numberLen, 0, 0);
}
// number len equals n
for (int prefLen = 0; prefLen <= n; prefLen++) {
int mask = 0;
for (int i = 0; i < prefLen; i++) {
mask ^= 1 << digits[n - i - 1];
}
if (prefLen == n) {
res += calc(b, 0, mask, 1);
continue;
}
for (int last = 0; last < digits[n - prefLen - 1]; last++) {
if (last == 0 && prefLen == 0) {
continue;
}
mask ^= 1 << last;
res += calc(b, n - prefLen - 1, mask, 1);
mask ^= 1 << last;
}
}
return res;
}
private long calc(int base, int n, int mask, int leadingZeroAllowed) {
if (n == 0) {
return mask == 0 ? 1 : 0;
}
if (was[leadingZeroAllowed][base][n][mask]) {
return dp[leadingZeroAllowed][base][n][mask];
}
was[leadingZeroAllowed][base][n][mask] = true;
long[] d = new long[n + 1];
long[] nd = new long[n + 1];
d[0] = 1;
for (int digit = 0; digit < base; digit++) {
Arrays.fill(nd, 0);
for (int old = 0; old <= n; old++) {
if (d[old] == 0) {
continue;
}
for (int here = 0; here + old <= n; here++) {
if (here % 2 != ((mask >> digit) & 1)) {
continue;
}
long ways = C[n - old][here];
if (leadingZeroAllowed == 0 && digit == 0) {
ways = C[n - 1][here];
}
nd[old + here] += d[old] * ways;
}
}
long[] t = d;
d = nd;
nd = t;
}
dp[leadingZeroAllowed][base][n][mask] = d[n];
return d[n];
}
private int[] getDigits(int b, long r) {
int n = 0;
long x = r;
while (x > 0) {
x /= b;
++n;
}
int[] digits = new int[n];
n = 0;
x = r;
while (x > 0) {
digits[n] = (int) (x % b);
x /= b;
++n;
}
return digits;
}
private long dummy(int b, long r) {
int res = 1; // zero
for (int i = 1; i <= r; i++) {
int[] d = getDigits(b, i);
int mask = 0;
for (int j = 0; j < d.length; j++) {
mask ^= 1 << d[j];
}
if (mask == 0) {
++res;
}
}
return res;
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["2\n2 4 9\n3 1 10", "2\n2 1 100\n5 1 100"] | 2 seconds | ["1\n2", "21\n4"] | NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 2df506710dfbc401e5c71ff7ae63746d | First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018). | 2,200 | You have to output q lines, each containing a single integer, the answer to the corresponding query. | standard output | |
PASSED | b672a60cedaaa25efc5a88a561ae8f91 | train_004.jsonl | 1506263700 | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers. | 256 megabytes | //package manthan2017;
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 E {
InputStream is;
PrintWriter out;
String INPUT = "";
long[][][] hdps = new long[11][61][];
long[][][] dps = new long[11][61][];
void solve()
{
for(int b = 2;b <= 10;b++){
long[] dp = new long[1<<b];
dp[0] = 1;
dps[b][0] = dp;
for(int i = 1;i <= 60;i++){
long[] pdp = new long[1<<b];
for(int j = 0;j < 1<<b;j++){
for(int k = 1;k < b;k++){
pdp[j^1<<k] += dp[j];
}
}
hdps[b][i] = pdp;
long[] ndp = new long[1<<b];
for(int j = 0;j < 1<<b;j++){
for(int k = 0;k < b;k++){
ndp[j^1<<k] += dp[j];
}
}
dps[b][i] = ndp;
dp = ndp;
}
}
for(int Q = ni();Q > 0;Q--){
int b = ni();
long L = nl(), R = nl();
out.println(count(R, b) - count(L-1, b));
}
}
long count(long n, int b)
{
char[] s = Long.toString(n, b).toCharArray();
long ans = 0;
int ptn = 0;
for(int i = 0;i < s.length;i++){
int v = s[i]-'0';
for(int j = i == 0 ? 1 : 0;j < v;j++){
ans += dps[b][s.length-1-i][ptn^1<<j];
}
ptn ^= 1<<v;
}
if(ptn == 0)ans++;
for(int i = 1;i < s.length;i++){
ans += hdps[b][i][0];
}
return ans;
}
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 E().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 | ["2\n2 4 9\n3 1 10", "2\n2 1 100\n5 1 100"] | 2 seconds | ["1\n2", "21\n4"] | NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 2df506710dfbc401e5c71ff7ae63746d | First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018). | 2,200 | You have to output q lines, each containing a single integer, the answer to the corresponding query. | standard output | |
PASSED | aa0bea814d96dc89150b4af1cec8f2ff | train_004.jsonl | 1506263700 | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers. | 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.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
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 {
public long[][][] count;
public long solve(int base, int digits, int ones) {
if (digits == 0) return ones == 0 ? 1 : 0;
if (count[base][digits][ones] != -1) return count[base][digits][ones];
long ret = 0;
if (ones > 0) ret += ones * solve(base, digits - 1, ones - 1);
if (ones < base) ret += (base - ones) * solve(base, digits - 1, ones + 1);
return count[base][digits][ones] = ret;
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
int q = in.nextInt();
count = new long[11][61][11];
for (long[][] x : count) for (long[] y : x) Arrays.fill(y, -1);
while (q-- > 0) {
int base = in.nextInt();
char[] s = Long.toString(in.nextLong(), base).toCharArray();
char[] t = Long.toString(in.nextLong() + 1, base).toCharArray();
out.println(solve(t, base) - solve(s, base));
}
}
public long solve(char[] s, int base) {
long ret = 0;
int[] counts = new int[base];
int odd = 0;
if (s.length % 2 == 0) {
for (int pref = 0; pref < s.length; pref++) {
for (int dig = (pref == 0 ? 1 : 0); dig < s[pref] - '0'; dig++) {
counts[dig]++;
if (counts[dig] % 2 == 1) odd++;
else odd--;
ret += solve(base, s.length - pref - 1, odd);
counts[dig]--;
if (counts[dig] % 2 == 1) odd++;
else odd--;
}
counts[s[pref] - '0']++;
if (counts[s[pref] - '0'] % 2 == 1) odd++;
else odd--;
}
}
for (int lead = 1; lead < s.length; lead++) {
ret += (base - 1) * solve(base, s.length - lead - 1, 1);
}
return ret;
}
}
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 println(long i) {
writer.println(i);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
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 long nextLong() {
int c;
for (c = this.read(); isSpaceChar(c); c = this.read()) {
;
}
byte sgn = 1;
if (c == 45) {
sgn = -1;
c = this.read();
}
long res = 0L;
while (c >= 48 && c <= 57) {
res *= 10L;
res += (long) (c - 48);
c = this.read();
if (isSpaceChar(c)) {
return res * (long) sgn;
}
}
throw new InputMismatchException();
}
public static boolean isSpaceChar(int c) {
return c == 32 || c == 10 || c == 13 || c == 9 || c == -1;
}
}
}
| Java | ["2\n2 4 9\n3 1 10", "2\n2 1 100\n5 1 100"] | 2 seconds | ["1\n2", "21\n4"] | NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 2df506710dfbc401e5c71ff7ae63746d | First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018). | 2,200 | You have to output q lines, each containing a single integer, the answer to the corresponding query. | standard output | |
PASSED | ffb58bc3a2a74fbb2f25e5501a8bfaea | train_004.jsonl | 1506263700 | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers. | 256 megabytes | import java.io.*;
import java.util.*;
public class E {
static final int MAX_B = 11;
static final int MAX_LEN = 70;
long go(int base, long x) {
char[] s = Long.toString(x, base).toCharArray();
long ret = 0;
for (int len = 1; len < s.length; len++) {
ret += (base - 1) * f[base][len - 1][1];
}
int maskOdd = 0;
for (int i = 0; i < s.length; i++) {
int dig = s[i] - '0';
int from = i == 0 ? 1 : 0;
for (int j = from; j < dig; j++) {
maskOdd ^= (1 << j);
ret += f[base][s.length - 1 - i][Integer.bitCount(maskOdd)];
maskOdd ^= (1 << j);
}
maskOdd ^= (1 << dig);
}
return ret;
}
void submit() {
int q = nextInt();
while (q-- > 0) {
int b = nextInt();
long l = nextLong();
long r = nextLong();
out.println(go(b, r + 1) - go(b, l));
}
}
long[][][] f;
void preCalc() {
f = new long[MAX_B][MAX_LEN][];
for (int base = 2; base < MAX_B; base++) {
for (int len = 0; len < MAX_LEN; len++) {
f[base][len] = new long[base + 1];
if (len == 0) {
f[base][len][0] = 1;
continue;
}
for (int odd = 0; odd <= base; odd++) {
if (odd > 0) {
f[base][len][odd] += f[base][len - 1][odd - 1] * odd;
}
if (odd < base) {
f[base][len][odd] += f[base][len - 1][odd + 1]
* (base - odd);
}
}
}
}
}
void stress() {
}
void test() {
System.err.println(go(2, 3));
}
E() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
preCalc();
submit();
// stress();
// test();
out.close();
}
static final Random rng = new Random();
static int rand(int l, int r) {
return l + rng.nextInt(r - l + 1);
}
public static void main(String[] args) throws IOException {
new E();
}
BufferedReader br;
PrintWriter out;
StringTokenizer st;
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
String nextString() {
try {
return br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
| Java | ["2\n2 4 9\n3 1 10", "2\n2 1 100\n5 1 100"] | 2 seconds | ["1\n2", "21\n4"] | NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 2df506710dfbc401e5c71ff7ae63746d | First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018). | 2,200 | You have to output q lines, each containing a single integer, the answer to the corresponding query. | standard output | |
PASSED | f8898b8794b21bfd6e4e4c02a408f62e | train_004.jsonl | 1506263700 | Harry came to know from Dumbledore that Salazar Slytherin's locket is a horcrux. This locket was present earlier at 12 Grimmauld Place, the home of Sirius Black's mother. It was stolen from there and is now present in the Ministry of Magic in the office of Dolorous Umbridge, Harry's former Defense Against the Dark Arts teacher. Harry, Ron and Hermione are infiltrating the Ministry. Upon reaching Umbridge's office, they observed a code lock with a puzzle asking them to calculate count of magic numbers between two integers l and r (both inclusive). Harry remembered from his detention time with Umbridge that she defined a magic number as a number which when converted to a given base b, all the digits from 0 to b - 1 appear even number of times in its representation without any leading zeros.You have to answer q queries to unlock the office. Each query has three integers bi, li and ri, the base and the range for which you have to find the count of magic numbers. | 256 megabytes | import java.lang.*;
import java.lang.reflect.Array;
import java.math.*;
import java.util.*;
import java.io.*;
public class Main {
void solve() {
int q=ni();
dp=new long[11][60][1<<10][2];
for(int i=0;i<11;i++) for(int j=0;j<60;j++) for(int k=0;k<(1<<10);k++) Arrays.fill(dp[i][j][k],-1);
while(q-->0){
int b=ni(); long l=nl(),r=nl();
long ans=solve(r,b)- solve(l-1,b);
pw.println(ans);
}
}
long dp[][][][];
long solve(long num,int b){
a=convert(num,b);
int n=a.length;
long ans=go(0,0,1,n,b,1);
// pw.println(ans);
return ans;
}
int a[];
long go(int i,int mask,int t,int n,int b,int l){
if(i>=n){
if(mask==0 && l!=1) return 1;
else return 0;
}
if(t==0 && l!=1 && dp[b][i][mask][t]!=-1) {
// pw.print(i+" "+mask+" "+dp[b][i][mask][t]+" ");
return dp[b][i][mask][t];
}
long cc=0;
int ed=b-1;
if(t==1) ed=a[i];
for(int j=0;j<=ed;j++){
int nmask=mask,nl=l;
if(!(l==1 && j==0)) {
nmask ^= (1 << j);
nl=0;
}
cc+=go(i+1,nmask,(t==1 && j==ed)?1:0,n,b,nl);
}
// if(t==0 && dp[b][i][mask][t]!=-1) pw.println(i+" "+mask+" "+dp[b][i][mask][t]+" "+cc);
//if(i==58 && mask==0 && t==0) pw.println(dp[b][i][mask][t]+" "+cc);
if(l!=1)
dp[b][i][mask][t]=cc;
return cc;
}
int [] convert(long n,int b){
int a[]=new int[60];
int id=59;
while(n>0){
a[id--]=(int)(n%b);
n/=b;
}
return a;
}
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 | ["2\n2 4 9\n3 1 10", "2\n2 1 100\n5 1 100"] | 2 seconds | ["1\n2", "21\n4"] | NoteIn sample test case 1, for first query, when we convert numbers 4 to 9 into base 2, we get: 4 = 1002, 5 = 1012, 6 = 1102, 7 = 1112, 8 = 10002, 9 = 10012. Out of these, only base 2 representation of 9 has even number of 1 and 0. Thus, the answer is 1. | Java 8 | standard input | [
"dp",
"bitmasks"
] | 2df506710dfbc401e5c71ff7ae63746d | First line of input contains q (1 ≤ q ≤ 105) — number of queries. Each of the next q lines contain three space separated integers bi, li, ri (2 ≤ bi ≤ 10, 1 ≤ li ≤ ri ≤ 1018). | 2,200 | You have to output q lines, each containing a single integer, the answer to the corresponding query. | standard output | |
PASSED | 82d047334a971455c9d1b919c646b1f1 | train_004.jsonl | 1323443100 | Little Petya very much likes rectangular tables that consist of characters "0" and "1". Recently he has received one such table as a gift from his mother. The table contained n rows and m columns. The rows are numbered from top to bottom from 1 to n, the columns are numbered from the left to the right from 1 to m. Petya immediately decided to find the longest cool cycle whatever it takes.A cycle is a sequence of pairwise distinct cells where each two consecutive cells have a common side; besides, the first cell has a common side with the last cell. A cycle is called cool if it fulfills all the following conditions simultaneously: The cycle entirely consists of the cells that contain "1". Each cell that belongs to the cycle, has a common side with exactly two other cells that belong to the cycle. Each cell of the table that contains "1" either belongs to the cycle or is positioned outside of it (see definition below). To define the notion of "outside" formally, let's draw a cycle on a plane. Let each cell of the cycle (i, j) (i is the row number, j is the column number) correspond to the point (i, j) on the coordinate plane. Let a straight line segment join each pair of points that correspond to the cells belonging to the cycle and sharing a side. Thus, we will get a closed polyline that has no self-intersections and self-touches. The polyline divides the plane into two connected parts: the part of an infinite area and the part of a finite area. It is considered that cell (r, c) lies outside of the cycle if it does not belong to the cycle and the corresponding point on the plane with coordinates (r, c) lies in the part with the infinite area.Help Petya to find the length of the longest cool cycle in the table. The cycle length is defined as the number of cells that belong to the cycle. | 256 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author AlexFetisov
*/
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
int n, m;
boolean[][] f;
boolean[][] used;
int[][] color;
int[][] found;
int curColor;
int rx, ry;
int count;
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt();
m = in.nextInt();
f = new boolean[n][m];
for (int i = 0; i < n; ++i) {
char[] c = in.nextString().toCharArray();
for (int j = 0; j < m; ++j) {
if (c[j] == '1') {
f[i][j] = true;
} else {
f[i][j] = false;
}
}
}
int best = 0;
for (int i = 0; i < n - 1; ++i) {
for (int j = 0; j < m - 1; ++j) {
if (f[i][j] && f[i + 1][j + 1] && f[i + 1][j] && f[i][j + 1]) {
best = 4;
}
}
}
used = new boolean[n][m];
color = new int[n][m];
found = new int[n][m];
curColor = 1;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (!f[i][j]) {
++curColor;
rx = -1;
count = 0;
if (dfs(i, j)) {
int memo = count;
count = 0;
if (rx == -1) continue;
if (dfs2(rx, ry)) {
if (count == memo) {
best = Math.max(best, count);
}
}
}
}
}
}
out.println(best);
}
private boolean dfs2(int x, int y) {
++count;
found[x][y] = curColor;
int nei = 0;
for (int d = 0; d < 4; ++d) {
int nx = x + dx[d];
int ny = y + dy[d];
if (isValid(nx, ny) && color[nx][ny] == curColor) {
++nei;
}
}
if (nei != 2) return false;
for (int d = 0; d < 4; ++d) {
int nx = x + dx[d];
int ny = y + dy[d];
if (isValid(nx, ny) && found[nx][ny] != curColor && color[nx][ny] == curColor) {
return dfs2(nx, ny);
}
}
return true;
}
private boolean isValid(int x, int y) {
return x >= 0 && y >= 0 && x < n && y < m;
}
private boolean dfs(int x, int y) {
if (x < 0 || y < 0 || x >= n || y >= m) {
return false;
}
if (used[x][y]) {
return true;
}
if (color[x][y] == curColor) {
return true;
}
if (f[x][y]) {
++count;
rx = x;
ry = y;
color[x][y] = curColor;
return true;
}
used[x][y] = true;
for (int dx = -1; dx <= 1; ++dx) {
for (int dy = -1; dy <= 1; ++dy) {
if (dx == 0 && dy == 0) continue;
int nx = x + dx;
int ny = y + dy;
if (!dfs(nx, ny)) {
return false;
}
}
}
return true;
}
int[] dx = new int[]{1, 0, -1, 0};
int[] dy = new int[]{0, 1, 0, -1};
}
class InputReader {
private BufferedReader reader;
private StringTokenizer stt;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
return null;
}
}
public String nextString() {
while (stt == null || !stt.hasMoreTokens()) {
stt = new StringTokenizer(nextLine());
}
return stt.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextString());
}
}
| Java | ["3 3\n111\n101\n111", "5 5\n01010\n10101\n01010\n10101\n01010", "7 7\n1111111\n1000101\n1000101\n1000101\n1000111\n1000001\n1111111", "5 5\n11111\n10001\n10101\n10001\n11111"] | 3 seconds | ["8", "0", "24", "0"] | NoteIn the first example there's only one cycle and it is cool.In the second sample there's no cycle at all.In the third sample there are two cool cycles: their lengths are 12 and 24.In the fourth sample there also is only one cycle but it isn't cool as there's a cell containing "1" inside this cycle. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force"
] | 26909af720a7b1fbd247e61af6054174 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the table, respectively. Each of the following n lines contains m characters. Each character can be either "0" or "1". | 2,500 | Print a single number — the length of the longest cool cycle in the table. If such cycles do not exist, print 0. | standard output | |
PASSED | 51e778328dae77835b6f87947766fb42 | train_004.jsonl | 1323443100 | Little Petya very much likes rectangular tables that consist of characters "0" and "1". Recently he has received one such table as a gift from his mother. The table contained n rows and m columns. The rows are numbered from top to bottom from 1 to n, the columns are numbered from the left to the right from 1 to m. Petya immediately decided to find the longest cool cycle whatever it takes.A cycle is a sequence of pairwise distinct cells where each two consecutive cells have a common side; besides, the first cell has a common side with the last cell. A cycle is called cool if it fulfills all the following conditions simultaneously: The cycle entirely consists of the cells that contain "1". Each cell that belongs to the cycle, has a common side with exactly two other cells that belong to the cycle. Each cell of the table that contains "1" either belongs to the cycle or is positioned outside of it (see definition below). To define the notion of "outside" formally, let's draw a cycle on a plane. Let each cell of the cycle (i, j) (i is the row number, j is the column number) correspond to the point (i, j) on the coordinate plane. Let a straight line segment join each pair of points that correspond to the cells belonging to the cycle and sharing a side. Thus, we will get a closed polyline that has no self-intersections and self-touches. The polyline divides the plane into two connected parts: the part of an infinite area and the part of a finite area. It is considered that cell (r, c) lies outside of the cycle if it does not belong to the cycle and the corresponding point on the plane with coordinates (r, c) lies in the part with the infinite area.Help Petya to find the length of the longest cool cycle in the table. The cycle length is defined as the number of cells that belong to the cycle. | 256 megabytes | import java.io.*;
import java.util.*;
public class D
{
private static ArrayList<int []> borders;
private static final int [] dx = new int[] {-1,-1,-1, 0, 0, 1, 1, 1};
private static final int [] dy = new int[] { 1, 0,-1, 1,-1, 1, 0,-1};
private static boolean [][] visited;
private static char [][] map;
private static boolean bad;
public static void main(String[] strings) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out));
StringTokenizer tokenizer = new StringTokenizer(reader.readLine());
int n = Integer.parseInt(tokenizer.nextToken());
int m = Integer.parseInt(tokenizer.nextToken());
map = new char[n][m];
for(int i = 0 ; i < n ; i++)
map[i] = reader.readLine().toCharArray();
borders = new ArrayList<int[]>();
visited = new boolean[n][m];
int [][] neighbours = new int[n][m];
int res = 0;
for(int i = 0 ; i < n ; i++)
for(int j = 0 ; j < m ; j++)
if(map[i][j] == '0')
if(!visited[i][j])
{
bad = false;
bfsBuild(i, j);
if(!borders.isEmpty() && !bad)
{
for(int [] pos : borders)
for(int d = 0 ; d < dx.length ; d++)
if(dx[d]*dy[d] == 0)
{
int tx = pos[0] + dx[d];
int ty = pos[1] + dy[d];
if(tx < 0 || ty < 0 || tx >= map.length || ty >= map[0].length)
continue;
if(map[tx][ty] == '0')
continue;
if(!visited[tx][ty])
continue;
neighbours[pos[0]][pos[1]]++;
}
bfsCheck(borders.get(0)[0], borders.get(0)[1]);
boolean valid = true;
for(int [] pos : borders)
{
if(visited[pos[0]][pos[1]])
valid = false;
if(neighbours[pos[0]][pos[1]] != 2)
valid = false;
neighbours[pos[0]][pos[1]] = 0;
}
if(valid)
res = Math.max(res, borders.size());
}
for(int [] pos : borders)
{
visited[pos[0]][pos[1]] = false;
}
borders.clear();
}
for(int i = 0 ; i < n-1 ; i++)
for(int j = 0 ; j < m-1 ; j++)
if(map[i][j] + map[i][j+1] + map[i+1][j] + map[i+1][j+1] == 4*'1')
res = Math.max(res, 4);
System.out.println(res);
}
private static void bfsCheck(int sx, int sy)
{
Queue<Integer> queue = new LinkedList<Integer>();
queue.offer(sx);
queue.offer(sy);
visited[sx][sy] = false;
while(!queue.isEmpty())
{
int ax = queue.poll();
int ay = queue.poll();
for(int d = 0 ; d < dx.length ; d++)
if(dx[d]*dy[d] == 0)
{
int tx = ax + dx[d];
int ty = ay + dy[d];
if(tx < 0 || ty < 0 || tx >= map.length || ty >= map[0].length)
continue;
if(map[tx][ty] == '0')
continue;
if(!visited[tx][ty])
continue;
visited[tx][ty] = false;
queue.offer(tx);
queue.offer(ty);
}
}
}
private static void bfsBuild(int sx, int sy)
{
Queue<Integer> queue = new LinkedList<Integer>();
queue.offer(sx);
queue.offer(sy);
visited[sx][sy] = true;
while(!queue.isEmpty())
{
int ax = queue.poll();
int ay = queue.poll();
for (int d = 0; d < dx.length; d++)
{
int tx = ax + dx[d];
int ty = ay + dy[d];
if (tx < 0 || ty < 0 || tx >= map.length || ty >= map[0].length)
{
bad = true;
continue;
}
if (map[tx][ty] == '0')
continue;
if (visited[tx][ty])
continue;
visited[tx][ty] = true;
borders.add(new int[]{tx, ty});
}
for (int d = 0; d < dx.length; d++)
{
int tx = ax + dx[d];
int ty = ay + dy[d];
if (tx < 0 || ty < 0 || tx >= map.length || ty >= map[0].length)
continue;
if (map[tx][ty] == '1')
continue;
if (visited[tx][ty])
continue;
visited[tx][ty] = true;
queue.offer(tx);
queue.offer(ty);
}
}
}
} | Java | ["3 3\n111\n101\n111", "5 5\n01010\n10101\n01010\n10101\n01010", "7 7\n1111111\n1000101\n1000101\n1000101\n1000111\n1000001\n1111111", "5 5\n11111\n10001\n10101\n10001\n11111"] | 3 seconds | ["8", "0", "24", "0"] | NoteIn the first example there's only one cycle and it is cool.In the second sample there's no cycle at all.In the third sample there are two cool cycles: their lengths are 12 and 24.In the fourth sample there also is only one cycle but it isn't cool as there's a cell containing "1" inside this cycle. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force"
] | 26909af720a7b1fbd247e61af6054174 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the table, respectively. Each of the following n lines contains m characters. Each character can be either "0" or "1". | 2,500 | Print a single number — the length of the longest cool cycle in the table. If such cycles do not exist, print 0. | standard output | |
PASSED | 40461bef409c08100964f948bb7e98b6 | train_004.jsonl | 1323443100 | Little Petya very much likes rectangular tables that consist of characters "0" and "1". Recently he has received one such table as a gift from his mother. The table contained n rows and m columns. The rows are numbered from top to bottom from 1 to n, the columns are numbered from the left to the right from 1 to m. Petya immediately decided to find the longest cool cycle whatever it takes.A cycle is a sequence of pairwise distinct cells where each two consecutive cells have a common side; besides, the first cell has a common side with the last cell. A cycle is called cool if it fulfills all the following conditions simultaneously: The cycle entirely consists of the cells that contain "1". Each cell that belongs to the cycle, has a common side with exactly two other cells that belong to the cycle. Each cell of the table that contains "1" either belongs to the cycle or is positioned outside of it (see definition below). To define the notion of "outside" formally, let's draw a cycle on a plane. Let each cell of the cycle (i, j) (i is the row number, j is the column number) correspond to the point (i, j) on the coordinate plane. Let a straight line segment join each pair of points that correspond to the cells belonging to the cycle and sharing a side. Thus, we will get a closed polyline that has no self-intersections and self-touches. The polyline divides the plane into two connected parts: the part of an infinite area and the part of a finite area. It is considered that cell (r, c) lies outside of the cycle if it does not belong to the cycle and the corresponding point on the plane with coordinates (r, c) lies in the part with the infinite area.Help Petya to find the length of the longest cool cycle in the table. The cycle length is defined as the number of cells that belong to the cycle. | 256 megabytes | // practice with rainboy
import java.io.*;
import java.util.*;
public class CF135D extends PrintWriter {
CF135D() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF135D o = new CF135D(); o.main(); o.flush();
}
int[] dsu;
int find(int i) {
return dsu[i] < 0 ? i : (dsu[i] = find(dsu[i]));
}
void join(int i, int j) {
i = find(i);
j = find(j);
if (i == j)
return;
if (dsu[i] > dsu[j])
dsu[i] = j;
else {
if (dsu[i] == dsu[j])
dsu[i]--;
dsu[j] = i;
}
}
int n, m;
byte[][] cc;
int[] ii, jj; int cnt;
boolean[][] used;
void dfs1(int i, int j) {
if (i < 0 || i >= n || j < 0 || j >= m || used[i][j])
return;
used[i][j] = true;
if (cc[i][j] == '1') {
ii[cnt] = i; jj[cnt] = j; cnt++;
return;
}
for (int i_ = i - 1; i_ <= i + 1; i_++)
for (int j_ = j - 1; j_ <= j + 1; j_++)
dfs1(i_, j_);
}
void dfs2(int i, int j) {
if (i < 0 || i >= n || j < 0 || j >= m || !used[i][j])
return;
used[i][j] = false;
for (int i_ = i - 1; i_ <= i + 1; i_++)
for (int j_ = j - 1; j_ <= j + 1; j_++)
dfs2(i_, j_);
}
void main() {
n = sc.nextInt();
m = sc.nextInt();
cc = new byte[n][];
for (int i = 0; i < n; i++)
cc[i] = sc.next().getBytes();
dsu = new int[n * m]; Arrays.fill(dsu, -1);
for (int i = 0; i < n; i++)
for (int j = 1; j < m; j++)
if (cc[i][j - 1] == cc[i][j])
join(i * m + j - 1, i * m + j);
for (int j = 0; j < m; j++)
for (int i = 1; i < n; i++)
if (cc[i - 1][j] == cc[i][j])
join((i - 1) * m + j, i * m + j);
for (int i = 1; i < n; i++)
for (int j = 1; j < m; j++) {
if (cc[i - 1][j - 1] == '0' && cc[i][j] == '0')
join((i - 1) * m + j - 1, i * m + j);
if (cc[i][j - 1] == '0' && cc[i - 1][j] == '0')
join(i * m + j - 1, (i - 1) * m + j);
}
boolean[] bad = new boolean[n * m];
for (int i = 0; i < n; i++) {
if (cc[i][0] == '0')
bad[find(i * m + 0)] = true;
if (cc[i][m - 1] == '0')
bad[find(i * m + m - 1)] = true;
}
for (int j = 0; j < m; j++) {
if (cc[0][j] == '0')
bad[find(0 * m + j)] = true;
if (cc[n - 1][j] == '0')
bad[find((n - 1) * m + j)] = true;
}
int[] aa = new int[n * m]; Arrays.fill(aa, -1);
for (int i = 0; i < n; i++)
for (int j = 1; j < m; j++)
if (cc[i][j - 1] != cc[i][j]) {
int h = find(i * m + j - 1), h_ = find(i * m + j);
if (cc[i][j] == '0') {
int tmp = h; h = h_; h_ = tmp;
}
if (aa[h] == -1)
aa[h] = h_;
else if (aa[h] != h_)
bad[h] = true;
}
for (int j = 0; j < m; j++)
for (int i = 1; i < n; i++)
if (cc[i - 1][j] != cc[i][j]) {
int h = find((i - 1) * m + j), h_ = find(i * m + j);
if (cc[i][j] == '0') {
int tmp = h; h = h_; h_ = tmp;
}
if (aa[h] == -1)
aa[h] = h_;
else if (aa[h] != h_)
bad[h] = true;
}
int ans = 0;
for (int j = 1; j < m; j++)
for (int i = 1; i < n; i++)
if (cc[i - 1][j - 1] == '1' && cc[i - 1][j] == '1' && cc[i][j - 1] == '1' && cc[i][j] == '1') {
ans = 4;
break;
}
ii = new int[n * m]; jj = new int[n * m];
used = new boolean[n][m];
for (int h = 0; h < n * m; h++)
if (dsu[h] < 0 && !bad[h]) {
cnt = 0;
dfs1(h / m, h % m);
boolean yes = true;
for (int g = 0; g < cnt; g++) {
int i = ii[g], j = jj[g], k = 0;
if (i > 0 && used[i - 1][j] && cc[i - 1][j] == '1')
k++;
if (i + 1 < n && used[i + 1][j] && cc[i + 1][j] == '1')
k++;
if (j > 0 && used[i][j - 1] && cc[i][j - 1] == '1')
k++;
if (j + 1 < m && used[i][j + 1] && cc[i][j + 1] == '1')
k++;
if (k != 2) {
yes = false;
break;
}
}
if (yes)
ans = Math.max(ans, cnt);
dfs2(h / m, h % m);
}
println(ans);
}
}
| Java | ["3 3\n111\n101\n111", "5 5\n01010\n10101\n01010\n10101\n01010", "7 7\n1111111\n1000101\n1000101\n1000101\n1000111\n1000001\n1111111", "5 5\n11111\n10001\n10101\n10001\n11111"] | 3 seconds | ["8", "0", "24", "0"] | NoteIn the first example there's only one cycle and it is cool.In the second sample there's no cycle at all.In the third sample there are two cool cycles: their lengths are 12 and 24.In the fourth sample there also is only one cycle but it isn't cool as there's a cell containing "1" inside this cycle. | Java 8 | standard input | [
"implementation",
"dfs and similar",
"brute force"
] | 26909af720a7b1fbd247e61af6054174 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the table, respectively. Each of the following n lines contains m characters. Each character can be either "0" or "1". | 2,500 | Print a single number — the length of the longest cool cycle in the table. If such cycles do not exist, print 0. | standard output | |
PASSED | 340aadcd34b64583445847f76265bdd3 | train_004.jsonl | 1323443100 | Little Petya very much likes rectangular tables that consist of characters "0" and "1". Recently he has received one such table as a gift from his mother. The table contained n rows and m columns. The rows are numbered from top to bottom from 1 to n, the columns are numbered from the left to the right from 1 to m. Petya immediately decided to find the longest cool cycle whatever it takes.A cycle is a sequence of pairwise distinct cells where each two consecutive cells have a common side; besides, the first cell has a common side with the last cell. A cycle is called cool if it fulfills all the following conditions simultaneously: The cycle entirely consists of the cells that contain "1". Each cell that belongs to the cycle, has a common side with exactly two other cells that belong to the cycle. Each cell of the table that contains "1" either belongs to the cycle or is positioned outside of it (see definition below). To define the notion of "outside" formally, let's draw a cycle on a plane. Let each cell of the cycle (i, j) (i is the row number, j is the column number) correspond to the point (i, j) on the coordinate plane. Let a straight line segment join each pair of points that correspond to the cells belonging to the cycle and sharing a side. Thus, we will get a closed polyline that has no self-intersections and self-touches. The polyline divides the plane into two connected parts: the part of an infinite area and the part of a finite area. It is considered that cell (r, c) lies outside of the cycle if it does not belong to the cycle and the corresponding point on the plane with coordinates (r, c) lies in the part with the infinite area.Help Petya to find the length of the longest cool cycle in the table. The cycle length is defined as the number of cells that belong to the cycle. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class D {
static final Scanner sc = new Scanner(System.in);
int n, m;
char[][] cs;
boolean[][] visited;
int[][] num, num2;
boolean inside(int x, int y) {
return 0 <= x && x < m && 0 <= y && y < n;
}
int bfs2(int x, int y, int val) {
s = t = 0;
q[t++] = x*1000+y;
num2[y][x] = val;
while(s != t) {
final int v = q[s++];
final int x_ = v/1000;
final int y_ = v%1000;
int cnt = 0;
for(int dy = -1; dy <= 1; dy++)
for(int dx = -1; dx <= 1; dx++) {
x = x_+dx;
y = y_+dy;
if(!inside(x, y) || num[y][x] != val) {
continue;
}
if(num2[y_][x_] != num2[y][x]) {
num2[y][x] = val;
q[t++] = x*1000+y;
}
if(dx*dy == 0) cnt++;
}
if(cnt != 3) {
return -1;
}
}
return t;
}
int res;
int[] q = new int[1000*1000];
int[] q2 = new int[1000*1000];
int s, t;
void bfs(int x, int y, int val) {
s = t = 0;
q[t++] = x*1000+y;
visited[y][x] = true;
int s0 = 0;
boolean bad = false;
while(s != t) {
final int v = q[s++];
final int x_ = v/1000;
final int y_ = v%1000;
// System.out.printf("%d: %d %d\n", val, x_, y_);
boolean ed = false;
for(int dy = -1; dy <= 1; dy++)
for(int dx = -1; dx <= 1; dx++) {
x = x_+dx;
y = y_+dy;
if(!inside(x, y)) {
bad = true;
// System.out.printf("%d %d: bad\n", x, y);
continue;
}
if(cs[y][x] == '1') {
ed = true;
} else if(!visited[y][x]) {
visited[y][x] = true;
q[t++] = x*1000+y;
}
}
if(ed) {
q2[s0++] = x_*1000+y_;
}
}
if(!bad) {
int cnt = 0;
int x_ = -1, y_ = -1;
for(int i = 0; i < s0; i++) {
x = q2[i]/1000;
y = q2[i]%1000;
for(int dy = -1; dy <= 1; dy++)
for(int dx = -1; dx <= 1; dx++) {
if(cs[y+dy][x+dx] == '1' && num[y+dy][x+dx] != val) {
num[y+dy][x+dx] = val;
cnt++;
x_ = x+dx;
y_ = y+dy;
}
}
}
if(bfs2(x_, y_, val) == cnt) {
res = Math.max(res, cnt);
}
}
}
void run() {
n = sc.nextInt();
m = sc.nextInt();
cs = new char[n][];
visited = new boolean[n][m];
num = new int[n][m];
num2 = new int[n][m];
for(int i = 0; i < n; i++) {
cs[i] = sc.next().toCharArray();
}
for(int i = 0; i < n - 1; i++) {
for(int j = 0; j < m - 1; j++) {
boolean good = true;
for(int dy = 0; dy <= 1; dy++) {
for(int dx = 0; dx <= 1; dx++) {
good &= cs[i+dy][j+dx] == '1';
}
}
if(good) {
res = 4;
}
}
}
for(int i = 0, v = 1; i < n; i++) {
for(int j = 0; j < m; j++) {
if(!visited[i][j] && cs[i][j] == '0') {
bfs(j, i, v++);
}
}
}
System.out.println(res);
}
public static void main(String[] args) {
new D().run();
}
static class UnionFind {
int[] data;
public UnionFind(int size) {
data = new int[size];
Arrays.fill(data, -1);
}
int root(int x) { return data[x] < 0 ? x : (data[x] = root(data[x])); }
void union(int x, int y) {
if((x = root(x)) != (y = root(y))) {
data[x] += data[y];
data[y] = x;
}
}
boolean same(int x, int y) { return root(x) == root(y); }
int size(int x) { return -data[root(x)]; }
}
}
| Java | ["3 3\n111\n101\n111", "5 5\n01010\n10101\n01010\n10101\n01010", "7 7\n1111111\n1000101\n1000101\n1000101\n1000111\n1000001\n1111111", "5 5\n11111\n10001\n10101\n10001\n11111"] | 3 seconds | ["8", "0", "24", "0"] | NoteIn the first example there's only one cycle and it is cool.In the second sample there's no cycle at all.In the third sample there are two cool cycles: their lengths are 12 and 24.In the fourth sample there also is only one cycle but it isn't cool as there's a cell containing "1" inside this cycle. | Java 6 | standard input | [
"implementation",
"dfs and similar",
"brute force"
] | 26909af720a7b1fbd247e61af6054174 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the table, respectively. Each of the following n lines contains m characters. Each character can be either "0" or "1". | 2,500 | Print a single number — the length of the longest cool cycle in the table. If such cycles do not exist, print 0. | standard output | |
PASSED | 5ac1139db986d44c53f69260598fb922 | train_004.jsonl | 1323443100 | Little Petya very much likes rectangular tables that consist of characters "0" and "1". Recently he has received one such table as a gift from his mother. The table contained n rows and m columns. The rows are numbered from top to bottom from 1 to n, the columns are numbered from the left to the right from 1 to m. Petya immediately decided to find the longest cool cycle whatever it takes.A cycle is a sequence of pairwise distinct cells where each two consecutive cells have a common side; besides, the first cell has a common side with the last cell. A cycle is called cool if it fulfills all the following conditions simultaneously: The cycle entirely consists of the cells that contain "1". Each cell that belongs to the cycle, has a common side with exactly two other cells that belong to the cycle. Each cell of the table that contains "1" either belongs to the cycle or is positioned outside of it (see definition below). To define the notion of "outside" formally, let's draw a cycle on a plane. Let each cell of the cycle (i, j) (i is the row number, j is the column number) correspond to the point (i, j) on the coordinate plane. Let a straight line segment join each pair of points that correspond to the cells belonging to the cycle and sharing a side. Thus, we will get a closed polyline that has no self-intersections and self-touches. The polyline divides the plane into two connected parts: the part of an infinite area and the part of a finite area. It is considered that cell (r, c) lies outside of the cycle if it does not belong to the cycle and the corresponding point on the plane with coordinates (r, c) lies in the part with the infinite area.Help Petya to find the length of the longest cool cycle in the table. The cycle length is defined as the number of cells that belong to the cycle. | 256 megabytes | import static java.lang.Math.max;
import static java.util.Arrays.deepToString;
import java.io.*;
import java.math.*;
import java.util.*;
public class D {
static int[] dx = new int[] { -1, -1, -1, 0, 0, 1, 1, 1 };
static int[] dy = new int[] { -1, 0, 1, -1, 1, -1, 0, 1 };
static int[] dx1 = new int[] { -1, 0, 0, 1 };
static int[] dy1 = new int[] { 0, -1, 1, 0 };
static int[][] color;
static int[] stackX, stackY;
static int size;
static int[][] add_color;
static boolean gone, ok;
static void goZero(char[][] c, int i, int j, boolean[][] was, int cur_color) {
was[i][j] = true;
if (i == 0 || i == c.length - 1 || j == 0 || j == c[0].length - 1) ok = false;
for (int dir = 0; dir < 8; dir++) {
int ni = i + dy[dir];
int nj = j + dx[dir];
if (ni < 0 || ni >= c.length || nj < 0 || nj >= c[0].length) continue;
if (c[ni][nj] == '1') {
if (color[ni][nj] != cur_color) {
color[ni][nj] = cur_color;
stackX[size] = nj;
stackY[size] = ni;
size++;
}
}
if (!was[ni][nj] && c[ni][nj] == '0') {
goZero(c, ni, nj, was, cur_color);
}
}
}
static boolean checkOnes(int cur_color, int n, int m, char [][] c) {
for (int i = 0; i < size; i++) {
if (onesNeigh(cur_color, stackX[i], stackY[i], n, m, c) != 2)
return false;
}
return true;
}
static int onesNeigh(int cur_color, int x, int y, int n, int m, char [][] c) {
if (gone && add_color[y][x] != cur_color) return 0;
go(cur_color, x, y, n, m);
gone = true;
int ret = 0;
for (int i = 0; i < 4; i++) {
int nx = x + dx1[i];
int ny = y + dy1[i];
if (nx >= 0 && nx < m && ny >= 0 && ny < n && color[ny][nx] == cur_color) ret++;
}
return ret;
}
static void go(int cur_color, int x, int y, int n, int m) {
add_color[y][x] = cur_color;
for (int i = 0; i < 4; i++) {
int nx = x + dx1[i];
int ny = y + dy1[i];
if (nx >= 0 && nx < m && ny >= 0 && ny < n && color[ny][nx] == cur_color && add_color[ny][nx] != cur_color) {
go(cur_color, nx, ny, n, m);
}
}
}
static int solve(char[][] c, int n, int m) {
int res = 0;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < m - 1; j++) {
if (c[i][j] == '1' && c[i + 1][j] == '1' && c[i][j + 1] == '1' && c[i + 1][j + 1] == '1') {
res = 4;
}
}
}
int cur_c = 1;
stackX = new int[n * m];
stackY = new int[n * m];
color = new int[n][m];
add_color = new int[n][m];
boolean[][] wasZero = new boolean[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (c[i][j] == '0' && !wasZero[i][j]) {
size = 0;
ok = true;
goZero(c, i, j, wasZero, cur_c);
gone = false;
if (ok && checkOnes(cur_c, n, m, c)) {
res = max(res, size);
}
cur_c++;
}
}
}
return res;
}
public static void main(String[] args) throws Exception {
reader = new BufferedReader(new InputStreamReader(System.in));
writer = new PrintWriter(System.out);
setTime();
int n = nextInt(), m = nextInt();
char[][] c = new char[n][];
for (int i = 0; i < n; i++) {
c[i] = next().toCharArray();
}
int res = solve(c, n, m);
writer.println(res);
printTime();
printMemory();
writer.close();
}
static BufferedReader reader;
static PrintWriter writer;
static StringTokenizer tok = new StringTokenizer("");
static long systemTime;
static void debug(Object... o) {
System.err.println(deepToString(o));
}
static void setTime() {
systemTime = System.currentTimeMillis();
}
static void printTime() {
System.err.println("Time consumed: " + (System.currentTimeMillis() - systemTime));
}
static void printMemory() {
System.err.println("Memory consumed: "
+ (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1000 + "kb");
}
static String next() {
while (!tok.hasMoreTokens()) {
String w = null;
try {
w = reader.readLine();
} catch (Exception e) {
e.printStackTrace();
}
if (w == null)
return null;
tok = new StringTokenizer(w);
}
return tok.nextToken();
}
static int nextInt() {
return Integer.parseInt(next());
}
static long nextLong() {
return Long.parseLong(next());
}
static double nextDouble() {
return Double.parseDouble(next());
}
static BigInteger nextBigInteger() {
return new BigInteger(next());
}
} | Java | ["3 3\n111\n101\n111", "5 5\n01010\n10101\n01010\n10101\n01010", "7 7\n1111111\n1000101\n1000101\n1000101\n1000111\n1000001\n1111111", "5 5\n11111\n10001\n10101\n10001\n11111"] | 3 seconds | ["8", "0", "24", "0"] | NoteIn the first example there's only one cycle and it is cool.In the second sample there's no cycle at all.In the third sample there are two cool cycles: their lengths are 12 and 24.In the fourth sample there also is only one cycle but it isn't cool as there's a cell containing "1" inside this cycle. | Java 6 | standard input | [
"implementation",
"dfs and similar",
"brute force"
] | 26909af720a7b1fbd247e61af6054174 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the table, respectively. Each of the following n lines contains m characters. Each character can be either "0" or "1". | 2,500 | Print a single number — the length of the longest cool cycle in the table. If such cycles do not exist, print 0. | standard output | |
PASSED | 1cce083a3cce9efe99dba98d4eba7cbe | train_004.jsonl | 1323443100 | Little Petya very much likes rectangular tables that consist of characters "0" and "1". Recently he has received one such table as a gift from his mother. The table contained n rows and m columns. The rows are numbered from top to bottom from 1 to n, the columns are numbered from the left to the right from 1 to m. Petya immediately decided to find the longest cool cycle whatever it takes.A cycle is a sequence of pairwise distinct cells where each two consecutive cells have a common side; besides, the first cell has a common side with the last cell. A cycle is called cool if it fulfills all the following conditions simultaneously: The cycle entirely consists of the cells that contain "1". Each cell that belongs to the cycle, has a common side with exactly two other cells that belong to the cycle. Each cell of the table that contains "1" either belongs to the cycle or is positioned outside of it (see definition below). To define the notion of "outside" formally, let's draw a cycle on a plane. Let each cell of the cycle (i, j) (i is the row number, j is the column number) correspond to the point (i, j) on the coordinate plane. Let a straight line segment join each pair of points that correspond to the cells belonging to the cycle and sharing a side. Thus, we will get a closed polyline that has no self-intersections and self-touches. The polyline divides the plane into two connected parts: the part of an infinite area and the part of a finite area. It is considered that cell (r, c) lies outside of the cycle if it does not belong to the cycle and the corresponding point on the plane with coordinates (r, c) lies in the part with the infinite area.Help Petya to find the length of the longest cool cycle in the table. The cycle length is defined as the number of cells that belong to the cycle. | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
public D () throws IOException {
String input = r.readLine();
String [] NM = input.split(" ");
int N = Integer.parseInt(NM[0]);
int M = Integer.parseInt(NM[1]);
boolean [][] G = new boolean [N][M];
for (int i = 0; i < N; ++i) {
String row = r.readLine();
for (int j = 0; j < M; ++j)
G[i][j] = (row.charAt(j) == '1');
}
this.G = G;
this.N = N;
this.M = M;
solve();
}
int N, M;
boolean [][] G;
final int K = 1000000;
public void solve () {
t = millis();
boolean [][] V = new boolean [N][M];
int res = 0;
for (int i = 0; i < N-1; ++i)
for (int j = 0; j < M-1; ++j) {
int i0 = i, j0 = j;
if (G[i][j] && !V[i][j]) {
List<Integer> path = new LinkedList<Integer>();
Set<Integer> points = new HashSet<Integer>();
int [] D = { 0, 1};
int z = i;
if (!next(i,j,D) || !next(i,j,inner(D))) {
V[i][j] = true;
continue;
}
else {
{
int p = K*i+j;
points.add(p);
path.add(p);
++j;
}
do {
int p = K*i+j;
path.add(p);
if (!points.add(p)) {
while (!path.get(0).equals(p))
points.remove(path.remove(0));
if (safeInt(path, points))
res = Math.max(res, path.size() - 1);
break;
}
int [] IN = inner(D), OUT = outer(D);
if (next(i,j,IN))
D = IN;
else if (!next(i,j,D))
D = OUT;
if (r(D))
V[i][j] = true;
if (next(i,j,D)) {
i += D[0];
j += D[1];
} else
break;
if (i < z)
break;
} while (true);
}
}
i = i0; j = j0;
}
print (res);
}
int [] decode (int n) {
return new int [] { n/K, n%K };
}
boolean safeInt(List<Integer> path, Set<Integer> points) {
if (path.size() == 4)
return true;
for (int p : path) {
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int c = 0;
if (points.contains(K*(x-1) + y))
++c;
if (points.contains(K*(x+1) + y))
++c;
if (points.contains(K*x + (y-1)))
++c;
if (points.contains(K*x + (y+1)))
++c;
if (c != 2)
return false;
}
int [] D = { 0, 1 };
Set<Integer> IP = new HashSet<Integer>();
Queue<Integer> Q = new LinkedList<Integer>();
int [] zero = decode(path.get(0));
int [] one = decode(path.get(1));
if (one[0] == zero[0] + 1 && one[1] == zero[0]) {
List<Integer> reverse = new LinkedList<Integer>();
for (int p : path)
reverse.add(0, p);
return safeInt(reverse, points);
}
for (int p : path) {
if (p == path.get(0))
continue;
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int [] IN = inner(D);
if (next(x,y,IN))
D = IN;
else {
if (!next(x,y,D))
D = outer(D);
x += IN[0]; y += IN[1];
if (x >= 0 && y >= 0 && x < N && y < M) {
int ip = K*x+y;
if (IP.add(ip))
Q.add(ip);
}
}
}
while (!Q.isEmpty()) {
int p = Q.poll();
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int nx, ny;
boolean t = true;
nx = x+1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y+1;
t = t && test(nx, ny, points, IP, Q);
nx = x-1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y-1;
t = t && test(nx, ny, points, IP, Q);
if (!t)
return false;
}
return true;
}
boolean test(int nx, int ny, Set<Integer> points, Set<Integer> IP, Queue<Integer> Q) {
int np = K*nx+ny;
if (nx >= 0 && ny >= 0 && nx < N && ny < M) {
if (!points.contains(np)) {
if (G[nx][ny])
return false;
if (IP.add(np))
Q.add(np);
}
}
return true;
}
boolean next (int x, int y, int [] d) {
x += d[0]; y += d[1];
return x >= 0 && y >= 0 && x < N && y < M && G[x][y];
}
boolean r(int [] d) {
return (d[0] == 0 && d[1] == 1);
}
int [] inner (int [] d) {
int s = K*d[0] + d[1];
if (s == 1)
return new int [] { 1, 0 };
if (s == K)
return new int [] { 0, -1 };
if (s == -1)
return new int [] { -1, 0 };
if (s == -K)
return new int [] { 0, 1 };
return null;
}
int [] outer (int [] d) {
int [] IN = inner(d);
return new int [] { -IN[0], -IN[1] };
}
////////////////////////////////////////////////////////////////////////////////////
static BufferedReader r;
static long t;
static void print2 (Object o) {
System.out.println(o);
}
static void print (Object o) {
print2(o);
//print2((millis() - t) / 1000.0);
System.exit(0);
}
static void run () throws IOException {
r = new BufferedReader(new InputStreamReader(System.in));
new D();
}
public static void main(String[] args) throws IOException {
run();
}
static long millis() {
return System.currentTimeMillis();
}
} | Java | ["3 3\n111\n101\n111", "5 5\n01010\n10101\n01010\n10101\n01010", "7 7\n1111111\n1000101\n1000101\n1000101\n1000111\n1000001\n1111111", "5 5\n11111\n10001\n10101\n10001\n11111"] | 3 seconds | ["8", "0", "24", "0"] | NoteIn the first example there's only one cycle and it is cool.In the second sample there's no cycle at all.In the third sample there are two cool cycles: their lengths are 12 and 24.In the fourth sample there also is only one cycle but it isn't cool as there's a cell containing "1" inside this cycle. | Java 6 | standard input | [
"implementation",
"dfs and similar",
"brute force"
] | 26909af720a7b1fbd247e61af6054174 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the table, respectively. Each of the following n lines contains m characters. Each character can be either "0" or "1". | 2,500 | Print a single number — the length of the longest cool cycle in the table. If such cycles do not exist, print 0. | standard output | |
PASSED | b4d2682ac9f4961102dd82cc21e150c5 | train_004.jsonl | 1323443100 | Little Petya very much likes rectangular tables that consist of characters "0" and "1". Recently he has received one such table as a gift from his mother. The table contained n rows and m columns. The rows are numbered from top to bottom from 1 to n, the columns are numbered from the left to the right from 1 to m. Petya immediately decided to find the longest cool cycle whatever it takes.A cycle is a sequence of pairwise distinct cells where each two consecutive cells have a common side; besides, the first cell has a common side with the last cell. A cycle is called cool if it fulfills all the following conditions simultaneously: The cycle entirely consists of the cells that contain "1". Each cell that belongs to the cycle, has a common side with exactly two other cells that belong to the cycle. Each cell of the table that contains "1" either belongs to the cycle or is positioned outside of it (see definition below). To define the notion of "outside" formally, let's draw a cycle on a plane. Let each cell of the cycle (i, j) (i is the row number, j is the column number) correspond to the point (i, j) on the coordinate plane. Let a straight line segment join each pair of points that correspond to the cells belonging to the cycle and sharing a side. Thus, we will get a closed polyline that has no self-intersections and self-touches. The polyline divides the plane into two connected parts: the part of an infinite area and the part of a finite area. It is considered that cell (r, c) lies outside of the cycle if it does not belong to the cycle and the corresponding point on the plane with coordinates (r, c) lies in the part with the infinite area.Help Petya to find the length of the longest cool cycle in the table. The cycle length is defined as the number of cells that belong to the cycle. | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
public D () throws IOException {
String input = r.readLine();
String [] NM = input.split(" ");
int N = Integer.parseInt(NM[0]);
int M = Integer.parseInt(NM[1]);
boolean [][] G = new boolean [N][M];
for (int i = 0; i < N; ++i) {
String row = r.readLine();
for (int j = 0; j < M; ++j)
G[i][j] = (row.charAt(j) == '1');
}
this.G = G;
this.N = N;
this.M = M;
solve();
}
int N, M;
boolean [][] G;
final static int K = 100000;
public void solve () {
t = millis();
boolean [][] V = new boolean [N][M];
int res = 0;
for (int i = 0; i < N-1; ++i)
for (int j = 0; j < M-1; ++j) {
int i0 = i, j0 = j;
if (G[i][j] && !V[i][j]) {
List<Integer> path = new LinkedList<Integer>();
Set<Integer> points = new HashSet<Integer>();
int [] D = { 0, 1};
int z = i;
if (!next(i,j,D) || !next(i,j,inner(D))) {
V[i][j] = true;
continue;
}
else {
{
int p = K*i+j;
points.add(p);
path.add(p);
++j;
}
do {
int p = K*i+j;
path.add(p);
if (!points.add(p)) {
while (!path.get(0).equals(p))
points.remove(path.remove(0));
if (safeInt(path, points))
res = Math.max(res, path.size() - 1);
break;
}
int [] IN = inner(D), OUT = outer(D);
if (next(i,j,IN))
D = IN;
else if (!next(i,j,D))
D = OUT;
if (r(D))
V[i][j] = true;
if (next(i,j,D)) {
i += D[0];
j += D[1];
} else
break;
if (i < z)
break;
} while (true);
}
}
i = i0; j = j0;
}
print (res);
}
int [] decode (int n) {
return new int [] { n/K, n%K };
}
boolean safeInt(List<Integer> path, Set<Integer> points) {
if (path.size() == 4)
return true;
for (int p : path) {
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int c = 0;
if (points.contains(K*(x-1) + y))
++c;
if (points.contains(K*(x+1) + y))
++c;
if (points.contains(K*x + (y-1)))
++c;
if (points.contains(K*x + (y+1)))
++c;
if (c != 2)
return false;
}
int [] D = { 0, 1 };
Set<Integer> IP = new HashSet<Integer>();
Queue<Integer> Q = new LinkedList<Integer>();
int [] zero = decode(path.get(0));
int [] one = decode(path.get(1));
if (one[0] == zero[0] + 1 && one[1] == zero[0]) {
List<Integer> reverse = new LinkedList<Integer>();
for (int p : path)
reverse.add(0, p);
return safeInt(reverse, points);
}
for (int p : path) {
if (p == path.get(0))
continue;
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int [] IN = inner(D);
if (next(x,y,IN))
D = IN;
else {
if (!next(x,y,D))
D = outer(D);
x += IN[0]; y += IN[1];
if (x >= 0 && y >= 0 && x < N && y < M) {
int ip = K*x+y;
if (IP.add(ip))
Q.add(ip);
}
}
}
while (!Q.isEmpty()) {
int p = Q.poll();
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int nx, ny;
boolean t = true;
nx = x+1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y+1;
t = t && test(nx, ny, points, IP, Q);
nx = x-1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y-1;
t = t && test(nx, ny, points, IP, Q);
if (!t)
return false;
}
return true;
}
boolean test(int nx, int ny, Set<Integer> points, Set<Integer> IP, Queue<Integer> Q) {
int np = K*nx+ny;
if (nx >= 0 && ny >= 0 && nx < N && ny < M) {
if (!points.contains(np)) {
if (G[nx][ny])
return false;
if (IP.add(np))
Q.add(np);
}
}
return true;
}
boolean next (int x, int y, int [] d) {
x += d[0]; y += d[1];
return x >= 0 && y >= 0 && x < N && y < M && G[x][y];
}
boolean r(int [] d) {
return (d[0] == 0 && d[1] == 1);
}
int [] inner (int [] d) {
int s = K*d[0] + d[1];
if (s == 1)
return new int [] { 1, 0 };
if (s == K)
return new int [] { 0, -1 };
if (s == -1)
return new int [] { -1, 0 };
if (s == -K)
return new int [] { 0, 1 };
return null;
}
int [] outer (int [] d) {
int [] IN = inner(d);
return new int [] { -IN[0], -IN[1] };
}
////////////////////////////////////////////////////////////////////////////////////
static BufferedReader r;
static long t;
static void print2 (Object o) {
System.out.println(o);
}
static void print (Object o) {
print2(o);
//print2((millis() - t) / 1000.0);
System.exit(0);
}
static void run () throws IOException {
r = new BufferedReader(new InputStreamReader(System.in));
new D();
}
public static void main(String[] args) throws IOException {
run();
}
static long millis() {
return System.currentTimeMillis();
}
} | Java | ["3 3\n111\n101\n111", "5 5\n01010\n10101\n01010\n10101\n01010", "7 7\n1111111\n1000101\n1000101\n1000101\n1000111\n1000001\n1111111", "5 5\n11111\n10001\n10101\n10001\n11111"] | 3 seconds | ["8", "0", "24", "0"] | NoteIn the first example there's only one cycle and it is cool.In the second sample there's no cycle at all.In the third sample there are two cool cycles: their lengths are 12 and 24.In the fourth sample there also is only one cycle but it isn't cool as there's a cell containing "1" inside this cycle. | Java 6 | standard input | [
"implementation",
"dfs and similar",
"brute force"
] | 26909af720a7b1fbd247e61af6054174 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the table, respectively. Each of the following n lines contains m characters. Each character can be either "0" or "1". | 2,500 | Print a single number — the length of the longest cool cycle in the table. If such cycles do not exist, print 0. | standard output | |
PASSED | eb2c0a32c303e5338fe2c4eaa0731af4 | train_004.jsonl | 1323443100 | Little Petya very much likes rectangular tables that consist of characters "0" and "1". Recently he has received one such table as a gift from his mother. The table contained n rows and m columns. The rows are numbered from top to bottom from 1 to n, the columns are numbered from the left to the right from 1 to m. Petya immediately decided to find the longest cool cycle whatever it takes.A cycle is a sequence of pairwise distinct cells where each two consecutive cells have a common side; besides, the first cell has a common side with the last cell. A cycle is called cool if it fulfills all the following conditions simultaneously: The cycle entirely consists of the cells that contain "1". Each cell that belongs to the cycle, has a common side with exactly two other cells that belong to the cycle. Each cell of the table that contains "1" either belongs to the cycle or is positioned outside of it (see definition below). To define the notion of "outside" formally, let's draw a cycle on a plane. Let each cell of the cycle (i, j) (i is the row number, j is the column number) correspond to the point (i, j) on the coordinate plane. Let a straight line segment join each pair of points that correspond to the cells belonging to the cycle and sharing a side. Thus, we will get a closed polyline that has no self-intersections and self-touches. The polyline divides the plane into two connected parts: the part of an infinite area and the part of a finite area. It is considered that cell (r, c) lies outside of the cycle if it does not belong to the cycle and the corresponding point on the plane with coordinates (r, c) lies in the part with the infinite area.Help Petya to find the length of the longest cool cycle in the table. The cycle length is defined as the number of cells that belong to the cycle. | 256 megabytes | import java.io.*;
import java.util.*;
public class D135 {
public D135 () throws IOException {
String input = r.readLine();
String [] NM = input.split(" ");
int N = Integer.parseInt(NM[0]);
int M = Integer.parseInt(NM[1]);
boolean [][] G = new boolean [N][M];
for (int i = 0; i < N; ++i) {
String row = r.readLine();
for (int j = 0; j < M; ++j)
G[i][j] = (row.charAt(j) == '1');
}
this.G = G;
this.N = N;
this.M = M;
solve();
}
int N, M;
boolean [][] G;
int res;
final static int K = 1000000;
public void solve () {
t = millis();
boolean [][] V = new boolean [N][M];
res = 0;
for (int i = 0; i < N-1; ++i)
for (int j = 0; j < M-1; ++j) {
int i0 = i, j0 = j;
if (G[i][j] && !V[i][j]) {
if (G[i][j+1] && G[i+1][j+1] && G[i+1][j]) {
if (res < 4) res = 4;
continue;
}
List<Integer> path = new LinkedList<Integer>();
Set<Integer> points = new HashSet<Integer>();
int [] D = { 0, 1};
int z = i;
if (!next(i,j,D) || !next(i,j,inner(D))) {
V[i][j] = true;
continue;
}
else {
{
int p = K*i+j;
points.add(p);
path.add(p);
++j;
}
do {
int p = K*i+j;
path.add(p);
if (!points.add(p)) {
while (!path.get(0).equals(p))
points.remove(path.remove(0));
if (safeInt(p, path, points))
res = Math.max(res, path.size() - 1);
break;
}
int [] IN = inner(D), OUT = outer(D);
if (next(i,j,IN))
D = IN;
else if (!next(i,j,D))
D = OUT;
if (r(D))
V[i][j] = true;
if (next(i,j,D)) {
i += D[0];
j += D[1];
} else
break;
if (i < z)
break;
} while (true);
}
}
i = i0; j = j0;
}
print (res);
}
int [] decode (int n) {
return new int [] { n/K, n%K };
}
boolean safeInt(int p0, List<Integer> path, Set<Integer> points) {
if (path.size() <= res+1)
return false;
if (path.size() == 5)
return true;
for (int p : path) {
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int c = 0;
if (points.contains(K*(x-1) + y))
++c;
if (points.contains(K*(x+1) + y))
++c;
if (points.contains(K*x + (y-1)))
++c;
if (points.contains(K*x + (y+1)))
++c;
if (c != 2)
return false;
}
if (p0 != path.get(0)) {
int x = K, y = K;
for (int p : path) {
int [] xy = decode(p);
x = Math.min(x, xy[0]);
if (x == xy[0])
y = Math.min(y, xy[1]);
}
int p1 = K*x + y;
path.remove(0);
while(path.get(0) != p1)
path.add(path.remove(0));
path.add(p1);
if (decode(path.get(1))[0] > decode(path.get(0))[0]) {
List<Integer> reverse = new LinkedList<Integer>();
for (int q : path)
reverse.add(0, q);
}
}
return safeInt2(path, points);
}
boolean safeInt2(List<Integer> path, Set<Integer> points) {
int [] D = { 0, 1 };
Set<Integer> IP = new HashSet<Integer>();
Queue<Integer> Q = new LinkedList<Integer>();
for (int p : path) {
if (p == path.get(0))
continue;
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int [] IN = inner(D);
if (next(x,y,IN))
D = IN;
else {
if (!next(x,y,D))
D = outer(D);
x += IN[0]; y += IN[1];
if (x >= 0 && y >= 0 && x < N && y < M) {
int ip = K*x+y;
if (IP.add(ip))
Q.add(ip);
}
}
}
while (!Q.isEmpty()) {
int p = Q.poll();
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int nx, ny;
boolean t = true;
nx = x+1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y+1;
t = t && test(nx, ny, points, IP, Q);
nx = x-1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y-1;
t = t && test(nx, ny, points, IP, Q);
if (!t)
return false;
}
return true;
}
boolean test(int nx, int ny, Set<Integer> points, Set<Integer> IP, Queue<Integer> Q) {
int np = K*nx+ny;
if (nx >= 0 && ny >= 0 && nx < N && ny < M) {
if (!points.contains(np)) {
if (G[nx][ny])
return false;
if (IP.add(np))
Q.add(np);
}
}
return true;
}
boolean next (int x, int y, int [] d) {
x += d[0]; y += d[1];
return x >= 0 && y >= 0 && x < N && y < M && G[x][y];
}
boolean r(int [] d) {
return (d[0] == 0 && d[1] == 1);
}
int [] inner (int [] d) {
int s = K*d[0] + d[1];
if (s == 1)
return new int [] { 1, 0 };
if (s == K)
return new int [] { 0, -1 };
if (s == -1)
return new int [] { -1, 0 };
if (s == -K)
return new int [] { 0, 1 };
return null;
}
int [] outer (int [] d) {
int [] IN = inner(d);
return new int [] { -IN[0], -IN[1] };
}
////////////////////////////////////////////////////////////////////////////////////
static BufferedReader r;
static long t;
static void print2 (Object o) {
System.out.println(o);
}
static void print (Object o) {
print2(o);
//print2((millis() - t) / 1000.0);
System.exit(0);
}
static void run () throws IOException {
r = new BufferedReader(new InputStreamReader(System.in));
new D135();
}
public static void main(String[] args) throws IOException {
run();
}
static long millis() {
return System.currentTimeMillis();
}
} | Java | ["3 3\n111\n101\n111", "5 5\n01010\n10101\n01010\n10101\n01010", "7 7\n1111111\n1000101\n1000101\n1000101\n1000111\n1000001\n1111111", "5 5\n11111\n10001\n10101\n10001\n11111"] | 3 seconds | ["8", "0", "24", "0"] | NoteIn the first example there's only one cycle and it is cool.In the second sample there's no cycle at all.In the third sample there are two cool cycles: their lengths are 12 and 24.In the fourth sample there also is only one cycle but it isn't cool as there's a cell containing "1" inside this cycle. | Java 6 | standard input | [
"implementation",
"dfs and similar",
"brute force"
] | 26909af720a7b1fbd247e61af6054174 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the table, respectively. Each of the following n lines contains m characters. Each character can be either "0" or "1". | 2,500 | Print a single number — the length of the longest cool cycle in the table. If such cycles do not exist, print 0. | standard output | |
PASSED | 87a17fbe5e7e73c9b838b746518d60ca | train_004.jsonl | 1323443100 | Little Petya very much likes rectangular tables that consist of characters "0" and "1". Recently he has received one such table as a gift from his mother. The table contained n rows and m columns. The rows are numbered from top to bottom from 1 to n, the columns are numbered from the left to the right from 1 to m. Petya immediately decided to find the longest cool cycle whatever it takes.A cycle is a sequence of pairwise distinct cells where each two consecutive cells have a common side; besides, the first cell has a common side with the last cell. A cycle is called cool if it fulfills all the following conditions simultaneously: The cycle entirely consists of the cells that contain "1". Each cell that belongs to the cycle, has a common side with exactly two other cells that belong to the cycle. Each cell of the table that contains "1" either belongs to the cycle or is positioned outside of it (see definition below). To define the notion of "outside" formally, let's draw a cycle on a plane. Let each cell of the cycle (i, j) (i is the row number, j is the column number) correspond to the point (i, j) on the coordinate plane. Let a straight line segment join each pair of points that correspond to the cells belonging to the cycle and sharing a side. Thus, we will get a closed polyline that has no self-intersections and self-touches. The polyline divides the plane into two connected parts: the part of an infinite area and the part of a finite area. It is considered that cell (r, c) lies outside of the cycle if it does not belong to the cycle and the corresponding point on the plane with coordinates (r, c) lies in the part with the infinite area.Help Petya to find the length of the longest cool cycle in the table. The cycle length is defined as the number of cells that belong to the cycle. | 256 megabytes | import java.io.*;
import java.util.*;
public class D135 {
public D135 () throws IOException {
String input = r.readLine();
String [] NM = input.split(" ");
int N = Integer.parseInt(NM[0]);
int M = Integer.parseInt(NM[1]);
boolean [][] G = new boolean [N][M];
for (int i = 0; i < N; ++i) {
String row = r.readLine();
for (int j = 0; j < M; ++j)
G[i][j] = (row.charAt(j) == '1');
}
this.G = G;
this.N = N;
this.M = M;
solve();
}
int N, M;
boolean [][] G;
int res;
final static int K = 1000000;
public void solve () {
t = millis();
boolean [][] V = new boolean [N][M];
res = 0;
for (int i = 0; i < N-1; ++i)
for (int j = 0; j < M-1; ++j) {
int i0 = i, j0 = j;
if (G[i][j] && !V[i][j]) {
if (G[i][j+1] && G[i+1][j+1] && G[i+1][j]) {
if (res < 4) res = 4;
continue;
}
List<Integer> path = new LinkedList<Integer>();
Set<Integer> points = new HashSet<Integer>();
int [] D = { 0, 1};
int z = i;
if (!next(i,j,D) || !next(i,j,inner(D))) {
V[i][j] = true;
continue;
}
else {
{
int p = K*i+j;
points.add(p);
path.add(p);
++j;
}
do {
int p = K*i+j;
path.add(p);
if (!points.add(p)) {
while (!path.get(0).equals(p))
points.remove(path.remove(0));
if (safeInt(path, points))
res = Math.max(res, path.size() - 1);
break;
}
int [] IN = inner(D), OUT = outer(D);
if (next(i,j,IN))
D = IN;
else if (!next(i,j,D))
D = OUT;
if (r(D))
V[i][j] = true;
if (next(i,j,D)) {
i += D[0];
j += D[1];
} else
break;
if (i < z)
break;
} while (true);
}
}
i = i0; j = j0;
}
print (res);
}
int [] decode (int n) {
return new int [] { n/K, n%K };
}
boolean safeInt(List<Integer> path, Set<Integer> points) {
if (path.size() <= res+1)
return false;
if (path.size() == 5)
return true;
for (int p : path) {
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int c = 0;
if (points.contains(K*(x-1) + y))
++c;
if (points.contains(K*(x+1) + y))
++c;
if (points.contains(K*x + (y-1)))
++c;
if (points.contains(K*x + (y+1)))
++c;
if (c != 2)
return false;
}
int [] D = { 0, 1 };
Set<Integer> IP = new HashSet<Integer>();
Queue<Integer> Q = new LinkedList<Integer>();
for (int p : path) {
if (p == path.get(0))
continue;
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int [] IN = inner(D);
if (next(x,y,IN))
D = IN;
else {
if (!next(x,y,D))
D = outer(D);
x += IN[0]; y += IN[1];
if (x >= 0 && y >= 0 && x < N && y < M) {
int ip = K*x+y;
if (IP.add(ip))
Q.add(ip);
}
}
}
while (!Q.isEmpty()) {
int p = Q.poll();
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int nx, ny;
boolean t = true;
nx = x+1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y+1;
t = t && test(nx, ny, points, IP, Q);
nx = x-1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y-1;
t = t && test(nx, ny, points, IP, Q);
if (!t)
return false;
}
return true;
}
boolean test(int nx, int ny, Set<Integer> points, Set<Integer> IP, Queue<Integer> Q) {
int np = K*nx+ny;
if (nx >= 0 && ny >= 0 && nx < N && ny < M) {
if (!points.contains(np)) {
if (G[nx][ny])
return false;
if (IP.add(np))
Q.add(np);
}
}
return true;
}
boolean next (int x, int y, int [] d) {
x += d[0]; y += d[1];
return x >= 0 && y >= 0 && x < N && y < M && G[x][y];
}
boolean r(int [] d) {
return (d[0] == 0 && d[1] == 1);
}
int [] inner (int [] d) {
int s = K*d[0] + d[1];
if (s == 1)
return new int [] { 1, 0 };
if (s == K)
return new int [] { 0, -1 };
if (s == -1)
return new int [] { -1, 0 };
if (s == -K)
return new int [] { 0, 1 };
return null;
}
int [] outer (int [] d) {
int [] IN = inner(d);
return new int [] { -IN[0], -IN[1] };
}
////////////////////////////////////////////////////////////////////////////////////
static BufferedReader r;
static long t;
static void print2 (Object o) {
System.out.println(o);
}
static void print (Object o) {
print2(o);
//print2((millis() - t) / 1000.0);
System.exit(0);
}
static void run () throws IOException {
r = new BufferedReader(new InputStreamReader(System.in));
new D135();
}
public static void main(String[] args) throws IOException {
run();
}
static long millis() {
return System.currentTimeMillis();
}
} | Java | ["3 3\n111\n101\n111", "5 5\n01010\n10101\n01010\n10101\n01010", "7 7\n1111111\n1000101\n1000101\n1000101\n1000111\n1000001\n1111111", "5 5\n11111\n10001\n10101\n10001\n11111"] | 3 seconds | ["8", "0", "24", "0"] | NoteIn the first example there's only one cycle and it is cool.In the second sample there's no cycle at all.In the third sample there are two cool cycles: their lengths are 12 and 24.In the fourth sample there also is only one cycle but it isn't cool as there's a cell containing "1" inside this cycle. | Java 6 | standard input | [
"implementation",
"dfs and similar",
"brute force"
] | 26909af720a7b1fbd247e61af6054174 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the table, respectively. Each of the following n lines contains m characters. Each character can be either "0" or "1". | 2,500 | Print a single number — the length of the longest cool cycle in the table. If such cycles do not exist, print 0. | standard output | |
PASSED | 8729b8b9139080433d999874aada4d9b | train_004.jsonl | 1323443100 | Little Petya very much likes rectangular tables that consist of characters "0" and "1". Recently he has received one such table as a gift from his mother. The table contained n rows and m columns. The rows are numbered from top to bottom from 1 to n, the columns are numbered from the left to the right from 1 to m. Petya immediately decided to find the longest cool cycle whatever it takes.A cycle is a sequence of pairwise distinct cells where each two consecutive cells have a common side; besides, the first cell has a common side with the last cell. A cycle is called cool if it fulfills all the following conditions simultaneously: The cycle entirely consists of the cells that contain "1". Each cell that belongs to the cycle, has a common side with exactly two other cells that belong to the cycle. Each cell of the table that contains "1" either belongs to the cycle or is positioned outside of it (see definition below). To define the notion of "outside" formally, let's draw a cycle on a plane. Let each cell of the cycle (i, j) (i is the row number, j is the column number) correspond to the point (i, j) on the coordinate plane. Let a straight line segment join each pair of points that correspond to the cells belonging to the cycle and sharing a side. Thus, we will get a closed polyline that has no self-intersections and self-touches. The polyline divides the plane into two connected parts: the part of an infinite area and the part of a finite area. It is considered that cell (r, c) lies outside of the cycle if it does not belong to the cycle and the corresponding point on the plane with coordinates (r, c) lies in the part with the infinite area.Help Petya to find the length of the longest cool cycle in the table. The cycle length is defined as the number of cells that belong to the cycle. | 256 megabytes | import java.io.*;
import java.util.*;
public class D135 {
public D135 () throws IOException {
String input = r.readLine();
String [] NM = input.split(" ");
int N = Integer.parseInt(NM[0]);
int M = Integer.parseInt(NM[1]);
boolean [][] G = new boolean [N][M];
for (int i = 0; i < N; ++i) {
String row = r.readLine();
for (int j = 0; j < M; ++j)
G[i][j] = (row.charAt(j) == '1');
}
this.G = G;
this.N = N;
this.M = M;
solve();
}
int N, M;
boolean [][] G;
int res;
final static int K = 1000000;
public void solve () {
t = millis();
boolean [][] V = new boolean [N][M];
res = 0;
for (int i = 0; i < N-1; ++i)
for (int j = 0; j < M-1; ++j) {
int i0 = i, j0 = j;
if (G[i][j] && !V[i][j]) {
if (G[i][j+1] && G[i+1][j+1] && G[i+1][j]) {
if (res < 4) res = 4;
continue;
}
List<Integer> path = new LinkedList<Integer>();
Set<Integer> points = new HashSet<Integer>();
int [] D = { 0, 1};
int z = i;
if (!next(i,j,D) || !next(i,j,inner(D))) {
V[i][j] = true;
continue;
}
else {
{
int p = K*i+j;
points.add(p);
path.add(p);
++j;
}
do {
int p = K*i+j;
path.add(p);
if (!points.add(p)) {
while (!path.get(0).equals(p))
points.remove(path.remove(0));
if (safeInt(path, points))
res = Math.max(res, path.size() - 1);
break;
}
int [] IN = inner(D), OUT = outer(D);
if (next(i,j,IN))
D = IN;
else if (!next(i,j,D))
D = OUT;
if (r(D))
V[i][j] = true;
if (next(i,j,D)) {
i += D[0];
j += D[1];
} else
break;
if (i < z)
break;
} while (true);
}
}
i = i0; j = j0;
}
print (res);
}
int [] decode (int n) {
return new int [] { n/K, n%K };
}
boolean safeInt(List<Integer> path, Set<Integer> points) {
if (path.size() <= res+1)
return false;
if (path.size() == 5)
return true;
for (int p : path) {
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int c = 0;
if (points.contains(K*(x-1) + y))
++c;
if (points.contains(K*(x+1) + y))
++c;
if (points.contains(K*x + (y-1)))
++c;
if (points.contains(K*x + (y+1)))
++c;
if (c != 2)
return false;
}
int [] D = { 0, 1 };
Set<Integer> IP = new HashSet<Integer>();
Queue<Integer> Q = new LinkedList<Integer>();
for (int p : path) {
if (p == path.get(0))
continue;
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int [] IN = inner(D);
if (next(x,y,IN))
D = IN;
else {
if (!next(x,y,D))
D = outer(D);
x += IN[0]; y += IN[1];
if (x >= 0 && y >= 0 && x < N && y < M) {
int ip = K*x+y;
if (IP.add(ip))
Q.add(ip);
}
}
}
while (!Q.isEmpty()) {
int p = Q.poll();
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int nx, ny;
boolean t = true;
nx = x+1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y+1;
t = t && test(nx, ny, points, IP, Q);
nx = x-1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y-1;
t = t && test(nx, ny, points, IP, Q);
if (!t)
return false;
}
return true;
}
boolean test(int nx, int ny, Set<Integer> points, Set<Integer> IP, Queue<Integer> Q) {
int np = K*nx+ny;
if (nx >= 0 && ny >= 0 && nx < N && ny < M) {
if (!points.contains(np)) {
if (G[nx][ny])
return false;
if (IP.add(np))
Q.add(np);
}
}
return true;
}
boolean next (int x, int y, int [] d) {
x += d[0]; y += d[1];
return x >= 0 && y >= 0 && x < N && y < M && G[x][y];
}
boolean r(int [] d) {
return (d[0] == 0 && d[1] == 1);
}
int [] inner (int [] d) {
int s = K*d[0] + d[1];
if (s == 1)
return new int [] { 1, 0 };
if (s == K)
return new int [] { 0, -1 };
if (s == -1)
return new int [] { -1, 0 };
if (s == -K)
return new int [] { 0, 1 };
return null;
}
int [] outer (int [] d) {
int [] IN = inner(d);
return new int [] { -IN[0], -IN[1] };
}
////////////////////////////////////////////////////////////////////////////////////
static BufferedReader r;
static long t;
static void print2 (Object o) {
System.out.println(o);
}
static void print (Object o) {
print2(o);
//print2((millis() - t) / 1000.0);
System.exit(0);
}
static void run () throws IOException {
r = new BufferedReader(new InputStreamReader(System.in));
new D135();
}
public static void main(String[] args) throws IOException {
run();
}
static long millis() {
return System.currentTimeMillis();
}
} | Java | ["3 3\n111\n101\n111", "5 5\n01010\n10101\n01010\n10101\n01010", "7 7\n1111111\n1000101\n1000101\n1000101\n1000111\n1000001\n1111111", "5 5\n11111\n10001\n10101\n10001\n11111"] | 3 seconds | ["8", "0", "24", "0"] | NoteIn the first example there's only one cycle and it is cool.In the second sample there's no cycle at all.In the third sample there are two cool cycles: their lengths are 12 and 24.In the fourth sample there also is only one cycle but it isn't cool as there's a cell containing "1" inside this cycle. | Java 6 | standard input | [
"implementation",
"dfs and similar",
"brute force"
] | 26909af720a7b1fbd247e61af6054174 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the table, respectively. Each of the following n lines contains m characters. Each character can be either "0" or "1". | 2,500 | Print a single number — the length of the longest cool cycle in the table. If such cycles do not exist, print 0. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.