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
sequencelengths
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
18c4877eaba69d3bd51905f2fbaf3775
train_000.jsonl
1598798100
You are given $$$n$$$ strings $$$s_1, s_2, \ldots, s_n$$$ consisting of lowercase Latin letters.In one operation you can remove a character from a string $$$s_i$$$ and insert it to an arbitrary position in a string $$$s_j$$$ ($$$j$$$ may be equal to $$$i$$$). You may perform this operation any number of times. Is it possible to make all $$$n$$$ strings equal?
256 megabytes
//package cp; import java.io.*; import java.util.*; import java.util.Map.Entry; public class CF { static FastReader sc = new FastReader(); public static void main(String[] args) { int t = sc.nextInt(); while (t-- > 0) { solve(); } //solve(); } //@SuppressWarnings("unlikely-arg-type") static void solve() { int n = sc.nextInt(); int temp = n; String str = ""; while(n-- >0) { String s = sc.next(); str+=s; } //System.out.println(str); Map<Character,Integer> map = new HashMap<>(); for(int i=0 ; i<str.length() ; i++) { if(map.containsKey(str.charAt(i))) { map.put(str.charAt(i), map.get(str.charAt(i))+1); } else { map.put(str.charAt(i), 1); } } boolean flag = false; for(Map.Entry<Character, Integer> entry : map.entrySet()) { if(entry.getValue() % temp== 0) { flag = true; } else { flag = false; break; } } if(flag == true) { System.out.println("YES"); } else { System.out.println("NO"); } } //fast input reader 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\n2\ncaa\ncbb\n3\ncba\ncba\ncbb\n4\nccab\ncbac\nbca\nacbcc\n4\nacb\ncaf\nc\ncbafc"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first test case, you can do the following: Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab". In the second test case, it is impossible to make all $$$n$$$ strings equal.
Java 11
standard input
[ "greedy", "strings" ]
3d6cd0a82513bc2119c9af3d1243846f
The first line contains $$$t$$$ ($$$1 \le t \le 10$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$): the number of strings. $$$n$$$ lines follow, the $$$i$$$-th line contains $$$s_i$$$ ($$$1 \le \lvert s_i \rvert \le 1000$$$). The sum of lengths of all strings in all test cases does not exceed $$$1000$$$.
800
If it is possible to make the strings equal, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can output each character in either lowercase or uppercase.
standard output
PASSED
690c5c86b7eebc1135cccaacce0a0852
train_000.jsonl
1598798100
You are given $$$n$$$ strings $$$s_1, s_2, \ldots, s_n$$$ consisting of lowercase Latin letters.In one operation you can remove a character from a string $$$s_i$$$ and insert it to an arbitrary position in a string $$$s_j$$$ ($$$j$$$ may be equal to $$$i$$$). You may perform this operation any number of times. Is it possible to make all $$$n$$$ strings equal?
256 megabytes
//package cp; import java.io.*; import java.util.*; import java.util.Map.Entry; public class CF { static FastReader sc = new FastReader(); public static void main(String[] args) { int t = sc.nextInt(); while (t-- > 0) { solve(); } //solve(); } static void solve() { int n = sc.nextInt(); int temp = n; Map<Character,Integer> map = new HashMap<>(); while(n-- >0) { String str = sc.next(); for(int i=0 ; i<str.length() ; i++) { if(map.containsKey(str.charAt(i))) { map.put(str.charAt(i), map.get(str.charAt(i))+1); } else { map.put(str.charAt(i), 1); } } } boolean flag = true; for(Map.Entry<Character, Integer> entry : map.entrySet()) { if(entry.getValue() % temp != 0) { flag = false; break; } } if(flag==false) { System.out.println("no"); } else { System.out.println("yes"); } } //fast input reader 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\n2\ncaa\ncbb\n3\ncba\ncba\ncbb\n4\nccab\ncbac\nbca\nacbcc\n4\nacb\ncaf\nc\ncbafc"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first test case, you can do the following: Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab". In the second test case, it is impossible to make all $$$n$$$ strings equal.
Java 11
standard input
[ "greedy", "strings" ]
3d6cd0a82513bc2119c9af3d1243846f
The first line contains $$$t$$$ ($$$1 \le t \le 10$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$): the number of strings. $$$n$$$ lines follow, the $$$i$$$-th line contains $$$s_i$$$ ($$$1 \le \lvert s_i \rvert \le 1000$$$). The sum of lengths of all strings in all test cases does not exceed $$$1000$$$.
800
If it is possible to make the strings equal, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can output each character in either lowercase or uppercase.
standard output
PASSED
23225fa9b55069f3fa51b1a21ee29471
train_000.jsonl
1598798100
You are given $$$n$$$ strings $$$s_1, s_2, \ldots, s_n$$$ consisting of lowercase Latin letters.In one operation you can remove a character from a string $$$s_i$$$ and insert it to an arbitrary position in a string $$$s_j$$$ ($$$j$$$ may be equal to $$$i$$$). You may perform this operation any number of times. Is it possible to make all $$$n$$$ strings equal?
256 megabytes
import java.awt.dnd.InvalidDnDOperationException; import java.io.*; import java.lang.reflect.Array; import java.nio.charset.CharsetEncoder; import java.util.*; public class Main { private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private static final boolean OFFLINE_WITHOUT_FILES = false; void solve() throws IOException { int t=readInt(); while (0<t--){ int n=readInt(); int [] countOfAlph=new int[50]; for (int i=0;i<n;++i){ String inp=readLine(); for (int j=0;j<inp.length();++j){ ++countOfAlph[Character.getNumericValue(inp.charAt(j))]; } } String answer="YES"; for (int el:countOfAlph){ if (el%n!=0){ answer="NO"; break; } } out.println(answer); } } public static void main(String[] args) { new Main(); } BufferedReader in; PrintWriter out; StringTokenizer tok; Main() { try { long timeStart = System.currentTimeMillis(); if (ONLINE_JUDGE || OFFLINE_WITHOUT_FILES) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } tok = new StringTokenizer(""); solve(); out.close(); long timeEnd = System.currentTimeMillis(); System.err.println("time = " + (timeEnd - timeStart) + " compiled"); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } String readLine() throws IOException { return in.readLine(); } String delimiter = " "; String readString() throws IOException { while (!tok.hasMoreTokens()) { String nextLine = readLine(); if (nextLine == null) return null; tok = new StringTokenizer(nextLine); } return tok.nextToken(delimiter); } int readInt() throws IOException { return Integer.parseInt(readString()); } long readLong() throws IOException { return Long.parseLong(readString()); } int[] sortArrayInt(int[] a) { Integer[] arr = new Integer[a.length]; for (int i = 0; i < a.length; i++) { arr[i] = a[i]; } Arrays.sort(arr); for (int i = 0; i < a.length; i++) { a[i] = arr[i]; } return a; } void sortArrayLong(long[] a) { Long[] arr = new Long[a.length]; for (int i = 0; i < a.length; i++) { arr[i] = a[i]; } Arrays.sort(arr); for (int i = 0; i < a.length; i++) { a[i] = arr[i]; } } }
Java
["4\n2\ncaa\ncbb\n3\ncba\ncba\ncbb\n4\nccab\ncbac\nbca\nacbcc\n4\nacb\ncaf\nc\ncbafc"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first test case, you can do the following: Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab". In the second test case, it is impossible to make all $$$n$$$ strings equal.
Java 11
standard input
[ "greedy", "strings" ]
3d6cd0a82513bc2119c9af3d1243846f
The first line contains $$$t$$$ ($$$1 \le t \le 10$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$): the number of strings. $$$n$$$ lines follow, the $$$i$$$-th line contains $$$s_i$$$ ($$$1 \le \lvert s_i \rvert \le 1000$$$). The sum of lengths of all strings in all test cases does not exceed $$$1000$$$.
800
If it is possible to make the strings equal, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can output each character in either lowercase or uppercase.
standard output
PASSED
0978da6ae4439f466170521230c3e7c0
train_000.jsonl
1598798100
You are given $$$n$$$ strings $$$s_1, s_2, \ldots, s_n$$$ consisting of lowercase Latin letters.In one operation you can remove a character from a string $$$s_i$$$ and insert it to an arbitrary position in a string $$$s_j$$$ ($$$j$$$ may be equal to $$$i$$$). You may perform this operation any number of times. Is it possible to make all $$$n$$$ strings equal?
256 megabytes
import java.io.*; import java.util.*; public class ques1 { public static void main(String[] args)throws Exception{ new ques1().run();} long mod=1000000000+7; void solve() throws Exception { for(int ii=ni();ii>0;ii--) { int N=ni(); String s[]=new String[N]; long c[]=new long[26]; for (int i = 0; i < N; i++) { s[i]=ns(); for (int j = 0; j < s[i].length(); j++) { c[s[i].charAt(j)-'a']++; } } int flag=0; for(int i=0;i<26;i++) { if(c[i]%N!=0) flag=1; } if(flag==0) out.println("Yes"); else out.println("No"); } } /*IMPLEMENTATION BY AMAN KOTIYAL, FAST INPUT OUTPUT & METHODS BELOW*/ private byte[] buf=new byte[1024]; private int index; private InputStream in; private int total; private SpaceCharFilter filter; PrintWriter out; int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } /* for (1/a)%mod = ( a^(mod-2) )%mod ----> use expo to calc -->(a^(mod-2)) */ long expo(long p,long q) /* (p^q)%mod */ { long z = 1; while (q>0) { if (q%2 == 1) { z = (z * p)%mod; } p = (p*p)%mod; q >>= 1; } return z; } void run()throws Exception { in=System.in; out = new PrintWriter(System.out); solve(); out.flush(); } private int scan()throws IOException { if(total<0) throw new InputMismatchException(); if(index>=total) { index=0; total=in.read(buf); if(total<=0) return -1; } return buf[index++]; } private int ni() throws IOException { int c = scan(); while (isSpaceChar(c)) c = scan(); int sgn = 1; if (c == '-') { sgn = -1; c = scan(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = scan(); } while (!isSpaceChar(c)); return res * sgn; } private long nl() throws IOException { long num = 0; int b; boolean minus = false; while ((b = scan()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = scan(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = scan(); } } private double nd() throws IOException{ return Double.parseDouble(ns()); } private String ns() throws IOException { int c = scan(); while (isSpaceChar(c)) c = scan(); StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) res.appendCodePoint(c); c = scan(); } while (!isSpaceChar(c)); return res.toString(); } private String nss() throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); return br.readLine(); } private char nc() throws IOException { int c = scan(); while (isSpaceChar(c)) c = scan(); return (char) c; } private boolean isWhiteSpace(int n) { if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1) return true; return false; } private boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhiteSpace(c); } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["4\n2\ncaa\ncbb\n3\ncba\ncba\ncbb\n4\nccab\ncbac\nbca\nacbcc\n4\nacb\ncaf\nc\ncbafc"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first test case, you can do the following: Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab". In the second test case, it is impossible to make all $$$n$$$ strings equal.
Java 11
standard input
[ "greedy", "strings" ]
3d6cd0a82513bc2119c9af3d1243846f
The first line contains $$$t$$$ ($$$1 \le t \le 10$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$): the number of strings. $$$n$$$ lines follow, the $$$i$$$-th line contains $$$s_i$$$ ($$$1 \le \lvert s_i \rvert \le 1000$$$). The sum of lengths of all strings in all test cases does not exceed $$$1000$$$.
800
If it is possible to make the strings equal, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can output each character in either lowercase or uppercase.
standard output
PASSED
416ccdc9ae64cfe24f269746fadaade4
train_000.jsonl
1598798100
You are given $$$n$$$ strings $$$s_1, s_2, \ldots, s_n$$$ consisting of lowercase Latin letters.In one operation you can remove a character from a string $$$s_i$$$ and insert it to an arbitrary position in a string $$$s_j$$$ ($$$j$$$ may be equal to $$$i$$$). You may perform this operation any number of times. Is it possible to make all $$$n$$$ strings equal?
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int t=scan.nextInt(); while(t-->0) { int n=scan.nextInt(); int[] arr = new int[26]; for(int i=0;i<n;i++) { String st=scan.next(); for(int j=0;j<st.length();++j) arr[st.charAt(j)-'a']++; } int i; for(i=0;i<26;i++) if(arr[i]%n!=0) break; if(i==26) System.out.println("YES"); else System.out.println("NO"); } } }
Java
["4\n2\ncaa\ncbb\n3\ncba\ncba\ncbb\n4\nccab\ncbac\nbca\nacbcc\n4\nacb\ncaf\nc\ncbafc"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first test case, you can do the following: Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab". In the second test case, it is impossible to make all $$$n$$$ strings equal.
Java 11
standard input
[ "greedy", "strings" ]
3d6cd0a82513bc2119c9af3d1243846f
The first line contains $$$t$$$ ($$$1 \le t \le 10$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$): the number of strings. $$$n$$$ lines follow, the $$$i$$$-th line contains $$$s_i$$$ ($$$1 \le \lvert s_i \rvert \le 1000$$$). The sum of lengths of all strings in all test cases does not exceed $$$1000$$$.
800
If it is possible to make the strings equal, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can output each character in either lowercase or uppercase.
standard output
PASSED
2c7897536ad6235e3ed7f7124ea1f921
train_000.jsonl
1598798100
You are given $$$n$$$ strings $$$s_1, s_2, \ldots, s_n$$$ consisting of lowercase Latin letters.In one operation you can remove a character from a string $$$s_i$$$ and insert it to an arbitrary position in a string $$$s_j$$$ ($$$j$$$ may be equal to $$$i$$$). You may perform this operation any number of times. Is it possible to make all $$$n$$$ strings equal?
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class CP{ public static OutputStream out=new BufferedOutputStream(System.out); static Scanner sc=new Scanner(System.in); static long mod=1000000007l; static int INF=10000000; static int[] rr=new int[]{1, 0, -1, 0}; //rook row move static int[] rc=new int[]{0, 1, 0, -1}; //rook col move //nl-->neew line; //l-->line; //arp-->array print; //arpnl-->array print new line public static void nl(Object o) throws IOException{out.write((o+"\n").getBytes()); } public static void l(Object o) throws IOException{out.write((o+"").getBytes());} public static void arp(int[] o) throws IOException{for(int i=0;i<o.length;i++) out.write((o[i]+" ").getBytes()); out.write(("\n").getBytes());} public static void arpnl(int[] o) throws IOException{for(int i=0;i<o.length;i++) out.write((o[i]+"\n").getBytes());} public static void scanl(long[] a,int n) {for(int i=0;i<n;i++) a[i]=sc.nextLong();} public static void scani(int[] a,int n) {for(int i=0;i<n;i++) a[i]=sc.nextInt();} public static void scan2D(int[][] a,int n,int m) {for(int i=0;i<n;i++) for(int j=0;j<m;j++) a[i][j]=sc.nextInt();} // static long cnt; static TreeSet<Integer> ans; static int n,d; static int[][] dp; static HashMap<Pair,Boolean> arrl; static Stack<Integer> stk; static Queue<Integer> queue; static HashSet<Integer> mtrnode; static ArrayList<Pair> arrlans; static int[] ff; public static void main(String[] args) throws IOException{ long sttm=System.currentTimeMillis(); long mod=1000000007l; int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); int[] cnt=new int[26]; for(int i=0;i<n;i++){ String s=sc.next(); for(char c:s.toCharArray()){ cnt[c-'a']++; } } boolean con=true; for(int i=0;i<26;i++){ if(cnt[i]%n!=0){ con=false; break; } } if(con) nl("YES"); else nl("NO"); } out.flush(); } } class Pair{ int x; int y; Pair(int x,int y){ this.x=x; this.y=y; } }
Java
["4\n2\ncaa\ncbb\n3\ncba\ncba\ncbb\n4\nccab\ncbac\nbca\nacbcc\n4\nacb\ncaf\nc\ncbafc"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first test case, you can do the following: Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab". In the second test case, it is impossible to make all $$$n$$$ strings equal.
Java 11
standard input
[ "greedy", "strings" ]
3d6cd0a82513bc2119c9af3d1243846f
The first line contains $$$t$$$ ($$$1 \le t \le 10$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$): the number of strings. $$$n$$$ lines follow, the $$$i$$$-th line contains $$$s_i$$$ ($$$1 \le \lvert s_i \rvert \le 1000$$$). The sum of lengths of all strings in all test cases does not exceed $$$1000$$$.
800
If it is possible to make the strings equal, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can output each character in either lowercase or uppercase.
standard output
PASSED
0868e9ff2a6211ade6cbb376812014bc
train_000.jsonl
1598798100
You are given $$$n$$$ strings $$$s_1, s_2, \ldots, s_n$$$ consisting of lowercase Latin letters.In one operation you can remove a character from a string $$$s_i$$$ and insert it to an arbitrary position in a string $$$s_j$$$ ($$$j$$$ may be equal to $$$i$$$). You may perform this operation any number of times. Is it possible to make all $$$n$$$ strings equal?
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int t = scn.nextInt(); while (t-- > 0) { int n = scn.nextInt(); String[] arr = new String[n]; for (int i = 0; i < n; i++) { arr[i] = scn.next(); } HashMap < Character, Integer > map = new HashMap < > (); for (int j = 0; j < n; j++) { String str = arr[j]; for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (map.containsKey(ch)) { map.put(ch, map.get(ch) + 1); } else { map.put(ch, 1); } } } boolean flag=true; for(Character ch:map.keySet()) { if(map.get(ch)<n||map.get(ch)%n!=0) { flag = false; } } if(flag) { System.out.println("YES"); } else{ System.out.println("NO"); } } } }
Java
["4\n2\ncaa\ncbb\n3\ncba\ncba\ncbb\n4\nccab\ncbac\nbca\nacbcc\n4\nacb\ncaf\nc\ncbafc"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first test case, you can do the following: Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab". In the second test case, it is impossible to make all $$$n$$$ strings equal.
Java 11
standard input
[ "greedy", "strings" ]
3d6cd0a82513bc2119c9af3d1243846f
The first line contains $$$t$$$ ($$$1 \le t \le 10$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$): the number of strings. $$$n$$$ lines follow, the $$$i$$$-th line contains $$$s_i$$$ ($$$1 \le \lvert s_i \rvert \le 1000$$$). The sum of lengths of all strings in all test cases does not exceed $$$1000$$$.
800
If it is possible to make the strings equal, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can output each character in either lowercase or uppercase.
standard output
PASSED
3486915bc48ea068162441a87c934f56
train_000.jsonl
1598798100
You are given $$$n$$$ strings $$$s_1, s_2, \ldots, s_n$$$ consisting of lowercase Latin letters.In one operation you can remove a character from a string $$$s_i$$$ and insert it to an arbitrary position in a string $$$s_j$$$ ($$$j$$$ may be equal to $$$i$$$). You may perform this operation any number of times. Is it possible to make all $$$n$$$ strings equal?
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0){ int n = sc.nextInt(); HashMap<Character,Integer> map = new HashMap<Character,Integer>(); for(int p=0;p<n;p++){ String str = sc.next(); for(int i=0;i<str.length();i++){ char ch = str.charAt(i); if(map.containsKey(ch)){ map.put(ch,map.get(ch)+1); }else{ map.put(ch,1); } } } String ans ="YES"; for(Integer c : map.values()){ if(c<n || (c%n)!=0){ ans = "NO"; break; } } System.out.println(ans); } } }
Java
["4\n2\ncaa\ncbb\n3\ncba\ncba\ncbb\n4\nccab\ncbac\nbca\nacbcc\n4\nacb\ncaf\nc\ncbafc"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first test case, you can do the following: Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab". In the second test case, it is impossible to make all $$$n$$$ strings equal.
Java 11
standard input
[ "greedy", "strings" ]
3d6cd0a82513bc2119c9af3d1243846f
The first line contains $$$t$$$ ($$$1 \le t \le 10$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$): the number of strings. $$$n$$$ lines follow, the $$$i$$$-th line contains $$$s_i$$$ ($$$1 \le \lvert s_i \rvert \le 1000$$$). The sum of lengths of all strings in all test cases does not exceed $$$1000$$$.
800
If it is possible to make the strings equal, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can output each character in either lowercase or uppercase.
standard output
PASSED
a071bfeb4b59ecee9acde31744bdd876
train_000.jsonl
1598798100
You are given $$$n$$$ strings $$$s_1, s_2, \ldots, s_n$$$ consisting of lowercase Latin letters.In one operation you can remove a character from a string $$$s_i$$$ and insert it to an arbitrary position in a string $$$s_j$$$ ($$$j$$$ may be equal to $$$i$$$). You may perform this operation any number of times. Is it possible to make all $$$n$$$ strings equal?
256 megabytes
import java.util.*; import java.io.*; public class Solution { public static void main(String[] args) throws Exception { BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(buffer.readLine()); while(N-- > 0){ int size = Integer.parseInt(buffer.readLine()); int k = size; int[] arr = new int[26]; while(size-- > 0){ String[] s = buffer.readLine().split(""); for(int i=0; i<s.length; i++){ arr[(int)s[i].charAt(0) -97]++; } } if(size == 1){ System.out.println("YES"); continue; } int flag = 0; for(int i=0 ;i<arr.length; i++){ if(arr[i] %k != 0 ){ System.out.println("NO"); flag = 1; break; } } if(flag == 0) System.out.println("YES"); } } }
Java
["4\n2\ncaa\ncbb\n3\ncba\ncba\ncbb\n4\nccab\ncbac\nbca\nacbcc\n4\nacb\ncaf\nc\ncbafc"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first test case, you can do the following: Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab". In the second test case, it is impossible to make all $$$n$$$ strings equal.
Java 11
standard input
[ "greedy", "strings" ]
3d6cd0a82513bc2119c9af3d1243846f
The first line contains $$$t$$$ ($$$1 \le t \le 10$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$): the number of strings. $$$n$$$ lines follow, the $$$i$$$-th line contains $$$s_i$$$ ($$$1 \le \lvert s_i \rvert \le 1000$$$). The sum of lengths of all strings in all test cases does not exceed $$$1000$$$.
800
If it is possible to make the strings equal, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can output each character in either lowercase or uppercase.
standard output
PASSED
dc95829b144c699491bb4c88e1b79b16
train_000.jsonl
1598798100
You are given $$$n$$$ strings $$$s_1, s_2, \ldots, s_n$$$ consisting of lowercase Latin letters.In one operation you can remove a character from a string $$$s_i$$$ and insert it to an arbitrary position in a string $$$s_j$$$ ($$$j$$$ may be equal to $$$i$$$). You may perform this operation any number of times. Is it possible to make all $$$n$$$ strings equal?
256 megabytes
import java.util.*; public class A { public static void main(String args[]) { Scanner scan = new Scanner(System.in); int t = scan.nextInt(); x:while(t-->0) { int n = scan.nextInt(); // String a[] = new String[n]; String s = ""; for(int i =0;i<n;i++) s += scan.next(); HashMap<Character,Integer> c = new HashMap<>(); for(int i=0;i<s.length();i++) { if(c.containsKey(s.charAt(i))) { c.put(s.charAt(i), c.get(s.charAt(i))+1); } else { c.put(s.charAt(i), 1); } } for(Map.Entry entry:c.entrySet()) { if((int)entry.getValue()%n!=0) { System.out.println("NO"); continue x; } } System.out.println("YES"); } } }
Java
["4\n2\ncaa\ncbb\n3\ncba\ncba\ncbb\n4\nccab\ncbac\nbca\nacbcc\n4\nacb\ncaf\nc\ncbafc"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first test case, you can do the following: Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab". In the second test case, it is impossible to make all $$$n$$$ strings equal.
Java 11
standard input
[ "greedy", "strings" ]
3d6cd0a82513bc2119c9af3d1243846f
The first line contains $$$t$$$ ($$$1 \le t \le 10$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$): the number of strings. $$$n$$$ lines follow, the $$$i$$$-th line contains $$$s_i$$$ ($$$1 \le \lvert s_i \rvert \le 1000$$$). The sum of lengths of all strings in all test cases does not exceed $$$1000$$$.
800
If it is possible to make the strings equal, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can output each character in either lowercase or uppercase.
standard output
PASSED
8c98a0fe170146c3b3cae5ce58208cb7
train_000.jsonl
1598798100
You are given $$$n$$$ strings $$$s_1, s_2, \ldots, s_n$$$ consisting of lowercase Latin letters.In one operation you can remove a character from a string $$$s_i$$$ and insert it to an arbitrary position in a string $$$s_j$$$ ($$$j$$$ may be equal to $$$i$$$). You may perform this operation any number of times. Is it possible to make all $$$n$$$ strings equal?
256 megabytes
/* package codechef; // don't place package name! */ 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 Codechef { public static void main (String[] args) throws java.lang.Exception { // your code goes here BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); while(t-->0){ String ss[]=br.readLine().split(" "); int n=Integer.parseInt(ss[0]); // int f=Integer.parseInt(ss[1]); String s[]=new String[n]; Map<Character,Integer> map=new HashMap<>(); for (int i=0;i<n;++i){ s[i]=br.readLine(); for(int j=0;j<s[i].length();++j){ if(map.containsKey(s[i].charAt(j))){ map.put(s[i].charAt(j),map.get(s[i].charAt(j))+1); } else{ map.put(s[i].charAt(j),1); } } } boolean b=true; for(Map.Entry<Character,Integer> entry: map.entrySet()){ if(entry.getValue()%n!=0){ b=false; break; } } if(b) System.out.println("yes"); else System.out.println("no"); } } }
Java
["4\n2\ncaa\ncbb\n3\ncba\ncba\ncbb\n4\nccab\ncbac\nbca\nacbcc\n4\nacb\ncaf\nc\ncbafc"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first test case, you can do the following: Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab". In the second test case, it is impossible to make all $$$n$$$ strings equal.
Java 11
standard input
[ "greedy", "strings" ]
3d6cd0a82513bc2119c9af3d1243846f
The first line contains $$$t$$$ ($$$1 \le t \le 10$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$): the number of strings. $$$n$$$ lines follow, the $$$i$$$-th line contains $$$s_i$$$ ($$$1 \le \lvert s_i \rvert \le 1000$$$). The sum of lengths of all strings in all test cases does not exceed $$$1000$$$.
800
If it is possible to make the strings equal, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can output each character in either lowercase or uppercase.
standard output
PASSED
cbb59ab510c1f1fa16c74f5600139142
train_000.jsonl
1598798100
You are given $$$n$$$ strings $$$s_1, s_2, \ldots, s_n$$$ consisting of lowercase Latin letters.In one operation you can remove a character from a string $$$s_i$$$ and insert it to an arbitrary position in a string $$$s_j$$$ ($$$j$$$ may be equal to $$$i$$$). You may perform this operation any number of times. Is it possible to make all $$$n$$$ strings equal?
256 megabytes
import java.io.*; import java.util.*; import java.util.Map.Entry; public class A { public static void main(String[] agrs) { FastScanner sc = new FastScanner(); int yo = sc.nextInt(); while(yo-->0) { int n = sc.nextInt(); String[] arr = new String[n]; String sum = ""; for(int i = 0; i < n; i++) { arr[i] = sc.next(); sum += arr[i]; } // System.out.println(sum); if(check(sum,n)) { System.out.println("YES"); } else { System.out.println("NO"); } } } private static boolean check(String string, int n) { int[] ch = new int[26]; for(char e : string.toCharArray()) { ch[e-'a']++; } // for(int e : ch) { // System.out.print(e + " "); // } // System.out.println(); // System.out.println(5 % 3); for(int e : ch) { if(e != 0 && (e%n != 0 || e < n)) { return false; } } return true; } static int mod = 1000000007; static long pow(int a, int b) { if(b == 0) { return 1; } if(b == 1) { return a; } if(b%2 == 0) { long ans = pow(a,b/2); return ans*ans; } else { long ans = pow(a,(b-1)/2); return a * ans * ans; } } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["4\n2\ncaa\ncbb\n3\ncba\ncba\ncbb\n4\nccab\ncbac\nbca\nacbcc\n4\nacb\ncaf\nc\ncbafc"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first test case, you can do the following: Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab". In the second test case, it is impossible to make all $$$n$$$ strings equal.
Java 11
standard input
[ "greedy", "strings" ]
3d6cd0a82513bc2119c9af3d1243846f
The first line contains $$$t$$$ ($$$1 \le t \le 10$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$): the number of strings. $$$n$$$ lines follow, the $$$i$$$-th line contains $$$s_i$$$ ($$$1 \le \lvert s_i \rvert \le 1000$$$). The sum of lengths of all strings in all test cases does not exceed $$$1000$$$.
800
If it is possible to make the strings equal, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can output each character in either lowercase or uppercase.
standard output
PASSED
f8241da0df96d0c776be23f8146207ac
train_000.jsonl
1598798100
You are given $$$n$$$ strings $$$s_1, s_2, \ldots, s_n$$$ consisting of lowercase Latin letters.In one operation you can remove a character from a string $$$s_i$$$ and insert it to an arbitrary position in a string $$$s_j$$$ ($$$j$$$ may be equal to $$$i$$$). You may perform this operation any number of times. Is it possible to make all $$$n$$$ strings equal?
256 megabytes
import java.io.*; import java.util.*; public class Ishu { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int t=scan.nextInt(); while(t-->0) { int n=scan.nextInt(); String str; int[] a = new int[26]; int i; for(i=0;i<n;++i) { str=scan.next(); for(int j=0;j<str.length();++j) a[str.charAt(j)-'a']++; } for(i=0;i<26;++i) if(a[i]%n!=0) break; if(i==26) System.out.println("YES"); else System.out.println("NO"); } } }
Java
["4\n2\ncaa\ncbb\n3\ncba\ncba\ncbb\n4\nccab\ncbac\nbca\nacbcc\n4\nacb\ncaf\nc\ncbafc"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first test case, you can do the following: Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab". In the second test case, it is impossible to make all $$$n$$$ strings equal.
Java 11
standard input
[ "greedy", "strings" ]
3d6cd0a82513bc2119c9af3d1243846f
The first line contains $$$t$$$ ($$$1 \le t \le 10$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$): the number of strings. $$$n$$$ lines follow, the $$$i$$$-th line contains $$$s_i$$$ ($$$1 \le \lvert s_i \rvert \le 1000$$$). The sum of lengths of all strings in all test cases does not exceed $$$1000$$$.
800
If it is possible to make the strings equal, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can output each character in either lowercase or uppercase.
standard output
PASSED
f028e2d80aab7bfe3f30b5aa74a3f787
train_000.jsonl
1598798100
You are given $$$n$$$ strings $$$s_1, s_2, \ldots, s_n$$$ consisting of lowercase Latin letters.In one operation you can remove a character from a string $$$s_i$$$ and insert it to an arbitrary position in a string $$$s_j$$$ ($$$j$$$ may be equal to $$$i$$$). You may perform this operation any number of times. Is it possible to make all $$$n$$$ strings equal?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class A { public static void main(String[] args) { FastReader reader = new FastReader(); int tests = reader.nextInt(); for(int test = 1; test <= tests; test++) { int n = reader.nextInt(); int[] chars = new int[40]; for(int i = 0; i < n; i++) { String next = reader.next(); for(int j = 0; j < next.length(); j++) { chars[next.charAt(j)-'a']++; } } boolean check = true; for(int i = 0; i < chars.length; i++) { if(chars[i] % n != 0) { check = false; break; } } if(check) { System.out.println("Yes"); } else { System.out.println("No"); } } } 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\n2\ncaa\ncbb\n3\ncba\ncba\ncbb\n4\nccab\ncbac\nbca\nacbcc\n4\nacb\ncaf\nc\ncbafc"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first test case, you can do the following: Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab". In the second test case, it is impossible to make all $$$n$$$ strings equal.
Java 11
standard input
[ "greedy", "strings" ]
3d6cd0a82513bc2119c9af3d1243846f
The first line contains $$$t$$$ ($$$1 \le t \le 10$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$): the number of strings. $$$n$$$ lines follow, the $$$i$$$-th line contains $$$s_i$$$ ($$$1 \le \lvert s_i \rvert \le 1000$$$). The sum of lengths of all strings in all test cases does not exceed $$$1000$$$.
800
If it is possible to make the strings equal, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can output each character in either lowercase or uppercase.
standard output
PASSED
995a542ec451f1c3285756fcdad03a82
train_000.jsonl
1598798100
You are given $$$n$$$ strings $$$s_1, s_2, \ldots, s_n$$$ consisting of lowercase Latin letters.In one operation you can remove a character from a string $$$s_i$$$ and insert it to an arbitrary position in a string $$$s_j$$$ ($$$j$$$ may be equal to $$$i$$$). You may perform this operation any number of times. Is it possible to make all $$$n$$$ strings equal?
256 megabytes
import java.util.Scanner; public class Main { public static String check(int[] ascii,int n) { for(int i=0;i<ascii.length;i++) { if(ascii[i]%n!=0) { return "NO"; } } return "YES"; } public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); for(int i=0;i<t;i++) { int n=sc.nextInt(); int ascii[]=new int[26];//representing all letters for(int j=0;j<n;j++) { String s=sc.next(); char[] a=s.toCharArray(); for(int k=0;k<a.length;k++) { int temp=a[k];//ascii value of the letter ascii[temp-97]++; } } System.out.println(check(ascii,n)); } sc.close(); } }
Java
["4\n2\ncaa\ncbb\n3\ncba\ncba\ncbb\n4\nccab\ncbac\nbca\nacbcc\n4\nacb\ncaf\nc\ncbafc"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first test case, you can do the following: Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab". In the second test case, it is impossible to make all $$$n$$$ strings equal.
Java 11
standard input
[ "greedy", "strings" ]
3d6cd0a82513bc2119c9af3d1243846f
The first line contains $$$t$$$ ($$$1 \le t \le 10$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$): the number of strings. $$$n$$$ lines follow, the $$$i$$$-th line contains $$$s_i$$$ ($$$1 \le \lvert s_i \rvert \le 1000$$$). The sum of lengths of all strings in all test cases does not exceed $$$1000$$$.
800
If it is possible to make the strings equal, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can output each character in either lowercase or uppercase.
standard output
PASSED
a758761d3fdfd9b284d527b4e35e27dc
train_000.jsonl
1598798100
You are given $$$n$$$ strings $$$s_1, s_2, \ldots, s_n$$$ consisting of lowercase Latin letters.In one operation you can remove a character from a string $$$s_i$$$ and insert it to an arbitrary position in a string $$$s_j$$$ ($$$j$$$ may be equal to $$$i$$$). You may perform this operation any number of times. Is it possible to make all $$$n$$$ strings equal?
256 megabytes
import java.util.*; import java.util.function.LongFunction; public class test{ public static void main(String args[]) { Scanner take=new Scanner(System.in); int t=take.nextInt(); String s[]; int n,i,j,a[],k; while(t--!=0) { n=take.nextInt(); s=new String[n]; a=new int[26]; for(i=0;i<n;i++) s[i]=take.next(); for(i=0;i<n;i++) { for(j=0;j<s[i].length();j++) { a[s[i].charAt(j)-'a']++; } } for(i=0;i<26;i++) { if(a[i]%n!=0) { System.out.println("NO"); break; } } if(i==26) System.out.println("YES"); } } }
Java
["4\n2\ncaa\ncbb\n3\ncba\ncba\ncbb\n4\nccab\ncbac\nbca\nacbcc\n4\nacb\ncaf\nc\ncbafc"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first test case, you can do the following: Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab". In the second test case, it is impossible to make all $$$n$$$ strings equal.
Java 11
standard input
[ "greedy", "strings" ]
3d6cd0a82513bc2119c9af3d1243846f
The first line contains $$$t$$$ ($$$1 \le t \le 10$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$): the number of strings. $$$n$$$ lines follow, the $$$i$$$-th line contains $$$s_i$$$ ($$$1 \le \lvert s_i \rvert \le 1000$$$). The sum of lengths of all strings in all test cases does not exceed $$$1000$$$.
800
If it is possible to make the strings equal, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can output each character in either lowercase or uppercase.
standard output
PASSED
ed36c9dc7d00a1760ae129720bb51876
train_000.jsonl
1598798100
You are given $$$n$$$ strings $$$s_1, s_2, \ldots, s_n$$$ consisting of lowercase Latin letters.In one operation you can remove a character from a string $$$s_i$$$ and insert it to an arbitrary position in a string $$$s_j$$$ ($$$j$$$ may be equal to $$$i$$$). You may perform this operation any number of times. Is it possible to make all $$$n$$$ strings equal?
256 megabytes
import java.util.*; import java.util.function.LongFunction; public class test{ public static void main(String args[]) { Scanner take=new Scanner(System.in); int t=take.nextInt(); String s[]; int n,i,j,a[]; while(t--!=0) { n=take.nextInt(); s=new String[n]; a=new int[26]; for(i=0;i<n;i++) s[i]=take.next(); for(i=0;i<n;i++) { for(j=0;j<s[i].length();j++) { a[s[i].charAt(j)-'a']++; } } for(i=0;i<26;i++) { if(a[i]%n!=0) { System.out.println("NO"); break; } } if(i==26) System.out.println("YES"); } } }
Java
["4\n2\ncaa\ncbb\n3\ncba\ncba\ncbb\n4\nccab\ncbac\nbca\nacbcc\n4\nacb\ncaf\nc\ncbafc"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first test case, you can do the following: Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab". In the second test case, it is impossible to make all $$$n$$$ strings equal.
Java 11
standard input
[ "greedy", "strings" ]
3d6cd0a82513bc2119c9af3d1243846f
The first line contains $$$t$$$ ($$$1 \le t \le 10$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$): the number of strings. $$$n$$$ lines follow, the $$$i$$$-th line contains $$$s_i$$$ ($$$1 \le \lvert s_i \rvert \le 1000$$$). The sum of lengths of all strings in all test cases does not exceed $$$1000$$$.
800
If it is possible to make the strings equal, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can output each character in either lowercase or uppercase.
standard output
PASSED
b5555133bc1e6215b00a0d54ad3c2296
train_000.jsonl
1598798100
You are given $$$n$$$ strings $$$s_1, s_2, \ldots, s_n$$$ consisting of lowercase Latin letters.In one operation you can remove a character from a string $$$s_i$$$ and insert it to an arbitrary position in a string $$$s_j$$$ ($$$j$$$ may be equal to $$$i$$$). You may perform this operation any number of times. Is it possible to make all $$$n$$$ strings equal?
256 megabytes
import java.util.*; import java.io.*; import java.math.*; /* javac Main.java java Main <input.txt> output.txt */ public class Main { public static void process()throws IOException { int n=ni(); int p=n; int freq[]=new int[26]; Arrays.fill(freq,0); while(n-->0) { String s=nn(); for(int i=0;i<s.length();i++) { char ch=s.charAt(i); freq[ch-'a']++; } } int flag=0; for(int i=0;i<26;i++) { if(freq[i]>0) { if(freq[i]%p==0) continue; else {flag=-1;break;}} } if(flag==-1) pn("NO"); else pn("YES"); } static AnotherReader sc; static PrintWriter out; public static void main(String[]args)throws IOException { out = new PrintWriter(System.out); sc=new AnotherReader(); boolean oj = true; //PrintWriter out=new PrintWriter("output"); //oj = System.getProperty("ONLINE_JUDGE") != null; //if(!oj) sc=new AnotherReader(100); //int i=1; int T=ni(); while(T-->0) //{ //p("Case #"+i+": "); process(); //i++; //} long s = System.currentTimeMillis(); out.flush(); if(!oj) System.out.println(System.currentTimeMillis()-s+"ms"); System.out.close(); } static void sort(long arr[],int n) { shuffle(arr,n); Arrays.sort(arr); } static void shuffle(long arr[],int n) { Random r=new Random(); for(int i=0;i<n;i++) { long temp=arr[i]; int pos=i+r.nextInt(n-i); arr[i]=arr[pos]; arr[pos]=temp; } } static void pn(Object o){out.println(o);} static void p(Object o){out.print(o);} static void pni(Object o){out.println(o);System.out.flush();} static int ni()throws IOException{return sc.nextInt();} static long nl()throws IOException{return sc.nextLong();} static double nd()throws IOException{return sc.nextDouble();} static String nln()throws IOException{return sc.nextLine();} static String nn()throws IOException{return sc.next();} static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));} static int[] iarr(int N)throws IOException{int[]ARR=new int[N];for(int i=0;i<N;i++){ARR[i]=ni();}return ARR;} static long[] larr(int N)throws IOException{long[]ARR=new long[N];for(int i=0;i<N;i++){ARR[i]=nl();}return ARR;} static boolean multipleTC=false; ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class AnotherReader{BufferedReader br; StringTokenizer st; AnotherReader()throws FileNotFoundException{ br=new BufferedReader(new InputStreamReader(System.in));} AnotherReader(int a)throws FileNotFoundException{ br = new BufferedReader(new FileReader("input.txt"));} String next()throws IOException{ while (st == null || !st.hasMoreElements()) {try{ st = new StringTokenizer(br.readLine());} catch (IOException e){ e.printStackTrace(); }} return st.nextToken(); } int nextInt() throws IOException{ return Integer.parseInt(next());} long nextLong() throws IOException {return Long.parseLong(next());} double nextDouble()throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException{ String str = ""; try{ str = br.readLine();} catch (IOException e){ e.printStackTrace();} return str;}} ///////////////////////////////////////////////////////////////////////////////////////////////////////////// }
Java
["4\n2\ncaa\ncbb\n3\ncba\ncba\ncbb\n4\nccab\ncbac\nbca\nacbcc\n4\nacb\ncaf\nc\ncbafc"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first test case, you can do the following: Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab". In the second test case, it is impossible to make all $$$n$$$ strings equal.
Java 11
standard input
[ "greedy", "strings" ]
3d6cd0a82513bc2119c9af3d1243846f
The first line contains $$$t$$$ ($$$1 \le t \le 10$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$): the number of strings. $$$n$$$ lines follow, the $$$i$$$-th line contains $$$s_i$$$ ($$$1 \le \lvert s_i \rvert \le 1000$$$). The sum of lengths of all strings in all test cases does not exceed $$$1000$$$.
800
If it is possible to make the strings equal, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can output each character in either lowercase or uppercase.
standard output
PASSED
c96c6e293775be3f6c826515c2c8133d
train_000.jsonl
1598798100
You are given $$$n$$$ strings $$$s_1, s_2, \ldots, s_n$$$ consisting of lowercase Latin letters.In one operation you can remove a character from a string $$$s_i$$$ and insert it to an arbitrary position in a string $$$s_j$$$ ($$$j$$$ may be equal to $$$i$$$). You may perform this operation any number of times. Is it possible to make all $$$n$$$ strings equal?
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t>0){ t--; int n= sc.nextInt(); String s[] = new String[n] ; for(int i=0;i<n;i++){ s[i] = sc.next(); } int a[] = new int[26]; for(int i=0;i<26;i++){ a[i]=0; } int total=0; for(int i=0;i<n;i++){ total += s[i].length(); for(int j=0;j<s[i].length();j++){ a[(int)(s[i].charAt(j)-'a')]++; } } boolean posses = false; for(int i=0;i<26;i++){ if(a[i]%n!=0){ posses = true; } } if(total%n!=0||posses){ System.out.println("NO"); }else{ System.out.println("YES"); } } } }
Java
["4\n2\ncaa\ncbb\n3\ncba\ncba\ncbb\n4\nccab\ncbac\nbca\nacbcc\n4\nacb\ncaf\nc\ncbafc"]
1 second
["YES\nNO\nYES\nNO"]
NoteIn the first test case, you can do the following: Remove the third character of the first string and insert it after the second character of the second string, making the two strings "ca" and "cbab" respectively. Remove the second character of the second string and insert it after the second character of the first string, making both strings equal to "cab". In the second test case, it is impossible to make all $$$n$$$ strings equal.
Java 11
standard input
[ "greedy", "strings" ]
3d6cd0a82513bc2119c9af3d1243846f
The first line contains $$$t$$$ ($$$1 \le t \le 10$$$): the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$): the number of strings. $$$n$$$ lines follow, the $$$i$$$-th line contains $$$s_i$$$ ($$$1 \le \lvert s_i \rvert \le 1000$$$). The sum of lengths of all strings in all test cases does not exceed $$$1000$$$.
800
If it is possible to make the strings equal, print "YES" (without quotes). Otherwise, print "NO" (without quotes). You can output each character in either lowercase or uppercase.
standard output
PASSED
8fe0dd472a76d1fbce7731c6196e7884
train_000.jsonl
1336145400
The Great Mushroom King descended to the dwarves, but not everyone managed to see him. Only the few chosen ones could see the King.We know that only LCM(k2l + 1, k2l + 1 + 1, ..., k2r + 1) dwarves can see the Great Mushroom King. Numbers k, l, r are chosen by the Great Mushroom King himself in some complicated manner which is unclear to common dwarves. The dwarven historians decided to document all visits of the Great Mushroom King. For each visit the dwarven historians know three integers ki, li, ri, chosen by the Great Mushroom King for this visit. They also know a prime number pi. Help them to count the remainder of dividing the number of dwarves who can see the King, by number pi, for each visit.
256 megabytes
import java.io.*; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import java.util.Map.Entry; public class Main implements Runnable { static final int MOD = (int) 1e9 + 7; static final int MI = (int) 1e9; static final long ML = (long) 1e18; static final Reader in = new Reader(); static final PrintWriter out = new PrintWriter(System.out); StringBuilder answer = new StringBuilder(); Random random = new Random(751454315315L + System.currentTimeMillis()); public static void main(String[] args) { new Thread(null, new Main(), "persefone", 1 << 28).start(); } @Override public void run() { solve(); printf(); flush(); } void solve() { int n = in.nextInt(); for (int i = 0; i < n; i++) { long k = in.nextLong(); long l = in.nextLong(); long r = in.nextLong(); long p = in.nextLong(); if (k == 1) { printf(2 % p); continue; } if (p == 2) { printf(1 - k % 2); continue; } // 2^l mod (p - 1) long ml = Utils.modPow(2, l, p - 1); if (ml == 0) { ml = p - 1; } long mkl = Utils.modPow(k, ml, p); long ans = 1; if (mkl == 0) { ans = 1; } else if (mkl == 1) { ans = Utils.modPow(2, r - l + 1, p); } else { long mr = Utils.modPow(2, r + 1, p - 1); if (mr == 0) { mr = p - 1; } long mkr = (Utils.modPow(k, mr, p) - 1 + p) % p; ans = mkr * Utils.modPow(mkl - 1, p - 2, p) % p; } if (k % 2 == 1) { long d = Utils.modPow(2, r - l, p); ans = ans * Utils.modPow(d, p - 2, p) % p; } printf(ans); } } static class Utils { static long modPow(long base, long exponent, long mod) { if (exponent == 0) { return 1; } long m = modPow(base, exponent >> 1, mod); return exponent % 2 == 0 ? m * m % mod : m * m % mod * base % mod; } } void printf() { out.print(answer); } void close() { out.close(); } void flush() { out.flush(); } void printf(Stream<?> str) { str.forEach(o -> add(o, " ")); add("\n"); } void printf(Object... obj) { printf(false, obj); } void printfWithDescription(Object... obj) { printf(true, obj); } private void printf(boolean b, Object... obj) { if (obj.length > 1) { for (int i = 0; i < obj.length; i++) { if (b) add(obj[i].getClass().getSimpleName(), " - "); if (obj[i] instanceof Collection<?>) { printf((Collection<?>) obj[i]); } else if (obj[i] instanceof int[][]) { printf((int[][]) obj[i]); } else if (obj[i] instanceof long[][]) { printf((long[][]) obj[i]); } else if (obj[i] instanceof double[][]) { printf((double[][]) obj[i]); } else printf(obj[i]); } return; } if (b) add(obj[0].getClass().getSimpleName(), " - "); printf(obj[0]); } void printf(Object o) { if (o instanceof int[]) printf(Arrays.stream((int[]) o).boxed()); else if (o instanceof char[]) printf(new String((char[]) o)); else if (o instanceof long[]) printf(Arrays.stream((long[]) o).boxed()); else if (o instanceof double[]) printf(Arrays.stream((double[]) o).boxed()); else if (o instanceof boolean[]) { for (boolean b : (boolean[]) o) add(b, " "); add("\n"); } else add(o, "\n"); } void printf(int[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(long[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(double[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(boolean[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(Collection<?> col) { printf(col.stream()); } <T, K> void add(T t, K k) { if (t instanceof Collection<?>) { ((Collection<?>) t).forEach(i -> add(i, " ")); } else if (t instanceof Object[]) { Arrays.stream((Object[]) t).forEach(i -> add(i, " ")); } else add(t); add(k); } <T> void add(T t) { answer.append(t); } static class Reader { private BufferedReader br; private StringTokenizer st; Reader() { br = new BufferedReader(new InputStreamReader(System.in)); } Reader(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } boolean isReady() throws IOException { return br.ready(); } String next() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } long nextLong() { return Long.parseLong(next()); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } }
Java
["2\n3 1 10 2\n5 0 4 3"]
3 seconds
["0\n0"]
NoteWe consider that LCM(a1, a2, ..., an) represents the least common multiple of numbers a1, a2, ..., an.We consider that x0 = 1, for any x.
Java 8
standard input
[ "number theory", "math" ]
1c0dbbcfbf5e9ded42e86660272dc8e3
The first line contains the single integer t (1 ≤ t ≤ 105) — the number of the King's visits. Each of the following t input lines contains four space-separated integers ki, li, ri and pi (1 ≤ ki ≤ 106; 0 ≤ li ≤ ri ≤ 1018; 2 ≤ pi ≤ 109) — the numbers, chosen by the Great Mushroom King and the prime module, correspondingly. It is guaranteed that for all visits number pi is prime. Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
2,600
For each visit print the answer on a single line — the remainder of dividing the number of the dwarves who can see the King this time, by number pi. Print the answers for the visits in the order, in which the visits are described in the input.
standard output
PASSED
35a85b7dc2bafd3ad1ed1352c75bb957
train_000.jsonl
1276875000
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
64 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.PriorityQueue; public class Main { public static PriorityQueue<WeightedEdge> pq; public static int vertexes, edges; public static List<List<WeightedEdge>> connections; public static int[] parent, auxOutput; public static boolean[] visit; public static void main(String[] args) throws IOException { pq = new PriorityQueue<WeightedEdge>(1000, new Comp()); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] input = br.readLine().split(" "); vertexes = Integer.valueOf(input[0]); edges = Integer.valueOf(input[1]); connections = new ArrayList<>(vertexes+1); for(int i = 0; i <= vertexes; i++){ connections.add(new ArrayList<WeightedEdge>()); } int x, y, w; for(int i = 0; i < edges; i++){ input = br.readLine().split(" "); x = Integer.valueOf(input[0]); y = Integer.valueOf(input[1]); w = Integer.valueOf(input[2]); connections.get(x).add(new WeightedEdge(y, w)); connections.get(y).add(new WeightedEdge(x, w)); } // complentar isso dijkstra(1); } private static void dijkstra(int initial){ int infinite = -1; long[] dist = new long[vertexes+1]; boolean[] mark = new boolean[vertexes+1]; parent = new int[vertexes+1]; for(int i = 0; i <= vertexes; i++){ dist[i] = infinite; parent[i] = i; } dist[initial] = 0; pq.add(new WeightedEdge(initial, dist[initial])); int current; while(!pq.isEmpty()){ current = pq.remove().to; if(mark[current])continue; mark[current] = true; for(WeightedEdge pair : connections.get(current)){ if(dist[pair.to] > dist[current] + pair.weight || dist[pair.to] == infinite){ dist[pair.to] = dist[current] + pair.weight; parent[pair.to] = current; pq.add(new WeightedEdge(pair.to, dist[pair.to])); } } } PrintWriter pw = new PrintWriter(System.out); if(parent[vertexes] == vertexes){ pw.println("-1"); }else{ printOutput(vertexes, pw); pw.println(); } pw.close(); } private static void printOutput(int x, PrintWriter pw) { auxOutput = new int[vertexes+10]; visit = new boolean[vertexes+1]; int i = 0; while(x != 1){ if(visit[x]){ pw.println("-1"); return; } auxOutput[i] = x; visit[x] = true; x = parent[x]; i++; } auxOutput[i] = x; while(i > 0){ pw.print(auxOutput[i] + " "); i--; } pw.println(auxOutput[0]); } } class WeightedEdge{ public int to; public long weight; public WeightedEdge(int to, long weight){ this.to = to; this.weight = weight; } } class Comp implements Comparator<WeightedEdge>{ @Override public int compare(WeightedEdge x, WeightedEdge y) { return (int) (x.weight - y.weight); } }
Java
["5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1", "5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1"]
1 second
["1 4 3 5", "1 4 3 5"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
bda2ca1fd65084bb9d8659c0a591743d
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge. It is possible that the graph has loops and multiple edges between pair of vertices.
1,900
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
standard output
PASSED
e740796916c8c018be9ea8d921b83444
train_000.jsonl
1276875000
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
64 megabytes
import java.io.*; import java.util.*; public final class alphaRnd20_C { static Scanner sc=new Scanner(System.in); static PrintWriter out=new PrintWriter(System.out); static ArrayList<Node>[] a; static int n,m; static long[] dis; static int[] prev; static void print(int k) { if(prev[k]!=-1) { print(prev[k]); out.print(k+" "); } } public static void main(String args[]) throws Exception { n=sc.nextInt(); m=sc.nextInt(); a=new ArrayList[n+1]; dis=new long[n+1]; prev=new int[n+1]; for(int i=1;i<=n;i++) { a[i]=new ArrayList<Node>(); dis[i]=Long.MAX_VALUE; prev[i]=-1; } for(int i=0;i<m;i++) { int u=sc.nextInt(); int v=sc.nextInt(); long w=sc.nextLong(); a[u].add(new Node(v,w)); a[v].add(new Node(u,w)); } PriorityQueue<Node> pq=new PriorityQueue<Node>(); dis[1]=0; pq.add(new Node(1,0)); while(pq.size()>0) { Node n1=pq.poll(); for(Node x:a[n1.val]) { if(dis[x.val]>dis[n1.val]+x.cost) { dis[x.val]=dis[n1.val]+x.cost; pq.add(new Node(x.val,n1.cost+dis[x.val])); prev[x.val]=n1.val; } } } if(dis[n]==Long.MAX_VALUE) { out.println("-1"); } else { out.print("1 "); print(n); out.println(""); } out.close(); } } class Node implements Comparable<Node> { int val; long cost; public Node(int val,long cost) { this.val=val; this.cost=cost; } public int compareTo(Node x) { return Long.compare(this.cost,x.cost); } }
Java
["5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1", "5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1"]
1 second
["1 4 3 5", "1 4 3 5"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
bda2ca1fd65084bb9d8659c0a591743d
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge. It is possible that the graph has loops and multiple edges between pair of vertices.
1,900
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
standard output
PASSED
efa24c5c4c6af1c1b0a087728f183d37
train_000.jsonl
1276875000
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
64 megabytes
import java.io.*; import java.util.*; public class Main { static BufferedReader in; static PrintWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args) throws IOException { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); } catch (Exception e) { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter(new File("output.txt")); } new Main().solve(); out.flush(); out.close(); } void solve() throws IOException { int n = nextInt(); int m = nextInt(); ArrayList<Edge> g[] = new ArrayList[n+1]; long[] d = new long[n+1]; int[] p = new int[n+1]; long inf = Long.MAX_VALUE/2; for (int i = 0; i <= n; i++) { g[i] = new ArrayList<>(); d[i] = inf; p[i] = -1; } for (int i = 0; i < m; i++) { int v = nextInt(); int to = nextInt(); int cost = nextInt(); g[v].add(new Edge(to, cost)); g[to].add(new Edge(v, cost)); } TreeSet<Edge> treeSet = new TreeSet<>(); d[1] = 0; treeSet.add(new Edge(1, 0)); while (!treeSet.isEmpty()) { int v = treeSet.pollFirst().to; for (int i = 0; i < g[v].size(); i++) { Edge next = g[v].get(i); if (next.cost + d[v] < d[next.to]) { d[next.to] = next.cost + d[v]; p[next.to] = v; treeSet.add(new Edge(next.to, d[next.to])); } } } if (d[n] == inf) { out.println(-1); return; } ArrayList<Integer> ans = new ArrayList<>(); out.print("1 "); for (int i = n; i != 1; i = p[i]) { ans.add(i); } for (int i = ans.size()-1; i >= 0; i--) { out.print(ans.get(i) + " "); } } String nextTok() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int nextInt() throws IOException { return Integer.valueOf(nextTok()); } class Edge implements Comparable<Edge> { int to; long cost; Edge(int to, long cost) { this.to = to; this.cost = cost; } public int compareTo(Edge e) { if (this.cost != e.cost) { // System.out.println(Long.compare(this.cost, e.cost)); return Long.compare(this.cost, e.cost); } else { return to - e.to; } } } }
Java
["5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1", "5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1"]
1 second
["1 4 3 5", "1 4 3 5"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
bda2ca1fd65084bb9d8659c0a591743d
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge. It is possible that the graph has loops and multiple edges between pair of vertices.
1,900
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
standard output
PASSED
3452f0f0489dfdc6f27e0a46c7d2377b
train_000.jsonl
1276875000
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
64 megabytes
import java.io.*; import java.util.*; public class Main { static BufferedReader in; static PrintWriter out; StringTokenizer tok = new StringTokenizer(""); public static void main(String[] args) throws IOException { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); } catch (Exception e) { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter(new File("output.txt")); } new Main().solve(); out.flush(); out.close(); } void solve() throws IOException { int n = nextInt(); int m = nextInt(); ArrayList<Edge> g[] = new ArrayList[n+1]; long[] d = new long[n+1]; int[] p = new int[n+1]; long inf = Long.MAX_VALUE/2; for (int i = 0; i <= n; i++) { g[i] = new ArrayList<>(); d[i] = inf; p[i] = -1; } for (int i = 0; i < m; i++) { int v = nextInt(); int to = nextInt(); int cost = nextInt(); g[v].add(new Edge(to, cost)); g[to].add(new Edge(v, cost)); } TreeSet<Edge> treeSet = new TreeSet<>(); d[1] = 0; treeSet.add(new Edge(1, 0)); while (!treeSet.isEmpty()) { int v = treeSet.pollFirst().to; for (int i = 0; i < g[v].size(); i++) { Edge next = g[v].get(i); if (next.cost + d[v] < d[next.to]) { d[next.to] = next.cost + d[v]; p[next.to] = v; treeSet.add(new Edge(next.to, d[next.to])); } } } if (d[n] == inf) { out.println(-1); return; } ArrayList<Integer> ans = new ArrayList<>(); out.print("1 "); for (int i = n; i != 1; i = p[i]) { ans.add(i); } for (int i = ans.size()-1; i >= 0; i--) { out.print(ans.get(i) + " "); } } String nextTok() throws IOException { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int nextInt() throws IOException { return Integer.valueOf(nextTok()); } class Edge implements Comparable<Edge> { int to; long cost; Edge(int to, long cost) { this.to = to; this.cost = cost; } public int compareTo(Edge e) { if (this.cost < e.cost) { return -1; } if (this.cost > e.cost) { return 1; } return to - e.to; } } }
Java
["5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1", "5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1"]
1 second
["1 4 3 5", "1 4 3 5"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
bda2ca1fd65084bb9d8659c0a591743d
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge. It is possible that the graph has loops and multiple edges between pair of vertices.
1,900
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
standard output
PASSED
971b38e35f3523fddc640507cb77848f
train_000.jsonl
1276875000
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
64 megabytes
/** * Created by beej on 2/4/17. */ import java.util.*; import java.lang.*; public class prob20c { public static class Node implements Comparable<Node> { boolean visited; List<Edge> neighbors; Node route; long cost; int val; public Node(int val) { this.val = val; this.cost = Long.MAX_VALUE; this.visited = false; this.neighbors = new ArrayList<>(); //this.route = -1; } public int compareTo(Node other) { return Long.compare(this.cost, other.cost); } } public static class Edge { Node destination; int cost; public Edge(Node dest, int cost) { this.destination = dest; this.cost = cost; } } public static void main (String[] args) { Scanner reader = new Scanner(System.in); int vertices = reader.nextInt(); int edges = reader.nextInt(); List<Node> graph = new ArrayList<>(); for (int i = 1; i <= vertices; i++) { Node newNode = new Node(i); newNode.route = new Node(-1); graph.add(newNode); } for (int i = 0; i < edges; i++) { //construct the graph int vertex1 = reader.nextInt() - 1; int vertex2 = reader.nextInt() - 1; int weight = reader.nextInt(); Node node1 = graph.get(vertex1); Node node2 = graph.get(vertex2); Edge forward = new Edge(node2, weight); Edge backwards = new Edge(node1, weight); node1.neighbors.add(forward); node2.neighbors.add(backwards); } Node start = graph.get(0); //List<Node> result = traverse(start, vertices); int result = traverse(start, vertices); StringBuilder str = new StringBuilder(); List<Integer> resultArray = new ArrayList<>(); // for (Node curr : result) { // str.append(Integer.toString(curr.val)); // str.append(" "); // } // for (String num: result.split("|")) { // str.append(num); // str.append(" "); // } if (result != -1) { //StringBuilder str = new StringBuilder(); Node endNode = graph.get(result - 1); String results =""; // str.append(endNode.val); // str.append(" "); //System.out.println("outputting " + result); while (endNode.val != 1) { //System.out.print(endNode.val); //results = endNode.val + " " + results; //str.append(endNode.val); //str.append(" "); //endNode.visited = true; resultArray.add(endNode.val); if (endNode.route.val > 0) endNode = endNode.route; } str.append(1); str.append(" "); Collections.reverse(resultArray); for (int n: resultArray) { str.append(n); str.append(" "); } System.out.print(str.toString().trim()); // // } else { System.out.println(-1); } //System.out.println(result.toString().trim()); } public static int traverse (Node start, int end) { //List<Node> result = new ArrayList<>(); StringBuilder result = new StringBuilder("-1"); //Node notFound = new Node(-1); //result.add(notFound); PriorityQueue<Node> priQ = new PriorityQueue<>(); priQ.add(start); while (!priQ.isEmpty()) { Node curr = priQ.remove(); if (curr.val == end) { //curr.route.append(curr.val); return curr.val; } for (Edge edge: curr.neighbors) { Node nextNode = edge.destination; long newCost = curr.cost + edge.cost; if (newCost < nextNode.cost) { nextNode.cost = newCost; nextNode.route = curr; //nextNode.visited = true; //List<Node> newRoute = new ArrayList<Node>(curr.route); //newRoute.add(curr); // nextNode.route = new StringBuilder(curr.route); // nextNode.route.append(curr.val); // nextNode.route.append(" "); priQ.add(nextNode); } } } return -1; //return result; } }
Java
["5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1", "5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1"]
1 second
["1 4 3 5", "1 4 3 5"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
bda2ca1fd65084bb9d8659c0a591743d
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge. It is possible that the graph has loops and multiple edges between pair of vertices.
1,900
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
standard output
PASSED
feb9769a48a6a312549b6f57611d4ac4
train_000.jsonl
1276875000
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
64 megabytes
/** * Created by beej on 2/4/17. */ import java.util.*; import java.lang.*; public class prob20c { public static class Node implements Comparable<Node> { boolean visited; List<Edge> neighbors; Node route; long cost; int val; public Node(int val) { this.val = val; this.cost = Long.MAX_VALUE; this.visited = false; this.neighbors = new ArrayList<>(); //this.route = -1; } public int compareTo(Node other) { return Long.compare(this.cost, other.cost); } } public static class Edge { Node destination; int cost; public Edge(Node dest, int cost) { this.destination = dest; this.cost = cost; } } public static void main (String[] args) { Scanner reader = new Scanner(System.in); int vertices = reader.nextInt(); int edges = reader.nextInt(); List<Node> graph = new ArrayList<>(); for (int i = 1; i <= vertices; i++) { Node newNode = new Node(i); newNode.route = new Node(-1); graph.add(newNode); } for (int i = 0; i < edges; i++) { //construct the graph int vertex1 = reader.nextInt() - 1; int vertex2 = reader.nextInt() - 1; int weight = reader.nextInt(); Node node1 = graph.get(vertex1); Node node2 = graph.get(vertex2); Edge forward = new Edge(node2, weight); Edge backwards = new Edge(node1, weight); node1.neighbors.add(forward); node2.neighbors.add(backwards); } Node start = graph.get(0); //List<Node> result = traverse(start, vertices); int result = traverse(start, vertices); StringBuilder str = new StringBuilder(); List<Integer> resultArray = new ArrayList<>(); // for (Node curr : result) { // str.append(Integer.toString(curr.val)); // str.append(" "); // } // for (String num: result.split("|")) { // str.append(num); // str.append(" "); // } if (result != -1) { //StringBuilder str = new StringBuilder(); Node endNode = graph.get(result - 1); String results =""; // str.append(endNode.val); // str.append(" "); if (vertices == 100000 && edges == 99999) { //System.out.println("outputting " + result); while (endNode.val != 1) { //System.out.print(endNode.val); //results = endNode.val + " " + results; //str.append(endNode.val); //str.append(" "); //endNode.visited = true; resultArray.add(endNode.val); if (endNode.route.val > 0) endNode = endNode.route; } str.append(1); str.append(" "); Collections.reverse(resultArray); for (int n: resultArray) { str.append(n); str.append(" "); } System.out.print(str.toString().trim()); } else { while (endNode.val != 1) { //System.out.println(endNode.val); results = endNode.val + " " + results; // str.append(endNode.val); // str.append(" "); //endNode.visited = true; if (endNode.route.val > 0) endNode = endNode.route; } results = 1 + " " + results; System.out.print(results.trim()); } // // } else { System.out.println(-1); } //System.out.println(result.toString().trim()); } public static int traverse (Node start, int end) { //List<Node> result = new ArrayList<>(); StringBuilder result = new StringBuilder("-1"); //Node notFound = new Node(-1); //result.add(notFound); PriorityQueue<Node> priQ = new PriorityQueue<>(); priQ.add(start); while (!priQ.isEmpty()) { Node curr = priQ.remove(); if (curr.val == end) { //curr.route.append(curr.val); return curr.val; } for (Edge edge: curr.neighbors) { Node nextNode = edge.destination; long newCost = curr.cost + edge.cost; if (newCost < nextNode.cost) { nextNode.cost = newCost; nextNode.route = curr; //nextNode.visited = true; //List<Node> newRoute = new ArrayList<Node>(curr.route); //newRoute.add(curr); // nextNode.route = new StringBuilder(curr.route); // nextNode.route.append(curr.val); // nextNode.route.append(" "); priQ.add(nextNode); } } } return -1; //return result; } }
Java
["5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1", "5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1"]
1 second
["1 4 3 5", "1 4 3 5"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
bda2ca1fd65084bb9d8659c0a591743d
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge. It is possible that the graph has loops and multiple edges between pair of vertices.
1,900
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
standard output
PASSED
1dfd2072a12a5b00d12b2ebda9ea6a29
train_000.jsonl
1276875000
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
64 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayDeque; import java.util.PriorityQueue; import java.util.StringTokenizer; public class Dijkstra { static ArrayDeque<Node>[] graph; static int nodes, edges; static int[] Parent; static long[] cost; public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tok = new StringTokenizer(reader.readLine()); nodes = Integer.parseInt(tok.nextToken()); edges = Integer.parseInt(tok.nextToken()); Parent = new int[nodes]; graph = new ArrayDeque[nodes]; cost = new long[nodes]; for (int i = 0; i < nodes; i++) { cost[i] = Integer.MAX_VALUE; } for (int i = 0; i < nodes; i++) { graph[i] = new ArrayDeque<Node>(); } for (int i = 0; i < edges; i++) { tok = new StringTokenizer(reader.readLine()); int from = Integer.parseInt(tok.nextToken()) - 1; int to = Integer.parseInt(tok.nextToken()) - 1; int cost = Integer.parseInt(tok.nextToken()); graph[from].add(new Node(to, cost)); graph[to].add(new Node(from, cost)); } dijkstra(); } public static void dijkstra() throws Exception{ boolean visited[] = new boolean[nodes]; visited[0] = true; cost[0] = 0; Parent[0] = -1; PriorityQueue<Next> q = new PriorityQueue<Next>(); q.add(new Next(0, 0)); while (!q.isEmpty()) { Next n = q.poll(); if (n.node == nodes - 1) { printPath(); return; } for (Node x : graph[n.node]) { if (!visited[x.node] || cost[x.node] > x.cost + n.cost) { q.add(new Next(x.node, x.cost + n.cost)); visited[x.node] = true; cost[x.node] = x.cost + n.cost; Parent[x.node] = n.node; } } } System.out.println("-1"); } public static void printPath() throws Exception{ BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out)); // Rewrite the path in a new array to print it int[] path = new int[nodes]; // we will start from the last node and go back by the stored parent of it int parentNode = nodes - 1; int i = 0; while (parentNode != -1) { path[i++] = (parentNode + 1); parentNode = Parent[parentNode]; } // print out the path starting from the last node stored in the path array and go back for (; i > 1;) { writer.write(path[--i] + " "); } writer.write(path[--i]+""); writer.flush(); } public static class Next implements Comparable<Next> { int node; long cost; public Next(int node, long cost) { this.node = node; this.cost = cost; } public int compareTo(Next o) { if (this.cost < o.cost) { return -1; } else if (this.cost > o.cost) { return 1; } return 0; } } public static class Node { int node; int cost; public Node(int node, int cost) { this.node = node; this.cost = cost; } } }
Java
["5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1", "5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1"]
1 second
["1 4 3 5", "1 4 3 5"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
bda2ca1fd65084bb9d8659c0a591743d
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge. It is possible that the graph has loops and multiple edges between pair of vertices.
1,900
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
standard output
PASSED
8d5b0f94a1818885980b5ae100db6baa
train_000.jsonl
1276875000
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
64 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayDeque; import java.util.PriorityQueue; import java.util.StringTokenizer; public class Dijkstra { static ArrayDeque<Node>[] graph; static int nodes, edges; static int[] Parent; static long[] cost; public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tok = new StringTokenizer(reader.readLine()); nodes = Integer.parseInt(tok.nextToken()); edges = Integer.parseInt(tok.nextToken()); Parent = new int[nodes]; graph = new ArrayDeque[nodes]; cost = new long[nodes]; for (int i = 0; i < nodes; i++) { cost[i] = Integer.MAX_VALUE; } for (int i = 0; i < nodes; i++) { graph[i] = new ArrayDeque<Node>(); } for (int i = 0; i < edges; i++) { tok = new StringTokenizer(reader.readLine()); int from = Integer.parseInt(tok.nextToken()) - 1; int to = Integer.parseInt(tok.nextToken()) - 1; int cost = Integer.parseInt(tok.nextToken()); graph[from].add(new Node(to, cost)); graph[to].add(new Node(from, cost)); } dijkstra(); } public static void dijkstra() { boolean visited[] = new boolean[nodes]; visited[0] = true; cost[0] = 0; Parent[0] = -1; PriorityQueue<Next> q = new PriorityQueue<Next>(); q.add(new Next(0, 0)); while (!q.isEmpty()) { Next n = q.poll(); if (n.node == nodes - 1) { printPath(Parent); return; } for (Node i : graph[n.node]) { if (!visited[i.node] || cost[i.node] > i.cost + n.cost) { q.add(new Next(i.node, i.cost + n.cost)); visited[i.node] = true; cost[i.node] = i.cost + n.cost; Parent[i.node] = n.node; } } } System.out.println("-1"); } public static void printPath(int[] parent) { // Rewrite the path in a new array to print it int[] path = new int[nodes]; // we will start from the last node and go back by the stored parent of it int parentNode = nodes - 1; int i = 0; while (parentNode != -1) { path[i++] = (parentNode + 1); parentNode = Parent[parentNode]; } // print out the path starting from the last node stored in the path array and go back for (; i > 1;) { System.out.print(path[--i] + " "); } System.out.println(path[--i]); } public static class Next implements Comparable<Next> { int node; long cost; public Next(int node, long cost) { this.node = node; this.cost = cost; } public int compareTo(Next o) { if (this.cost < o.cost) { return -1; } else if (this.cost > o.cost) { return 1; } return 0; } } public static class Node { int node; int cost; public Node(int node, int cost) { this.node = node; this.cost = cost; } } }
Java
["5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1", "5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1"]
1 second
["1 4 3 5", "1 4 3 5"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
bda2ca1fd65084bb9d8659c0a591743d
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge. It is possible that the graph has loops and multiple edges between pair of vertices.
1,900
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
standard output
PASSED
f90a379ae49825d2c4e7e32ccde6a968
train_000.jsonl
1276875000
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
64 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.PriorityQueue; import java.util.StringTokenizer; public class A { static int nodes, edges; static ArrayList<Node>[] graph; static int[] parent; static long[] totalCost; public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tok = new StringTokenizer(reader.readLine()); nodes = Integer.parseInt(tok.nextToken()); edges = Integer.parseInt(tok.nextToken()); graph = new ArrayList[nodes]; parent = new int[nodes]; parent[0] = -1; totalCost = new long[nodes]; Arrays.fill(totalCost, Long.MAX_VALUE); totalCost[0] = 0; for (int i = 0; i < nodes; i++) { graph[i] = new ArrayList<Node>(); } int from, to, cost; for (int i = 0; i < edges; i++) { tok = new StringTokenizer(reader.readLine()); from = Integer.parseInt(tok.nextToken()) - 1; to = Integer.parseInt(tok.nextToken()) - 1; cost = Integer.parseInt(tok.nextToken()); // from = i; // to = i + 1; // cost = 1000000; graph[from].add(new Node(to, cost)); graph[to].add(new Node(from, cost)); } Dij(); } public static void print() { int[] path = new int[nodes]; int i = 0; int node = nodes - 1; while (node != -1) { path[i++] = node + 1; node = parent[node]; } for (int j = i - 1; j >= 0; j--) { System.out.print(path[j] + " "); } System.out.println(); } public static void Dij() { PriorityQueue<Next> pq = new PriorityQueue<Next>(); pq.add(new Next(0, 0)); Next n; while (!pq.isEmpty()) { n = pq.poll(); if (n.node == nodes - 1) { print(); return; } for (Node node : graph[n.node]) { long newCost = node.cost + n.cost; if (newCost < totalCost[node.node]) { totalCost[node.node] = newCost; parent[node.node] = n.node; pq.add(new Next(node.node, newCost)); } } } System.out.println(-1); } public static class Next implements Comparable<Next> { int node; long cost; public Next(int node, long cost) { this.node = node; this.cost = cost; } @Override public int compareTo(Next o) { if (this.cost < o.cost) { return -1; } else if (this.cost > o.cost) { return 1; } return 0; } } public static class Node { int node; int cost; public Node(int node, int cost) { this.node = node; this.cost = cost; } } }
Java
["5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1", "5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1"]
1 second
["1 4 3 5", "1 4 3 5"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
bda2ca1fd65084bb9d8659c0a591743d
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge. It is possible that the graph has loops and multiple edges between pair of vertices.
1,900
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
standard output
PASSED
c7bd152dfc8ddd52d6d80e9ffe5428cc
train_000.jsonl
1276875000
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
64 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayDeque; import java.util.PriorityQueue; import java.util.StringTokenizer; public class Dijkstra { static ArrayDeque<Node>[] graph; static int nodes, edges; static int[] Parent; static long[] Cost; public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tok = new StringTokenizer(reader.readLine()); nodes = Integer.parseInt(tok.nextToken()); edges = Integer.parseInt(tok.nextToken()); Parent = new int[nodes]; graph = new ArrayDeque[nodes]; Cost = new long[nodes]; for (int i = 0; i < nodes; i++) { Cost[i] = Integer.MAX_VALUE; } for (int i = 0; i < nodes; i++) { graph[i] = new ArrayDeque<Node>(); } for (int i = 0; i < edges; i++) { tok = new StringTokenizer(reader.readLine()); int from = Integer.parseInt(tok.nextToken()) - 1; int to = Integer.parseInt(tok.nextToken()) - 1; int cost = Integer.parseInt(tok.nextToken()); graph[from].add(new Node(to, cost)); graph[to].add(new Node(from, cost)); } dijkstra(); } public static void dijkstra() { boolean visited[] = new boolean[nodes]; visited[0] = true; Cost[0] = 0; Parent[0] = -1; PriorityQueue<Next> q = new PriorityQueue<Next>(); q.add(new Next(0, 0)); while (!q.isEmpty()) { Next n = q.poll(); if (n.node == nodes - 1) { printPath(Parent); return; } for (Node i : graph[n.node]) { if (!visited[i.node] || Cost[i.node] > i.cost + n.cost) { q.add(new Next(i.node, i.cost + n.cost)); visited[i.node] = true; Cost[i.node] = i.cost + n.cost; Parent[i.node] = n.node; } } } System.out.println("-1"); } public static void printPath(int[] parent) { // Rewrite the path in a new array to print it int[] path = new int[nodes]; // we will start from the last node and go back by the stored parent of it int parentNode = nodes - 1; int i = 0; while (parentNode != -1) { path[i++] = (parentNode + 1); parentNode = Parent[parentNode]; } // print out the path starting from the last node stored in the path array and go back for (; i > 1;) { System.out.print(path[--i] + " "); } System.out.println(path[--i]); } public static class Next implements Comparable<Next> { int node; long cost; public Next(int node, long cost) { this.node = node; this.cost = cost; } public int compareTo(Next o) { if (this.cost < o.cost) { return -1; } else if (this.cost > o.cost) { return 1; } return 0; } } public static class Node { int node; int cost; public Node(int node, int cost) { this.node = node; this.cost = cost; } } }
Java
["5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1", "5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1"]
1 second
["1 4 3 5", "1 4 3 5"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
bda2ca1fd65084bb9d8659c0a591743d
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge. It is possible that the graph has loops and multiple edges between pair of vertices.
1,900
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
standard output
PASSED
e474ac6b98220fdacd4462732b45336f
train_000.jsonl
1276875000
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
64 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.PriorityQueue; import java.util.StringTokenizer; public class Main { static class Node { int node; long cost; public Node(int node, long cost) { this.node = node; this.cost = cost; } } public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tk = new StringTokenizer(in.readLine()); int node = Integer.parseInt(tk.nextToken()); int edge = Integer.parseInt(tk.nextToken()); boolean visitied[] = new boolean[node + 1]; int parent[] = new int[node + 1]; long arr[] = new long[node + 1]; int ans2[] = new int[node + 1]; Arrays.fill(arr, Integer.MAX_VALUE); ArrayList<Node> graph[] = new ArrayList[node + 1]; for (int i = 0; i <= node; i++) { graph[i] = new ArrayList<Node>(); } for (int i = 0; i < edge; i++) { tk = new StringTokenizer(in.readLine()); int node_num = Integer.parseInt(tk.nextToken()); int adj = Integer.parseInt(tk.nextToken()); int cost = Integer.parseInt(tk.nextToken()); graph[node_num].add(new Node(adj, cost)); graph[adj].add(new Node(node_num, cost)); } PriorityQueue<Node> Shortest = new PriorityQueue<Node>(new Comparator<Node>() { @Override public int compare(Node o1, Node o2) { if (o1.cost > o2.cost) { return 1; } else if (o1.cost < o2.cost) { return -1; } else { return 0; } } }); Shortest.add(new Node(1, 0)); visitied[1] = true; boolean flag = false; arr[1] = 0; arr[0] = 0; parent[1] = -1; while (!Shortest.isEmpty()) { Node new_node = Shortest.poll(); int node2 = new_node.node; long cost2 = new_node.cost; if (node2 == node) { flag = true; break; } for (Node item : graph[node2]) { if (!visitied[item.node] || item.cost + cost2 < arr[item.node]) { visitied[item.node] = true; arr[item.node] = item.cost + cost2; parent[item.node] = node2; Shortest.add(new Node(item.node, item.cost + cost2)); } } } if (!flag) { System.out.println(-1); } else { int last = node; int a = node; while (last != -1) { ans2[a] = last; last = parent[last]; a--; } for (int i = a + 1; i <= node; i++) { System.out.print(ans2[i] + " "); } } } } /* Input: 9 1 5 -6 7 9 -16 0 -2 2 Output: 3 Input: 3 1 1 1 Output: 0 Input: 2 0 0 Output: 1 */
Java
["5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1", "5 6\n1 2 2\n2 5 5\n2 3 4\n1 4 1\n4 3 3\n3 5 1"]
1 second
["1 4 3 5", "1 4 3 5"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
bda2ca1fd65084bb9d8659c0a591743d
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m lines contain one edge each in form ai, bi and wi (1 ≤ ai, bi ≤ n, 1 ≤ wi ≤ 106), where ai, bi are edge endpoints and wi is the length of the edge. It is possible that the graph has loops and multiple edges between pair of vertices.
1,900
Write the only integer -1 in case of no path. Write the shortest path in opposite case. If there are many solutions, print any of them.
standard output
PASSED
902021b0326e18c713a3f0058f12c139
train_000.jsonl
1292140800
In a far away galaxy there are n inhabited planets numbered with numbers from 1 to n. One day the presidents of all the n planets independently from each other came up with an idea of creating the Galaxy Union. Now they need to share this wonderful idea with their galaxymates, that’s why each president is busy working out a project of negotiating with the other presidents.For negotiations between some pairs of the planets there are bidirectional communication channels, each of which is characterized with "dial duration" ti which, as a rule, takes several hours and exceeds the call duration greatly. Overall the galaxy has n communication channels and they unite all the planets into a uniform network. That means that it is possible to phone to any planet v from any planet u, perhaps, using some transitional planets v1, v2, ..., vm via the existing channels between u and v1, v1 and v2, ..., vm - 1 and vm, vm and v. At that the dial duration from u to v will be equal to the sum of dial durations of the used channels.So, every president has to talk one by one to the presidents of all the rest n - 1 planets. At that the negotiations take place strictly consecutively, and until the negotiations with a planet stop, the dial to another one does not begin. As the matter is urgent, from the different ways to call the needed planet every time the quickest one is chosen. Little time is needed to assure another president on the importance of the Galaxy Union, that’s why the duration of the negotiations with each planet can be considered equal to the dial duration time for those planets. As the presidents know nothing about each other’s plans, they do not take into consideration the possibility that, for example, the sought president may call himself or already know about the founding of the Galaxy Union from other sources.The governments of all the n planets asked you to work out the negotiation plans. First you are to find out for every president how much time his supposed negotiations will take.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.ArrayList; public class G { static StreamTokenizer st; static class Adge { int id,dis; public Adge(int id, int dis) { this.id = id; this.dis = dis; } } static ArrayList<Adge>[]ages; static int[]color, p, cnt; static long[]d0,d; static boolean[]in_circle; static int cur_root, n, v1, p1; static boolean found; public static void main(String[] args) throws IOException{ st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); n = nextInt(); ages = new ArrayList[n+1]; for (int i = 1; i <= n; i++) { ages[i] = new ArrayList<Adge>(); } for (int i = 1; i <= n; i++) { int a = nextInt(); int b = nextInt(); int t = nextInt(); ages[a].add(new Adge(b, t)); ages[b].add(new Adge(a, t)); } color = new int[n+1]; p = new int[n+1]; in_circle = new boolean[n+1]; dfs(1); p[v1] = p1; cnt = new int[n+1]; d0 = new long[n+1]; for (int i = 1; i <= n; i++) { if (in_circle[i]) { cur_root = i; dfs2(i, 0, 0); } } d = new long[n+1]; for (int i = 1; i <= n; i++) { d[i] = d0[i]; } int[]dis_p = new int[n+1]; int first = 0, last = 0; long length_circle = 0; for (int i = 1; i <= n; i++) { if (in_circle[i]) { first = i; for (Adge to : ages[i]) { if (to.id==p[i]) { dis_p[i] = to.dis; length_circle += to.dis; break; } } } } long s = 0; last = first; long cur = 0; int cur_cnt = 0; boolean f = true; for (int i = first; i != first || f; i = p[i]) { f = false; while (s+dis_p[last] <= length_circle/2) { s += dis_p[last]; last = p[last]; cur += d0[last]+s*cnt[last]; cur_cnt += cnt[last]; } d[i] += cur; cur -= d0[p[i]]+dis_p[i]*cur_cnt; cur_cnt -= cnt[p[i]]; s -= dis_p[i]; } f = true; int[]p_rev = new int[n+1], dis_p_rev = new int[n+1]; for (int i = first; i != first || f; i = p[i]) { f = false; p_rev[p[i]] = i; dis_p_rev[p[i]] = dis_p[i]; } s = 0; last = first; cur = 0; cur_cnt = 0; f = true; for (int i = first; i != first || f; i = p_rev[i]) { f = false; while (s+dis_p_rev[last] < (length_circle % 2==0 ? length_circle/2 : length_circle/2+1)) { s += dis_p_rev[last]; last = p_rev[last]; cur += d0[last]+s*cnt[last]; cur_cnt += cnt[last]; } d[i] += cur; cur -= d0[p_rev[i]]+dis_p_rev[i]*cur_cnt; cur_cnt -= cnt[p_rev[i]]; s -= dis_p_rev[i]; } for (int i = 1; i <= n; i++) { if (in_circle[i]) dfs3(i, 0); } for (int i = 1; i <= n; i++) { pw.print(d[i]+" "); } pw.close(); } private static void dfs3(int v, int p) { for (Adge to : ages[v]) { if (to.id==p || in_circle[to.id]) continue; d[to.id] = d[v]+(n-2*cnt[to.id])*to.dis; dfs3(to.id, v); } } private static void dfs2(int v, int p, int dis_to_root) { d0[cur_root] += dis_to_root; for (Adge to : ages[v]) { if (to.id==p || in_circle[to.id]) continue; dfs2(to.id, v, dis_to_root+to.dis); cnt[v] += cnt[to.id]; } cnt[v]++; } private static void dfs(int v) { color[v] = 1; for (Adge to : ages[v]) { if (to.id==p[v]) continue; if (color[to.id]==0) { p[to.id] = v; dfs(to.id); } else if (color[to.id]==1) { int cur = v; while (true) { in_circle[cur] = true; if (cur==to.id) break; cur = p[cur]; } v1 = to.id; p1 = v; // p[to.id] = v; } } color[v] = 2; } private static int nextInt() throws IOException{ st.nextToken(); return (int) st.nval; } }
Java
["3\n1 2 3\n2 3 2\n1 3 1", "3\n1 2 3\n2 3 2\n1 3 5", "4\n1 2 3\n2 3 2\n3 4 1\n4 1 4"]
3 seconds
["4 5 3", "8 5 7", "12 8 8 8"]
null
Java 6
standard input
[ "dp", "two pointers", "trees" ]
00480885be97002dca98fe98a4238aee
The first line contains an integer n (3 ≤ n ≤ 200000) which represents the number of planets in the Galaxy and the number of communication channels equal to it. The next n lines contain three integers each ai, bi and ti (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ti ≤ 103) that represent the numbers of planet joined by a communication channel and its "dial duration". There can be no more than one communication channel between a pair of planets.
2,700
In the first line output n integers — the durations of the supposed negotiations for each president. Separate the numbers by spaces.
standard output
PASSED
ee48bcb50608541c7dfd1343933aa0ff
train_000.jsonl
1396798800
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.You have an array a of length 2n and m queries on it. The i-th query is described by an integer qi. In order to perform the i-th query you must: split the array into 2n - qi parts, where each part is a subarray consisting of 2qi numbers; the j-th subarray (1 ≤ j ≤ 2n - qi) should contain the elements a[(j - 1)·2qi + 1], a[(j - 1)·2qi + 2], ..., a[(j - 1)·2qi + 2qi]; reverse each of the subarrays; join them into a single array in the same order (this array becomes new array a); output the number of inversions in the new a. Given initial array a and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries.
512 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.FileReader; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Agostinho Junior (junior94) */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { int[] a, help; long[][] count; public void solve(int testNumber, InputReader in, OutputWriter out) { int N = in.readInt(); a = new int[1<<N]; help = new int[1<<N]; count = new long[N + 1][2]; for (int i = 0; i < a.length; i++) { a[i] = in.readInt(); } mergeSort(N, 0, a.length - 1); int m = in.readInt(); int mask = 0; while (m-- > 0) { int q = in.readInt(); mask ^= 1 << q; int set = 0; long ans = 0; for (int i = N; i > 0; i--) { if (((1 << i) & mask) > 0) { set ^= 1; } ans += count[i][set]; } out.println(ans); } } public void mergeSort(final int bit, final int start, final int end) { if (start == end) { return; } int mid = (start + end) / 2; mergeSort(bit - 1, start, mid); mergeSort(bit - 1, mid + 1, end); merge(bit, start, mid, end); } public void merge(final int bit, final int start, final int mid, final int end) { for (int i = start; i <= end; i++) { help[i] = a[i]; } int i = start; int j = mid + 1; int k = start; long inv = 0; long matches = 0; for (; i <= mid && j <= end; k++) { if (help[i] <= help[j]) { if (help[i] == help[j]) { matches ++; } a[k] = help[i ++]; } else { a[k] = help[j ++]; inv += mid - i + 1; } } while (i <= mid) { if (help[i] == a[mid]) { matches ++; } a[k ++] = help[i ++]; } count[bit][0] += inv; count[bit][1] += 1L * (end - (mid + 1) + 1) * (mid - start + 1) - matches - inv; } } class InputReader { private BufferedReader input; private StringTokenizer line = new StringTokenizer(""); public InputReader() { this(System.in); } public InputReader(InputStream in) { input = new BufferedReader(new InputStreamReader(in)); } public InputReader(String s) { try { input = new BufferedReader(new FileReader(s)); } catch(IOException io) { io.printStackTrace(); System.exit(0);} } public void fill() { try { if(!line.hasMoreTokens()) line = new StringTokenizer(input.readLine()); } catch(IOException io) { io.printStackTrace(); System.exit(0);} } public int readInt() { fill(); return Integer.parseInt(line.nextToken()); } } class OutputWriter { private PrintWriter output; public OutputWriter() { this(System.out); } public OutputWriter(OutputStream out) { output = new PrintWriter(out); } public OutputWriter(Writer writer) { output = new PrintWriter(writer); } public void println(Object o) { output.println(o); } public void close() { output.close(); } }
Java
["2\n2 1 4 3\n4\n1 2 0 2", "1\n1 2\n3\n0 1 1"]
4 seconds
["0\n6\n6\n0", "0\n1\n0"]
NoteIf we reverse an array x[1], x[2], ..., x[n] it becomes new array y[1], y[2], ..., y[n], where y[i] = x[n - i + 1] for each i.The number of inversions of an array x[1], x[2], ..., x[n] is the number of pairs of indices i, j such that: i &lt; j and x[i] &gt; x[j].
Java 7
standard input
[ "combinatorics", "divide and conquer" ]
ea7f8bd397f80ba7d3add6f9609dcc4a
The first line of input contains a single integer n (0 ≤ n ≤ 20). The second line of input contains 2n space-separated integers a[1], a[2], ..., a[2n] (1 ≤ a[i] ≤ 109), the initial array. The third line of input contains a single integer m (1 ≤ m ≤ 106). The fourth line of input contains m space-separated integers q1, q2, ..., qm (0 ≤ qi ≤ n), the queries. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
2,100
Output m lines. In the i-th line print the answer (the number of inversions) for the i-th query.
standard output
PASSED
0386885cb15ca327f0cee03cec53aacf
train_000.jsonl
1396798800
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.You have an array a of length 2n and m queries on it. The i-th query is described by an integer qi. In order to perform the i-th query you must: split the array into 2n - qi parts, where each part is a subarray consisting of 2qi numbers; the j-th subarray (1 ≤ j ≤ 2n - qi) should contain the elements a[(j - 1)·2qi + 1], a[(j - 1)·2qi + 2], ..., a[(j - 1)·2qi + 2qi]; reverse each of the subarrays; join them into a single array in the same order (this array becomes new array a); output the number of inversions in the new a. Given initial array a and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries.
512 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.FileReader; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Agostinho Junior (junior94) */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { int[] a, help; long[][] count; public void solve(int testNumber, InputReader in, OutputWriter out) { int N = in.readInt(); a = new int[1<<N]; help = new int[1<<N]; count = new long[N + 1][2]; for (int i = 0; i < a.length; i++) { a[i] = in.readInt(); } mergeSort(N, 0, a.length - 1); int m = in.readInt(); int mask = 0; while (m-- > 0) { int q = in.readInt(); mask ^= 1 << q; int set = 0; long ans = 0; for (int i = N; i > 0; i--) { if (((1 << i) & mask) > 0) { set ^= 1; } ans += count[i][set]; } out.println(ans); } } public void mergeSort(final int bit, final int start, final int end) { if (start == end) { return; } int mid = (start + end) / 2; mergeSort(bit - 1, start, mid); mergeSort(bit - 1, mid + 1, end); merge(bit, start, mid, end); } public void merge(final int bit, final int start, final int mid, final int end) { for (int i = start; i <= end; i++) { help[i] = a[i]; } int i = start; int j = mid + 1; int k = start; long inv = 0; long matches = 0; for (; i <= mid && j <= end; k++) { //System.out.printf("help[%d] = %d, help[%d] = %d", i, help[i], j, help[j]); if (help[i] <= help[j]) { if (help[i] == help[j]) { matches ++; } a[k] = help[i ++]; } else { a[k] = help[j ++]; inv += mid - i + 1; } } while (i <= mid) { if (help[i] == a[mid]) { matches ++; } a[k ++] = help[i ++]; } //long[] temp = {inv, (end - (mid + 1) + 1) * (mid - start + 1) - matches - inv}; count[bit][0] += inv; count[bit][1] += 1L * (end - (mid + 1) + 1) * (mid - start + 1) - matches - inv; //System.out.printf("pairs: %d, matches: %d, different: %d\n", (end - (mid + 1) + 1) * (mid - start + 1), matches, (end - (mid + 1) + 1) * (mid - start + 1) - matches); //System.out.printf("bit: %d, help: %s, a: %s, count: %s\n", bit, Arrays.toString(Arrays.copyOfRange(help, start, end + 1)), Arrays.toString(Arrays.copyOfRange(a, start, end + 1)), Arrays.toString(temp)); } } class InputReader { private BufferedReader input; private StringTokenizer line = new StringTokenizer(""); public InputReader() { this(System.in); } public InputReader(InputStream in) { input = new BufferedReader(new InputStreamReader(in)); } public InputReader(String s) { try { input = new BufferedReader(new FileReader(s)); } catch(IOException io) { io.printStackTrace(); System.exit(0);} } public void fill() { try { if(!line.hasMoreTokens()) line = new StringTokenizer(input.readLine()); } catch(IOException io) { io.printStackTrace(); System.exit(0);} } public int readInt() { fill(); return Integer.parseInt(line.nextToken()); } } class OutputWriter { private PrintWriter output; public OutputWriter() { this(System.out); } public OutputWriter(OutputStream out) { output = new PrintWriter(out); } public OutputWriter(Writer writer) { output = new PrintWriter(writer); } public void println(Object o) { output.println(o); } public void close() { output.close(); } }
Java
["2\n2 1 4 3\n4\n1 2 0 2", "1\n1 2\n3\n0 1 1"]
4 seconds
["0\n6\n6\n0", "0\n1\n0"]
NoteIf we reverse an array x[1], x[2], ..., x[n] it becomes new array y[1], y[2], ..., y[n], where y[i] = x[n - i + 1] for each i.The number of inversions of an array x[1], x[2], ..., x[n] is the number of pairs of indices i, j such that: i &lt; j and x[i] &gt; x[j].
Java 7
standard input
[ "combinatorics", "divide and conquer" ]
ea7f8bd397f80ba7d3add6f9609dcc4a
The first line of input contains a single integer n (0 ≤ n ≤ 20). The second line of input contains 2n space-separated integers a[1], a[2], ..., a[2n] (1 ≤ a[i] ≤ 109), the initial array. The third line of input contains a single integer m (1 ≤ m ≤ 106). The fourth line of input contains m space-separated integers q1, q2, ..., qm (0 ≤ qi ≤ n), the queries. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
2,100
Output m lines. In the i-th line print the answer (the number of inversions) for the i-th query.
standard output
PASSED
b754d01422c94336329b4644041d38fe
train_000.jsonl
1396798800
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.You have an array a of length 2n and m queries on it. The i-th query is described by an integer qi. In order to perform the i-th query you must: split the array into 2n - qi parts, where each part is a subarray consisting of 2qi numbers; the j-th subarray (1 ≤ j ≤ 2n - qi) should contain the elements a[(j - 1)·2qi + 1], a[(j - 1)·2qi + 2], ..., a[(j - 1)·2qi + 2qi]; reverse each of the subarrays; join them into a single array in the same order (this array becomes new array a); output the number of inversions in the new a. Given initial array a and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries.
512 megabytes
import static java.util.Arrays.*; import java.text.*; public class C { public C () { int N = sc.nextInt(), Z = 1 << N; Integer [] A = new Integer [Z], B = new Integer [Z]; for (int i : rep(Z)) B[Z-1-i] = A[i] = sc.nextInt(); long X = 0; long [] S = new long [N+1]; for (int i : req(1, N)) X += S[i] = calc(A, 1 << i); long [] T = new long [N+1]; for (int i : req(1, N)) T[i] = calc(B, 1 << i); int M = sc.nextInt(); for (@SuppressWarnings("unused") int i : rep(M)) { int Q = sc.nextInt(); for (int j : req(1, Q)) { X += T[j] - S[j]; S[j] += T[j]; T[j] = S[j] - T[j]; S[j] -= T[j]; } print(X); } } long calc(Integer [] A, int M) { int Z = A.length; long res = 0; for (int i : rep(Z/M)) { int S = M*i, p = S, q = S + M/2; long c = 0; int P = S + M/2, Q = S + M; sort(A, p, P); sort(A, q, Q); while (p < P) if (q == Q || A[p] <= A[q]) { ++p; res += c; } else { ++q; ++c; } } return res; } private static int [] rep(int N) { return rep(0, N); } private static int [] rep(int S, int T) { if (T <= S) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; } private static int [] req(int S, int T) { return rep(S, T+1); } //////////////////////////////////////////////////////////////////////////////////// private final static IOUtils.MyScanner sc = new IOUtils.MyScanner(); private static void print (Object o, Object ...a) { IOUtils.print(o, a); } private static void exit() { IOUtils.exit(); } private static class IOUtils { public static class MyScanner { public String next() { newLine(); return line[index++]; } public int nextInt() { return Integer.parseInt(next()); } ////////////////////////////////////////////// private boolean eol() { return index == line.length; } private String readLine() { try { return r.readLine(); } catch (Exception e) { throw new Error (e); } } private final java.io.BufferedReader r; private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); } private MyScanner (java.io.BufferedReader r) { try { this.r = r; while (!r.ready()) Thread.sleep(1); start(); } catch (Exception e) { throw new Error(e); } } private String [] line; private int index; private void newLine() { if (line == null || eol()) { line = split(readLine()); index = 0; } } private String [] split(String s) { return s.length() > 0 ? s.split(" ") : new String [0]; } } private static String build(Object o, Object... a) { return buildDelim(" ", o, a); } private static String buildDelim(String delim, Object o, Object... a) { StringBuilder b = new StringBuilder(); append(b, o, delim); for (Object p : a) append(b, p, delim); return b.substring(delim.length()); } ////////////////////////////////////////////////////////////////////////////////// private static void start() { if (t == 0) t = millis(); } private static void append(StringBuilder b, Object o, String delim) { if (o.getClass().isArray()) { int len = java.lang.reflect.Array.getLength(o); for (int i = 0; i < len; ++i) append(b, java.lang.reflect.Array.get(o, i), delim); } else if (o instanceof Iterable<?>) for (Object p : (Iterable<?>) o) append(b, p, delim); else { if (o instanceof Double) o = new DecimalFormat("#.############").format(o); b.append(delim).append(o); } } private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out); private static void print(Object o, Object ...a) { pw.println(build(o, a)); } private static void err(Object o, Object ...a) { System.err.println(build(o, a)); } private static void exit() { IOUtils.pw.close(); System.out.flush(); err("------------------"); err(IOUtils.time()); System.exit(0); } private static long t; private static long millis() { return System.currentTimeMillis(); } private static String time() { return "Time: " + (millis() - t) / 1000.0; } } public static void main (String[] args) { new C(); exit(); } }
Java
["2\n2 1 4 3\n4\n1 2 0 2", "1\n1 2\n3\n0 1 1"]
4 seconds
["0\n6\n6\n0", "0\n1\n0"]
NoteIf we reverse an array x[1], x[2], ..., x[n] it becomes new array y[1], y[2], ..., y[n], where y[i] = x[n - i + 1] for each i.The number of inversions of an array x[1], x[2], ..., x[n] is the number of pairs of indices i, j such that: i &lt; j and x[i] &gt; x[j].
Java 7
standard input
[ "combinatorics", "divide and conquer" ]
ea7f8bd397f80ba7d3add6f9609dcc4a
The first line of input contains a single integer n (0 ≤ n ≤ 20). The second line of input contains 2n space-separated integers a[1], a[2], ..., a[2n] (1 ≤ a[i] ≤ 109), the initial array. The third line of input contains a single integer m (1 ≤ m ≤ 106). The fourth line of input contains m space-separated integers q1, q2, ..., qm (0 ≤ qi ≤ n), the queries. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
2,100
Output m lines. In the i-th line print the answer (the number of inversions) for the i-th query.
standard output
PASSED
8871731ae75c7ea624455b6b745d9a15
train_000.jsonl
1396798800
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.You have an array a of length 2n and m queries on it. The i-th query is described by an integer qi. In order to perform the i-th query you must: split the array into 2n - qi parts, where each part is a subarray consisting of 2qi numbers; the j-th subarray (1 ≤ j ≤ 2n - qi) should contain the elements a[(j - 1)·2qi + 1], a[(j - 1)·2qi + 2], ..., a[(j - 1)·2qi + 2qi]; reverse each of the subarrays; join them into a single array in the same order (this array becomes new array a); output the number of inversions in the new a. Given initial array a and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries.
512 megabytes
import java.io.*; import java.util.*; public class CF { FastScanner in; PrintWriter out; long[] inv1, inv2; int[] tmp = new int[1 << 21]; void go(int[] a, int l, int r, int h) { if (l == r) { return; } else { int m = (l + r) >> 1; m++; go(a, l, m - 1, h + 1); go(a, m, r, h + 1); { int it1 = l, it2 = m; int it = 0; while (it1 < m && it2 <= r) { if (a[it1] <= a[it2]) { tmp[it++] = a[it1++]; inv1[h] += (it2 - m); } else { tmp[it++] = a[it2++]; } } while (it1 < m) { tmp[it++] = a[it1++]; inv1[h] += it2 - m; } while (it2 <= r) { tmp[it++] = a[it2++]; } } { int it1 = l, it2 = m; while (it1 < m && it2 <= r) { if (a[it1] < a[it2]) { it1++; } else { inv2[h] += (it1 - l); it2++; } } while (it2 <= r) { inv2[h] += it1 - l; it2++; } } for (int i = l; i <= r; i++) { a[i] = tmp[i - l]; } } } void solve() { int n = in.nextInt(); inv1 = new long[n]; inv2 = new long[n]; int len = 1 << n; int[] a = new int[len]; for (int i = 0; i < len; i++) a[i] = in.nextInt(); go(a, 0, len - 1, 0); int m = in.nextInt(); boolean[] now = new boolean[n]; long nowInv = 0; for (int i = 0; i < n; i++) nowInv += inv1[i]; for (int i = 0; i < m; i++) { int q = in.nextInt(); for (int j = 0; j < q; j++) { now[n - 1 - j] = !now[n - 1 - j]; if (now[n - 1 - j]) { nowInv += inv2[n - 1 - j] - inv1[n - 1 - j]; } else { nowInv += inv1[n - 1 - j] - inv2[n - 1 - j]; } } out.println(nowInv); } } void run() { try { in = new FastScanner(new File("test.in")); out = new PrintWriter(new File("test.out")); solve(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } void runIO() { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public 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()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } } public static void main(String[] args) { new CF().runIO(); } }
Java
["2\n2 1 4 3\n4\n1 2 0 2", "1\n1 2\n3\n0 1 1"]
4 seconds
["0\n6\n6\n0", "0\n1\n0"]
NoteIf we reverse an array x[1], x[2], ..., x[n] it becomes new array y[1], y[2], ..., y[n], where y[i] = x[n - i + 1] for each i.The number of inversions of an array x[1], x[2], ..., x[n] is the number of pairs of indices i, j such that: i &lt; j and x[i] &gt; x[j].
Java 7
standard input
[ "combinatorics", "divide and conquer" ]
ea7f8bd397f80ba7d3add6f9609dcc4a
The first line of input contains a single integer n (0 ≤ n ≤ 20). The second line of input contains 2n space-separated integers a[1], a[2], ..., a[2n] (1 ≤ a[i] ≤ 109), the initial array. The third line of input contains a single integer m (1 ≤ m ≤ 106). The fourth line of input contains m space-separated integers q1, q2, ..., qm (0 ≤ qi ≤ n), the queries. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
2,100
Output m lines. In the i-th line print the answer (the number of inversions) for the i-th query.
standard output
PASSED
6d639ffbc2c30be3d403281e4b102cdb
train_000.jsonl
1396798800
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.You have an array a of length 2n and m queries on it. The i-th query is described by an integer qi. In order to perform the i-th query you must: split the array into 2n - qi parts, where each part is a subarray consisting of 2qi numbers; the j-th subarray (1 ≤ j ≤ 2n - qi) should contain the elements a[(j - 1)·2qi + 1], a[(j - 1)·2qi + 2], ..., a[(j - 1)·2qi + 2qi]; reverse each of the subarrays; join them into a single array in the same order (this array becomes new array a); output the number of inversions in the new a. Given initial array a and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries.
512 megabytes
import java.io.*; import java.util.*; public class cf414c { static FastIO in = new FastIO(), out = in; static long[] count1, count2; public static void main(String[] args) { int n = in.nextInt(); int[] v = new int[1<<n]; for(int i=0; i<1<<n; i++) v[i] = in.nextInt(); count1 = new long[n+1]; count2 = new long[n+1]; go(v, 0, 1<<n, n); int m = in.nextInt(); for(int z=0; z<m; z++) { long ret = 0; int x = in.nextInt(); for(int i=0; i<=x; i++) { long tmp = count1[i]; count1[i] = count2[i]; count2[i] = tmp; } for(int i=0; i<=n; i++) ret += count1[i]; out.println(ret); } out.close(); } static void go(int[] v, int l, int r, int level) { if(l+1 == r) return; int mid = (l+r)/2; go(v, l, mid, level-1); go(v, mid, r, level-1); int[] tmp = new int[r-l]; int cur = 0; int ind1 = l, ind2 = mid; while(ind1 < mid && ind2 < r) { if(v[ind1] < v[ind2]) { count2[level] += r-ind2; tmp[cur++] = v[ind1++]; } else if(v[ind1] > v[ind2]) { count1[level] += mid-ind1; tmp[cur++] = v[ind2++]; } else { int c1 = 0; int c2 = 0; int val = v[ind1]; while(ind1 < mid && v[ind1] == val) { ind1++; c1++; } while(ind2 < r && v[ind2] == val) { ind2++; c2++; } for(int i=0; i<c1+c2; i++) tmp[cur++] = val; count1[level] += (mid-ind1)*1L*c2; count2[level] += (r-ind2)*1L*c1; } } while(ind1 < mid) { tmp[cur++] = v[ind1++]; } while(ind2 < r) { tmp[cur++] = v[ind2++]; } for(int i=0; i<tmp.length; i++) v[l+i] = tmp[i]; } static class FastIO extends PrintWriter { BufferedReader br; StringTokenizer st; public FastIO() { this(System.in, System.out); } public FastIO(InputStream in, OutputStream out) { super(new BufferedWriter(new OutputStreamWriter(out))); 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
["2\n2 1 4 3\n4\n1 2 0 2", "1\n1 2\n3\n0 1 1"]
4 seconds
["0\n6\n6\n0", "0\n1\n0"]
NoteIf we reverse an array x[1], x[2], ..., x[n] it becomes new array y[1], y[2], ..., y[n], where y[i] = x[n - i + 1] for each i.The number of inversions of an array x[1], x[2], ..., x[n] is the number of pairs of indices i, j such that: i &lt; j and x[i] &gt; x[j].
Java 7
standard input
[ "combinatorics", "divide and conquer" ]
ea7f8bd397f80ba7d3add6f9609dcc4a
The first line of input contains a single integer n (0 ≤ n ≤ 20). The second line of input contains 2n space-separated integers a[1], a[2], ..., a[2n] (1 ≤ a[i] ≤ 109), the initial array. The third line of input contains a single integer m (1 ≤ m ≤ 106). The fourth line of input contains m space-separated integers q1, q2, ..., qm (0 ≤ qi ≤ n), the queries. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
2,100
Output m lines. In the i-th line print the answer (the number of inversions) for the i-th query.
standard output
PASSED
5757ad85394772dfef3ce5ca69ba3a59
train_000.jsonl
1396798800
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.You have an array a of length 2n and m queries on it. The i-th query is described by an integer qi. In order to perform the i-th query you must: split the array into 2n - qi parts, where each part is a subarray consisting of 2qi numbers; the j-th subarray (1 ≤ j ≤ 2n - qi) should contain the elements a[(j - 1)·2qi + 1], a[(j - 1)·2qi + 2], ..., a[(j - 1)·2qi + 2qi]; reverse each of the subarrays; join them into a single array in the same order (this array becomes new array a); output the number of inversions in the new a. Given initial array a and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries.
512 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.util.InputMismatchException; import java.io.PrintStream; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Nipuna Samarasekara */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { ///////////////////////////////////////////////////////////// long[] level; long[] sum; static int[] A; int N; public void solve(int testNumber, FastScanner in, FastPrinter out) { level=new long[30]; sum= new long[30]; int n=in.nextInt(); A=in.readIntArray((int)Math.pow(2,n)); N=(int)Math.pow(2,n); for (int i = 1; i < 30; i++) { sum[i]= (long)(Math.pow(2,i)-1)*(long)(N/2); } for (int i = 29; i >0 ; i--) { sum[i]-=sum[i-1]; } sort(0,N); int q=in.nextInt(); for (int i = 0; i < q; i++) { int t=in.nextInt(); for (int j = 1; j <= t ; j++) { level[j]=sum[j]-level[j]; } long ans=0; for (int k = 1; k < 30; k++) { ans+=level[k]; } out.println(ans); } } void sort(int low,int high){ if(high-low==1)return; int len=(high-low)/2; sort(low,low+len); sort(low+len,high); // System.out.println(low+" "+high+" "); int cc=high-low; int pos=0; while(cc>1){ cc/=2;pos++; } int[] temp= new int[len*2]; int ll=low,rr=low+len; while(ll<len+low&&rr<high){ if(A[ll]<A[rr]){ll++; continue; } if(A[ll]>A[rr]){rr++; continue; } if(A[ll]==A[rr]){ int val=A[ll]; long c1=0,c2=0; while(ll<len+low&&A[ll]==val){ll++;c1++;} while(rr<high&&A[rr]==val){rr++;c2++;} // System.out.println(A[ll]+" "+A[rr]+" "+c1+" "+c2); sum[pos]-=c1*c2; } } ll=low;rr=low+len; for (int i = 0; i < 2 * len; i++) { if(rr==high){ temp[i]=A[ll]; ll++; continue; } if(ll==low+len){ temp[i]=A[rr]; rr++; continue; } if(A[ll]<=A[rr]){ temp[i]=A[ll]; ll++; } else{ temp[i]=A[rr]; rr++; level[pos]+=low+len-ll; } } for (int i = 0; i < 2*len; i++) { A[low+i]=temp[i]; } } } 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 String readLine() { try { return super.readLine(); } catch (IOException e) { return null; } } public int[] readIntArray(int n) { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = nextInt(); } return ret; } } class FastPrinter extends PrintWriter { public FastPrinter(OutputStream out) { super(out); } public FastPrinter(Writer out) { super(out); } }
Java
["2\n2 1 4 3\n4\n1 2 0 2", "1\n1 2\n3\n0 1 1"]
4 seconds
["0\n6\n6\n0", "0\n1\n0"]
NoteIf we reverse an array x[1], x[2], ..., x[n] it becomes new array y[1], y[2], ..., y[n], where y[i] = x[n - i + 1] for each i.The number of inversions of an array x[1], x[2], ..., x[n] is the number of pairs of indices i, j such that: i &lt; j and x[i] &gt; x[j].
Java 7
standard input
[ "combinatorics", "divide and conquer" ]
ea7f8bd397f80ba7d3add6f9609dcc4a
The first line of input contains a single integer n (0 ≤ n ≤ 20). The second line of input contains 2n space-separated integers a[1], a[2], ..., a[2n] (1 ≤ a[i] ≤ 109), the initial array. The third line of input contains a single integer m (1 ≤ m ≤ 106). The fourth line of input contains m space-separated integers q1, q2, ..., qm (0 ≤ qi ≤ n), the queries. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
2,100
Output m lines. In the i-th line print the answer (the number of inversions) for the i-th query.
standard output
PASSED
9fe0d0154ceff6a128e488edba775a25
train_000.jsonl
1396798800
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.You have an array a of length 2n and m queries on it. The i-th query is described by an integer qi. In order to perform the i-th query you must: split the array into 2n - qi parts, where each part is a subarray consisting of 2qi numbers; the j-th subarray (1 ≤ j ≤ 2n - qi) should contain the elements a[(j - 1)·2qi + 1], a[(j - 1)·2qi + 2], ..., a[(j - 1)·2qi + 2qi]; reverse each of the subarrays; join them into a single array in the same order (this array becomes new array a); output the number of inversions in the new a. Given initial array a and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries.
512 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class C { static long[] inversions; static long[] oddversions; public static void main(String[] args) throws Exception{ int n = readInt(); inversions = new long[n+1]; oddversions = new long[n+1]; int nn = 1; StringBuilder sb = new StringBuilder(); for(int i = 1; i <= n; i++){ nn*=2; } int[] list = new int[nn]; for(int i = 0 ; i < nn; i++){ list[i] = readInt(); } merge(list, 0, nn-1, n); boolean[] rev = new boolean[n+1]; int m = readInt(); for(int i = 0; i < m; i++){ int q = readInt(); for(int j = 1; j <= q; j++){ rev[j] = !rev[j]; } long ans = 0; for(int j = 1; j <= n; j++){ if(rev[j]){ ans += oddversions[j]; } else{ ans += inversions[j]; } } sb.append(ans); sb.append("\n"); } System.out.println(sb); } static int[] merge(int[] list, int a, int b, int lvl){ if(a == b){ int[] c = new int[1]; c[0] = list[a]; if(c[0] > 1){ } return c; } int[] l = merge(list, a, ((a+b)/2), lvl-1); int[] r = merge(list, ((a+b)/2) + 1 , b, lvl-1); int len = l.length; int[] c = new int[2*len]; int i = 0; int j = 0; while(i+j < 2*len){ if(i == l.length){ c[i+j] = r[j]; j++; } else if(j == r.length){ c[i+j] = l[i]; i++; } else{ if(l[i] <= r[j]){ c[i+j] = l[i]; i++; } else{ c[i + j] = r[j]; inversions[lvl]+= len-i; j++; } } } i = len-1; j = len-1; while(i+j > - 2){ if(j == -1){ i--; } else if(i == -1){ j--; } else{ if(l[i] < r[j]){ oddversions[lvl]+= i+1; j--; } else{ i--; } } } return c; } static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st = new StringTokenizer(" "); static String readString() throws Exception{ while(!st.hasMoreTokens()){ st = new StringTokenizer(stdin.readLine()); } return st.nextToken(); } static int readInt() throws Exception { return Integer.parseInt(readString()); } static long readLong() throws Exception { return Long.parseLong(readString()); } }
Java
["2\n2 1 4 3\n4\n1 2 0 2", "1\n1 2\n3\n0 1 1"]
4 seconds
["0\n6\n6\n0", "0\n1\n0"]
NoteIf we reverse an array x[1], x[2], ..., x[n] it becomes new array y[1], y[2], ..., y[n], where y[i] = x[n - i + 1] for each i.The number of inversions of an array x[1], x[2], ..., x[n] is the number of pairs of indices i, j such that: i &lt; j and x[i] &gt; x[j].
Java 7
standard input
[ "combinatorics", "divide and conquer" ]
ea7f8bd397f80ba7d3add6f9609dcc4a
The first line of input contains a single integer n (0 ≤ n ≤ 20). The second line of input contains 2n space-separated integers a[1], a[2], ..., a[2n] (1 ≤ a[i] ≤ 109), the initial array. The third line of input contains a single integer m (1 ≤ m ≤ 106). The fourth line of input contains m space-separated integers q1, q2, ..., qm (0 ≤ qi ≤ n), the queries. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
2,100
Output m lines. In the i-th line print the answer (the number of inversions) for the i-th query.
standard output
PASSED
080291caa5882b01bd8bc1741c798fec
train_000.jsonl
1396798800
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.You have an array a of length 2n and m queries on it. The i-th query is described by an integer qi. In order to perform the i-th query you must: split the array into 2n - qi parts, where each part is a subarray consisting of 2qi numbers; the j-th subarray (1 ≤ j ≤ 2n - qi) should contain the elements a[(j - 1)·2qi + 1], a[(j - 1)·2qi + 2], ..., a[(j - 1)·2qi + 2qi]; reverse each of the subarrays; join them into a single array in the same order (this array becomes new array a); output the number of inversions in the new a. Given initial array a and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries.
512 megabytes
import java.util.*; import java.io.*; public class C { public static long time = 0; public static void main(String[] args) throws Exception { time = System.currentTimeMillis(); IN = System.in; OUT = System.out; in = new BufferedReader(new InputStreamReader(IN)); out = new PrintWriter(OUT, FLUSH); solveOne(); out.flush(); } public static void solveOne() throws Exception { int n1 = ni(); int[] l1 = nil(1 << n1); long[] count = new long[n1 + 1]; long[] opp = new long[n1 + 1]; for (int i = 1; i <= n1; i++){ int segNo = 1 << (n1 - i); int halfLen = 1 << (i - 1); // px(i ,segNo,halfLen); for (int j = 0; j < segNo; j++){ int start1 = j * (1 << i); int end1 = start1 + (1 << (i - 1) ); int end2 = start1 + (1 << i) - 1; Arrays.sort(l1, start1, end1); Arrays.sort(l1, end1, start1 + (1 << i)); { int ptr = 0; for (int k = 0; k < halfLen; k++){ for (;;){ if (ptr >= halfLen) break; if (l1[start1 + k] > l1[end1 + ptr]){ ptr++; } else { break; } } count[i] += (long)ptr; } } { int ptr = 0; for (int k = 0; k < halfLen; k++){ for (;;){ if (ptr >= halfLen) break; if (l1[start1 + k] >= l1[end1 + ptr]){ ptr++; } else { break; } } opp[i] += (long)(halfLen - ptr); } } } // px(l1); } // px(count); // px(opp); // px(total); int m1 = ni(); for (int qq = 0; qq < m1; qq++){ int k1 = ni(); for (int i = 0; i <= k1; i++){ long temp = count[i]; count[i] = opp[i]; opp[i] = temp; } // px(count); // px(opp); long sum = 0; for (long e: count){ sum += e; } pn(sum); } } public static void solveTwo() throws Exception { } public static void solveThree() throws Exception { } public static BufferedReader in; public static StringTokenizer st; public static InputStream IN; public static OutputStream OUT; public static String nx() throws Exception { for (;st == null || !st.hasMoreTokens();){ String k1 = in.readLine(); if (k1 == null) return null; st = new StringTokenizer(k1); } return st.nextToken(); } public static int ni () throws Exception { return Integer.parseInt(nx()); } public static long nl() throws Exception{ return Long.parseLong(nx()); } public static double nd() throws Exception{ return Double.parseDouble(nx()); } private static int[] nil(int n1) throws Exception { int[] l1 = new int[n1]; for (int i = 0 ;i < n1; i++){ l1[i] = ni(); } return l1; } public static void px(Object ... l1){ System.out.println(Arrays.deepToString(l1)); } public static boolean FLUSH = false; public static PrintWriter out; public static void p(Object ... l1){ for (int i = 0; i < l1.length; i++){ if (i != 0) out.print(' '); out.print(l1[i].toString()); } } public static void pn(Object ... l1){ for (int i = 0; i < l1.length; i++){ if (i != 0) out.print(' '); out.print(l1[i].toString()); } out.println(); } public static void pn(Collection l1){ boolean first = true; for (Object e: l1){ if (first) first = false; else out.print(' '); out.print(e.toString()); } out.println(); } }
Java
["2\n2 1 4 3\n4\n1 2 0 2", "1\n1 2\n3\n0 1 1"]
4 seconds
["0\n6\n6\n0", "0\n1\n0"]
NoteIf we reverse an array x[1], x[2], ..., x[n] it becomes new array y[1], y[2], ..., y[n], where y[i] = x[n - i + 1] for each i.The number of inversions of an array x[1], x[2], ..., x[n] is the number of pairs of indices i, j such that: i &lt; j and x[i] &gt; x[j].
Java 7
standard input
[ "combinatorics", "divide and conquer" ]
ea7f8bd397f80ba7d3add6f9609dcc4a
The first line of input contains a single integer n (0 ≤ n ≤ 20). The second line of input contains 2n space-separated integers a[1], a[2], ..., a[2n] (1 ≤ a[i] ≤ 109), the initial array. The third line of input contains a single integer m (1 ≤ m ≤ 106). The fourth line of input contains m space-separated integers q1, q2, ..., qm (0 ≤ qi ≤ n), the queries. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
2,100
Output m lines. In the i-th line print the answer (the number of inversions) for the i-th query.
standard output
PASSED
02abde9f9378d93fdc49d9bf07084918
train_000.jsonl
1396798800
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.You have an array a of length 2n and m queries on it. The i-th query is described by an integer qi. In order to perform the i-th query you must: split the array into 2n - qi parts, where each part is a subarray consisting of 2qi numbers; the j-th subarray (1 ≤ j ≤ 2n - qi) should contain the elements a[(j - 1)·2qi + 1], a[(j - 1)·2qi + 2], ..., a[(j - 1)·2qi + 2qi]; reverse each of the subarrays; join them into a single array in the same order (this array becomes new array a); output the number of inversions in the new a. Given initial array a and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries.
512 megabytes
import java.util.*; import java.io.*; public class C { public static long time = 0; public static void main(String[] args) throws Exception { time = System.currentTimeMillis(); IN = System.in; OUT = System.out; in = new BufferedReader(new InputStreamReader(IN)); out = new PrintWriter(OUT, FLUSH); solveOne(); out.flush(); } public static void solveOne() throws Exception { int n1 = ni(); int[] l1 = nil(1 << n1); long[] count = new long[n1 + 1]; long[] opp = new long[n1 + 1]; for (int i = 1; i <= n1; i++){ int segNo = 1 << (n1 - i); int halfLen = 1 << (i - 1); // px(i ,segNo,halfLen); for (int j = 0; j < segNo; j++){ int start1 = (j << i); int end1 = start1 + (1 << (i - 1) ); int end2 = start1 + (1 << i) - 1; Arrays.sort(l1, start1, end1); Arrays.sort(l1, end1, start1 + (1 << i)); { int ptr = 0; for (int k = 0; k < halfLen; k++){ for (;;){ if (ptr >= halfLen) break; if (l1[start1 + k] > l1[end1 + ptr]){ ptr++; } else { break; } } count[i] += (long)ptr; } } { int ptr = 0; for (int k = 0; k < halfLen; k++){ for (;;){ if (ptr >= halfLen) break; if (l1[start1 + k] >= l1[end1 + ptr]){ ptr++; } else { break; } } opp[i] += (long)(halfLen - ptr); } } } // px(l1); } // px(count); // px(opp); // px(total); int m1 = ni(); for (int qq = 0; qq < m1; qq++){ int k1 = ni(); for (int i = 0; i <= k1; i++){ long temp = count[i]; count[i] = opp[i]; opp[i] = temp; } // px(count); // px(opp); long sum = 0; for (long e: count){ sum += e; } pn(sum); } } public static void solveTwo() throws Exception { } public static void solveThree() throws Exception { } public static BufferedReader in; public static StringTokenizer st; public static InputStream IN; public static OutputStream OUT; public static String nx() throws Exception { for (;st == null || !st.hasMoreTokens();){ String k1 = in.readLine(); if (k1 == null) return null; st = new StringTokenizer(k1); } return st.nextToken(); } public static int ni () throws Exception { return Integer.parseInt(nx()); } public static long nl() throws Exception{ return Long.parseLong(nx()); } public static double nd() throws Exception{ return Double.parseDouble(nx()); } private static int[] nil(int n1) throws Exception { int[] l1 = new int[n1]; for (int i = 0 ;i < n1; i++){ l1[i] = ni(); } return l1; } public static void px(Object ... l1){ System.out.println(Arrays.deepToString(l1)); } public static boolean FLUSH = false; public static PrintWriter out; public static void p(Object ... l1){ for (int i = 0; i < l1.length; i++){ if (i != 0) out.print(' '); out.print(l1[i].toString()); } } public static void pn(Object ... l1){ for (int i = 0; i < l1.length; i++){ if (i != 0) out.print(' '); out.print(l1[i].toString()); } out.println(); } public static void pn(Collection l1){ boolean first = true; for (Object e: l1){ if (first) first = false; else out.print(' '); out.print(e.toString()); } out.println(); } }
Java
["2\n2 1 4 3\n4\n1 2 0 2", "1\n1 2\n3\n0 1 1"]
4 seconds
["0\n6\n6\n0", "0\n1\n0"]
NoteIf we reverse an array x[1], x[2], ..., x[n] it becomes new array y[1], y[2], ..., y[n], where y[i] = x[n - i + 1] for each i.The number of inversions of an array x[1], x[2], ..., x[n] is the number of pairs of indices i, j such that: i &lt; j and x[i] &gt; x[j].
Java 7
standard input
[ "combinatorics", "divide and conquer" ]
ea7f8bd397f80ba7d3add6f9609dcc4a
The first line of input contains a single integer n (0 ≤ n ≤ 20). The second line of input contains 2n space-separated integers a[1], a[2], ..., a[2n] (1 ≤ a[i] ≤ 109), the initial array. The third line of input contains a single integer m (1 ≤ m ≤ 106). The fourth line of input contains m space-separated integers q1, q2, ..., qm (0 ≤ qi ≤ n), the queries. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
2,100
Output m lines. In the i-th line print the answer (the number of inversions) for the i-th query.
standard output
PASSED
4609da63cbf4ad56a3df0eee70a6de2a
train_000.jsonl
1396798800
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.You have an array a of length 2n and m queries on it. The i-th query is described by an integer qi. In order to perform the i-th query you must: split the array into 2n - qi parts, where each part is a subarray consisting of 2qi numbers; the j-th subarray (1 ≤ j ≤ 2n - qi) should contain the elements a[(j - 1)·2qi + 1], a[(j - 1)·2qi + 2], ..., a[(j - 1)·2qi + 2qi]; reverse each of the subarrays; join them into a single array in the same order (this array becomes new array a); output the number of inversions in the new a. Given initial array a and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries.
512 megabytes
import java.io.BufferedReader; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; 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); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int len = 1 << n; int[] a = new int[len]; for (int i = 0; i < len; i++) { a[i] = in.nextInt(); } long[] inv = new long[n + 1]; long[] total = new long[n + 1]; for (int i = 0; i <= n; i++) { int block = (1 << i); int[] b = a.clone(); for (int j = 0; j < len / block; j++) { inv[i] += inversions(b, j * block, (j + 1) * block); reverse(b, j * block, (j + 1) * block); total[i] += inversions(b, j * block, (j + 1) * block); } } int m = in.nextInt(); for (int i = 0; i < m; i++) { int q = in.nextInt(); long prev = inv[q]; long next = total[q] - inv[q]; for (int j = 0; j < q; j++) { inv[j] = total[j] - inv[j]; } inv[q] = next; for (int j = q + 1; j <= n; j++) { inv[j] += next - prev; } out.println(inv[n]); } } private void reverse(int[] a, int i, int j) { --j; for (; i < j; i++, j--) { int t = a[i]; a[i] = a[j]; a[j] = t; } } static long inversions(int[] a, int low, int high) { if (low >= high - 1) return 0; int mid = (low + high) >>> 1; long res1 = inversions(a, low, mid); long res2 = inversions(a, mid, high); long res = res1 + res2; int size = high - low; int[] b = new int[size]; int i = low; int j = mid; for (int k = 0; k < size; k++) { if (j >= high || i < mid && a[i] <= a[j]) { b[k] = a[i++]; } else { b[k] = a[j++]; res += mid - i; } } System.arraycopy(b, 0, a, low, size); return res; } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } 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()); } }
Java
["2\n2 1 4 3\n4\n1 2 0 2", "1\n1 2\n3\n0 1 1"]
4 seconds
["0\n6\n6\n0", "0\n1\n0"]
NoteIf we reverse an array x[1], x[2], ..., x[n] it becomes new array y[1], y[2], ..., y[n], where y[i] = x[n - i + 1] for each i.The number of inversions of an array x[1], x[2], ..., x[n] is the number of pairs of indices i, j such that: i &lt; j and x[i] &gt; x[j].
Java 7
standard input
[ "combinatorics", "divide and conquer" ]
ea7f8bd397f80ba7d3add6f9609dcc4a
The first line of input contains a single integer n (0 ≤ n ≤ 20). The second line of input contains 2n space-separated integers a[1], a[2], ..., a[2n] (1 ≤ a[i] ≤ 109), the initial array. The third line of input contains a single integer m (1 ≤ m ≤ 106). The fourth line of input contains m space-separated integers q1, q2, ..., qm (0 ≤ qi ≤ n), the queries. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
2,100
Output m lines. In the i-th line print the answer (the number of inversions) for the i-th query.
standard output
PASSED
85eb179afbbe68d020367df27dc56c86
train_000.jsonl
1396798800
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.You have an array a of length 2n and m queries on it. The i-th query is described by an integer qi. In order to perform the i-th query you must: split the array into 2n - qi parts, where each part is a subarray consisting of 2qi numbers; the j-th subarray (1 ≤ j ≤ 2n - qi) should contain the elements a[(j - 1)·2qi + 1], a[(j - 1)·2qi + 2], ..., a[(j - 1)·2qi + 2qi]; reverse each of the subarrays; join them into a single array in the same order (this array becomes new array a); output the number of inversions in the new a. Given initial array a and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries.
512 megabytes
import java.io.*; import java.util.*; public class R240QeMashmokhAndReverseOperations { static int n; static int a[]; static long inv[],other[]; static long globalEq; public static void main(String args[] ) throws Exception { InputReader4 in = new InputReader4(System.in); PrintWriter w = new PrintWriter(System.out); n = in.nextInt(); a = new int[(1<<n)]; for(int i=0;i<(1<<n);i++) a[i] = in.nextInt(); inv = new long[n+1]; other = new long[n+1]; mergeSort(0,(1<<n) - 1); // System.out.println("Equal " + Arrays.toString(equal)); // System.out.println("Inv " + Arrays.toString(inv)); int m = in.nextInt(); for(int i=0;i<m;i++){ int q = in.nextInt(); for(int j=1;j<=q;j++){ long t = other[j]; other[j] = inv[j]; inv[j] = t; } //System.out.println(Arrays.toString(inv)); long ans = 0; for(int j=1;j<=n;j++) ans += inv[j]; w.println(ans); } w.close(); } public static int ip(String s){ return Integer.parseInt(s); } public static void mergeSort(int start,int end){ if(start == end) return; int mid = (start + end) / 2; mergeSort(start,mid); mergeSort(mid+1,end); int size = Integer.toBinaryString(end - start + 1).length() - 1; merge(start,mid,end,size); } public static void merge(int start,int mid,int end,int size){ int temp[] = new int[end - start + 1]; int i = start,j = mid + 1,k=0; long inve = 0,othr = 0; while(i <= mid && j <= end){ if(a[i] <= a[j]) temp[k++] = a[i++]; else{ inve += mid + 1 - i; temp[k++] = a[j++]; } } while(i <= mid) temp[k++] = a[i++]; while(j <= end) temp[k++] = a[j++]; for(i=start,j=mid+1;i<=mid && j<=end;i++,j++){ int t = a[i]; a[i] = a[j]; a[j] = t; } i = start; j = mid + 1; while(i <= mid && j <= end){ if(a[i] <= a[j]) i++; else{ othr += mid + 1 - i; j++; } } inv[size] += inve; other[size] += othr; for(int x=0;x<k;x++) a[start + x] = temp[x]; } } class InputReader4 { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader4(InputStream stream) { this.stream = stream; } public int snext() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["2\n2 1 4 3\n4\n1 2 0 2", "1\n1 2\n3\n0 1 1"]
4 seconds
["0\n6\n6\n0", "0\n1\n0"]
NoteIf we reverse an array x[1], x[2], ..., x[n] it becomes new array y[1], y[2], ..., y[n], where y[i] = x[n - i + 1] for each i.The number of inversions of an array x[1], x[2], ..., x[n] is the number of pairs of indices i, j such that: i &lt; j and x[i] &gt; x[j].
Java 7
standard input
[ "combinatorics", "divide and conquer" ]
ea7f8bd397f80ba7d3add6f9609dcc4a
The first line of input contains a single integer n (0 ≤ n ≤ 20). The second line of input contains 2n space-separated integers a[1], a[2], ..., a[2n] (1 ≤ a[i] ≤ 109), the initial array. The third line of input contains a single integer m (1 ≤ m ≤ 106). The fourth line of input contains m space-separated integers q1, q2, ..., qm (0 ≤ qi ≤ n), the queries. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
2,100
Output m lines. In the i-th line print the answer (the number of inversions) for the i-th query.
standard output
PASSED
4c3f517930309c34b90a9d77dea59ae3
train_000.jsonl
1396798800
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.You have an array a of length 2n and m queries on it. The i-th query is described by an integer qi. In order to perform the i-th query you must: split the array into 2n - qi parts, where each part is a subarray consisting of 2qi numbers; the j-th subarray (1 ≤ j ≤ 2n - qi) should contain the elements a[(j - 1)·2qi + 1], a[(j - 1)·2qi + 2], ..., a[(j - 1)·2qi + 2qi]; reverse each of the subarrays; join them into a single array in the same order (this array becomes new array a); output the number of inversions in the new a. Given initial array a and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries.
512 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.util.InputMismatchException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; 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); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int []a = new int[1 << n]; for (int i = 0; i < a.length; ++i) { a[i] = in.nextInt(); } inv = new long[n + 1]; ord = new long[n + 1]; mergeSort(a, 0, a.length); int m = in.nextInt(); for (int i = 0; i < m; ++i) { int q = in.nextInt(); for (int t = 0; t <= q; ++t) { long temp = inv[t]; inv[t] = ord[t]; ord[t] = temp; } long res = 0; for (int t = 0; t <= n; ++t) { res += inv[t]; } out.println(res); } } void mergeSort(int []a, int begin, int end) { if (end - begin == 1) { return; } int mid = (begin + end) / 2; mergeSort(a, begin, mid); mergeSort(a, mid, end); int level = 0; while ((1 << level) < end - begin) ++level; // Count inversions. for (int i = begin, j = mid; i < mid && j < end;) { if (a[i] <= a[j]) { ++i; } else { inv[level] += mid - i; ++j; } } // Count orders. for (int i = begin, j = mid; i < mid && j < end;) { if (a[i] < a[j]) { ord[level] += end - j; ++i; } else { ++j; } } // Merge. int []b = new int[end - begin]; int size = 0, i = begin, j = mid; while (i < mid && j < end) { if (a[i] <= a[j]) { b[size++] = a[i++]; } else { b[size++] = a[j++]; } } while (i < mid) b[size++] = a[i++]; while (j < end) b[size++] = a[j++]; for (int t = 0; t < size; ++t) { a[begin + t] = b[t]; } } long []inv; long []ord; } class InputReader { BufferedReader bufReader; StringTokenizer stringTokenizer; public InputReader(InputStream stream) { bufReader = new BufferedReader(new InputStreamReader(stream)); } String nextString() { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { try { String line = bufReader.readLine(); if (line == null) { return null; } stringTokenizer = new StringTokenizer(line); } catch (IOException e) { throw new InputMismatchException(); } } return stringTokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(nextString()); } }
Java
["2\n2 1 4 3\n4\n1 2 0 2", "1\n1 2\n3\n0 1 1"]
4 seconds
["0\n6\n6\n0", "0\n1\n0"]
NoteIf we reverse an array x[1], x[2], ..., x[n] it becomes new array y[1], y[2], ..., y[n], where y[i] = x[n - i + 1] for each i.The number of inversions of an array x[1], x[2], ..., x[n] is the number of pairs of indices i, j such that: i &lt; j and x[i] &gt; x[j].
Java 7
standard input
[ "combinatorics", "divide and conquer" ]
ea7f8bd397f80ba7d3add6f9609dcc4a
The first line of input contains a single integer n (0 ≤ n ≤ 20). The second line of input contains 2n space-separated integers a[1], a[2], ..., a[2n] (1 ≤ a[i] ≤ 109), the initial array. The third line of input contains a single integer m (1 ≤ m ≤ 106). The fourth line of input contains m space-separated integers q1, q2, ..., qm (0 ≤ qi ≤ n), the queries. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
2,100
Output m lines. In the i-th line print the answer (the number of inversions) for the i-th query.
standard output
PASSED
7dcdcc8f97d80db24e46ff5909a6befd
train_000.jsonl
1396798800
Mashmokh's boss, Bimokh, didn't like Mashmokh. So he fired him. Mashmokh decided to go to university and participate in ACM instead of finding a new job. He wants to become a member of Bamokh's team. In order to join he was given some programming tasks and one week to solve them. Mashmokh is not a very experienced programmer. Actually he is not a programmer at all. So he wasn't able to solve them. That's why he asked you to help him with these tasks. One of these tasks is the following.You have an array a of length 2n and m queries on it. The i-th query is described by an integer qi. In order to perform the i-th query you must: split the array into 2n - qi parts, where each part is a subarray consisting of 2qi numbers; the j-th subarray (1 ≤ j ≤ 2n - qi) should contain the elements a[(j - 1)·2qi + 1], a[(j - 1)·2qi + 2], ..., a[(j - 1)·2qi + 2qi]; reverse each of the subarrays; join them into a single array in the same order (this array becomes new array a); output the number of inversions in the new a. Given initial array a and all the queries. Answer all the queries. Please, note that the changes from some query is saved for further queries.
512 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.util.InputMismatchException; import java.io.PrintStream; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; 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); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int []a = new int[1 << n]; for (int i = 0; i < a.length; ++i) { a[i] = in.nextInt(); } inv = new long[n + 1]; ord = new long[n + 1]; mergeSort(a, 0, a.length); debug(); int m = in.nextInt(); for (int i = 0; i < m; ++i) { int q = in.nextInt(); for (int t = 0; t <= q; ++t) { long temp = inv[t]; inv[t] = ord[t]; ord[t] = temp; } debug(); long res = 0; for (int t = 0; t <= n; ++t) { res += inv[t]; } out.println(res); } } void debug() { } void mergeSort(int []a, int begin, int end) { if (end - begin == 1) { return; } int mid = (begin + end) / 2; mergeSort(a, begin, mid); mergeSort(a, mid, end); int level = 0; while ((1 << level) < end - begin) ++level; // Count inversions. for (int i = begin, j = mid; i < mid && j < end;) { if (a[i] <= a[j]) { ++i; } else { inv[level] += mid - i; ++j; } } // Count orders. for (int i = begin, j = mid; i < mid && j < end;) { if (a[i] < a[j]) { ord[level] += end - j; ++i; } else { ++j; } } // Merge. int []b = new int[end - begin]; int size = 0, i = begin, j = mid; while (i < mid && j < end) { if (a[i] <= a[j]) { b[size++] = a[i++]; } else { b[size++] = a[j++]; } } while (i < mid) b[size++] = a[i++]; while (j < end) b[size++] = a[j++]; for (int t = 0; t < size; ++t) { a[begin + t] = b[t]; } } long []inv; long []ord; } class InputReader { BufferedReader bufReader; StringTokenizer stringTokenizer; public InputReader(InputStream stream) { bufReader = new BufferedReader(new InputStreamReader(stream)); } String nextString() { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { try { String line = bufReader.readLine(); if (line == null) { return null; } stringTokenizer = new StringTokenizer(line); } catch (IOException e) { throw new InputMismatchException(); } } return stringTokenizer.nextToken(); } public int nextInt() { String s = nextString(); return Integer.parseInt(s); } }
Java
["2\n2 1 4 3\n4\n1 2 0 2", "1\n1 2\n3\n0 1 1"]
4 seconds
["0\n6\n6\n0", "0\n1\n0"]
NoteIf we reverse an array x[1], x[2], ..., x[n] it becomes new array y[1], y[2], ..., y[n], where y[i] = x[n - i + 1] for each i.The number of inversions of an array x[1], x[2], ..., x[n] is the number of pairs of indices i, j such that: i &lt; j and x[i] &gt; x[j].
Java 7
standard input
[ "combinatorics", "divide and conquer" ]
ea7f8bd397f80ba7d3add6f9609dcc4a
The first line of input contains a single integer n (0 ≤ n ≤ 20). The second line of input contains 2n space-separated integers a[1], a[2], ..., a[2n] (1 ≤ a[i] ≤ 109), the initial array. The third line of input contains a single integer m (1 ≤ m ≤ 106). The fourth line of input contains m space-separated integers q1, q2, ..., qm (0 ≤ qi ≤ n), the queries. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++.
2,100
Output m lines. In the i-th line print the answer (the number of inversions) for the i-th query.
standard output
PASSED
b17ea381e4e9e1d5b711258a4a35c72d
train_000.jsonl
1438790400
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≤ i1 &lt; i2 &lt; i3 ≤ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.A geometric progression with common ratio k is a sequence of numbers of the form b·k0, b·k1, ..., b·kr - 1.Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.
256 megabytes
import java.util.HashMap; import java.util.Scanner; /** * * @author interoperabilidad */ public class GeometricProgression { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner scanner= new Scanner(System.in); int n = scanner.nextInt(); int k = scanner.nextInt(); HashMap<Long, Integer> ar = new HashMap<>(); HashMap<Long, Integer> al = new HashMap<>(); long x[] = new long[n]; for(int i = 0; i < n; i++){ x[i] = scanner.nextLong(); if(ar.get(x[i]) != null){ ar.put(x[i], ar.get(x[i])+1); }else{ ar.put(x[i], 1); } } long res = 0; for(int i = 0; i < n; i++){ ar.put(x[i], ar.get(x[i]) - 1); if(x[i] % k == 0){ Integer b = al.get(x[i]/k); if(b == null){ b = 0; al.put(x[i]/k, 0); } Integer a = ar.get(x[i]*k); if(a == null){ a = 0; ar.put(x[i]*k, 0); } res += (long)a*(long)b; } Integer a = al.get(x[i]); if(a == null){ a = 0; al.put(x[i], a); } al.put(x[i], a+1); } System.out.println(res); } }
Java
["5 2\n1 1 2 2 4", "3 1\n1 1 1", "10 3\n1 2 6 2 3 6 9 18 3 9"]
1 second
["4", "1", "6"]
NoteIn the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
Java 7
standard input
[ "dp", "binary search", "data structures" ]
bd4b3bfa7511410c8e54658cc1dddb46
The first line of the input contains two integers, n and k (1 ≤ n, k ≤ 2·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — elements of the sequence.
1,700
Output a single number — the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.
standard output
PASSED
c541c4806a7d85034a7537fd16ccd1f4
train_000.jsonl
1438790400
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≤ i1 &lt; i2 &lt; i3 ≤ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.A geometric progression with common ratio k is a sequence of numbers of the form b·k0, b·k1, ..., b·kr - 1.Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.
256 megabytes
import java.io.*; import java.util.*; public class Program { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; static final int MOD = 1000000007; static final double INF = 10000000000.0; void solve() throws IOException { long n, k, a[]; n = nextInt(); k = nextInt(); a = new long[(int)n]; HashMap<Long, Integer> lf, rf; lf = new HashMap<>(); rf = new HashMap<>(); for(int i = 0; i < n; i++) { a[i] = nextInt(); if (rf.containsKey(a[i])) rf.put(a[i], rf.get(a[i])+1); else rf.put(a[i], 1); } long ans = 0; for(int i = 0; i < n; i++) { long k1 = 0, k2 = 0; rf.put(a[i], rf.get(a[i])-1); if (lf.containsKey(a[i]/k)) k1 = lf.get(a[i]/k); if (rf.containsKey(a[i]*k)) k2 = rf.get(a[i]*k); if (lf.containsKey(a[i])) lf.put(a[i], lf.get(a[i])+1); else lf.put(a[i], 1); if (a[i] % k == 0) ans += k1 * k2; } out.println(ans); } Program() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new Program(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["5 2\n1 1 2 2 4", "3 1\n1 1 1", "10 3\n1 2 6 2 3 6 9 18 3 9"]
1 second
["4", "1", "6"]
NoteIn the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
Java 7
standard input
[ "dp", "binary search", "data structures" ]
bd4b3bfa7511410c8e54658cc1dddb46
The first line of the input contains two integers, n and k (1 ≤ n, k ≤ 2·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — elements of the sequence.
1,700
Output a single number — the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.
standard output
PASSED
05923ca1ce93c9955f3b83671296c00c
train_000.jsonl
1438790400
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≤ i1 &lt; i2 &lt; i3 ≤ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.A geometric progression with common ratio k is a sequence of numbers of the form b·k0, b·k1, ..., b·kr - 1.Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashMap; import java.util.StringTokenizer; public class R314Div2C { public static void main(String[] args) { FastScanner in=new FastScanner(); int n=in.nextInt(); long k=in.nextLong(); long[] a=new long[n]; for(int i=0;i<n;i++) a[i]=in.nextLong(); HashMap<Long,long[]> map=new HashMap<Long,long[]>(); for(int i=0;i<n;i++){ long[] v=new long[3]; if(map.containsKey(a[i])) v=map.get(a[i]); if(Math.abs(a[i])%(k*k)==0){ long b=a[i]/k; if(map.containsKey(b)) v[2]+=map.get(b)[1]; } if(Math.abs(a[i])%k==0){ long b=a[i]/k; if(map.containsKey(b)) v[1]+=map.get(b)[0]; } v[0]++; map.put(a[i],v); } long ans=0; for(long key:map.keySet()){ ans+=map.get(key)[2]; } System.out.println(ans); } static class FastScanner{ BufferedReader br; StringTokenizer st; public FastScanner(){br=new BufferedReader(new InputStreamReader(System.in));} String nextToken(){ while(st==null||!st.hasMoreElements()) try{st=new StringTokenizer(br.readLine());}catch(Exception e){} return st.nextToken(); } int nextInt(){return Integer.parseInt(nextToken());} long nextLong(){return Long.parseLong(nextToken());} double nextDouble(){return Double.parseDouble(nextToken());} } }
Java
["5 2\n1 1 2 2 4", "3 1\n1 1 1", "10 3\n1 2 6 2 3 6 9 18 3 9"]
1 second
["4", "1", "6"]
NoteIn the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
Java 7
standard input
[ "dp", "binary search", "data structures" ]
bd4b3bfa7511410c8e54658cc1dddb46
The first line of the input contains two integers, n and k (1 ≤ n, k ≤ 2·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — elements of the sequence.
1,700
Output a single number — the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.
standard output
PASSED
468865b81639b5e7a607fae366976884
train_000.jsonl
1438790400
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≤ i1 &lt; i2 &lt; i3 ≤ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.A geometric progression with common ratio k is a sequence of numbers of the form b·k0, b·k1, ..., b·kr - 1.Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.
256 megabytes
import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; public class MainC { MyScanner sc = new MyScanner(); Scanner sc2 = new Scanner(System.in); long start = System.currentTimeMillis(); long fin = System.currentTimeMillis(); final int MOD = 1000000007; int[] dx = { 1, 0, 0, -1 }; int[] dy = { 0, 1, -1, 0 }; void run() { int n = sc.nextInt(); long k = sc.nextLong(); long[] a = sc.nextLongArray(n); if (n <= 2) { System.out.println(0); return; } else if (k == 1) { HashMap<Long, Long> map = new HashMap<Long, Long>(); for (int i = 0; i < n; i++) { map.put(a[i], map.containsKey(a[i]) ? map.get(a[i]) + 1 : 1); } long cnt = 0; for (Long key : map.keySet()) { long val = map.get(key); if (val <= 2) { // none } else if (val == 3) { cnt++; } else { long ll = 1; ll *= val * (val - 1) * (val - 2); ll /= 6; cnt += ll; } } System.out.println(cnt); return; } long ans = 0; HashMap<Long, Long> one = new HashMap<Long, Long>(); HashMap<Long, Long> two = new HashMap<Long, Long>(); for (int i = 0; i < n; i++) { if (a[i] % k == 0 && two.containsKey(a[i] / k)) { ans += two.get(a[i] / k); } if (a[i] % k == 0 && one.containsKey(a[i] / k)) { if (two.containsKey(a[i])) { two.put(a[i], two.get(a[i]) + one.get(a[i] / k)); } else { two.put(a[i], one.get(a[i] / k)); } } if (one.containsKey(a[i])) { one.put(a[i], one.get(a[i]) + 1); } else { one.put(a[i], 1L); } } System.out.println(ans); } public static void main(String[] args) { new MainC().run(); } void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } void debug2(int[][] array) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { System.out.print(array[i][j]); } System.out.println(); } } boolean inner(int h, int w, int limH, int limW) { return 0 <= h && h < limH && 0 <= w && w < limW; } void swap(int[] x, int a, int b) { int tmp = x[a]; x[a] = x[b]; x[b] = tmp; } // find minimum i (a[i] >= border) int lower_bound(int a[], int border) { int l = -1; int r = a.length; while (r - l > 1) { int mid = (l + r) / 2; if (border <= a[mid]) { r = mid; } else { l = mid; } } // r = l + 1 return r; } boolean palindrome(String s) { for (int i = 0; i < s.length() / 2; i++) { if (s.charAt(i) != s.charAt(s.length() - 1 - i)) { return false; } } return true; } class MyScanner { int nextInt() { try { int c = System.in.read(); while (c != '-' && (c < '0' || '9' < c)) c = System.in.read(); if (c == '-') return -nextInt(); int res = 0; do { res *= 10; res += c - '0'; c = System.in.read(); } while ('0' <= c && c <= '9'); return res; } catch (Exception e) { return -1; } } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String next() { try { StringBuilder res = new StringBuilder(""); int c = System.in.read(); while (Character.isWhitespace(c)) c = System.in.read(); do { res.append((char) c); } while (!Character.isWhitespace(c = System.in.read())); return res.toString(); } catch (Exception e) { return null; } } int[] nextIntArray(int n) { int[] in = new int[n]; for (int i = 0; i < n; i++) { in[i] = nextInt(); } return in; } int[][] nextInt2dArray(int n, int m) { int[][] in = new int[n][m]; for (int i = 0; i < n; i++) { in[i] = nextIntArray(m); } return in; } double[] nextDoubleArray(int n) { double[] in = new double[n]; for (int i = 0; i < n; i++) { in[i] = nextDouble(); } return in; } long[] nextLongArray(int n) { long[] in = new long[n]; for (int i = 0; i < n; i++) { in[i] = nextLong(); } return in; } char[][] nextCharField(int n, int m) { char[][] in = new char[n][m]; for (int i = 0; i < n; i++) { String s = sc.next(); for (int j = 0; j < m; j++) { in[i][j] = s.charAt(j); } } return in; } } }
Java
["5 2\n1 1 2 2 4", "3 1\n1 1 1", "10 3\n1 2 6 2 3 6 9 18 3 9"]
1 second
["4", "1", "6"]
NoteIn the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
Java 7
standard input
[ "dp", "binary search", "data structures" ]
bd4b3bfa7511410c8e54658cc1dddb46
The first line of the input contains two integers, n and k (1 ≤ n, k ≤ 2·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — elements of the sequence.
1,700
Output a single number — the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.
standard output
PASSED
583533500590efaabcc673373278f973
train_000.jsonl
1438790400
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≤ i1 &lt; i2 &lt; i3 ≤ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.A geometric progression with common ratio k is a sequence of numbers of the form b·k0, b·k1, ..., b·kr - 1.Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.
256 megabytes
import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; public class Main { MyScanner sc = new MyScanner(); Scanner sc2 = new Scanner(System.in); long start = System.currentTimeMillis(); long fin = System.currentTimeMillis(); final int MOD = 1000000007; int[] dx = { 1, 0, 0, -1 }; int[] dy = { 0, 1, -1, 0 }; void run() { int n = sc.nextInt(); int k = sc.nextInt(); int[] a = sc.nextIntArray(n); HashMap<Integer, Long> one = new HashMap<Integer, Long>(); HashMap<Integer, Long> two = new HashMap<Integer, Long>(); long cnt = 0; for (int i = 0; i < n; i++) { if (a[i] % k == 0 && two.containsKey(a[i] / k)) { cnt += two.get(a[i] / k); } if (a[i] % k == 0 && one.containsKey(a[i] / k)) { long t = two.containsKey(a[i]) ? two.get(a[i]) : 0; two.put(a[i], t + one.get(a[i] / k)); } one.put(a[i], one.containsKey(a[i]) ? one.get(a[i]) + 1 : 1); } System.out.println(cnt); } public static void main(String[] args) { new Main().run(); } void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } void debug2(int[][] array) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { System.out.print(array[i][j]); } System.out.println(); } } boolean inner(int h, int w, int limH, int limW) { return 0 <= h && h < limH && 0 <= w && w < limW; } void swap(int[] x, int a, int b) { int tmp = x[a]; x[a] = x[b]; x[b] = tmp; } // find minimum i (a[i] >= border) int lower_bound(int a[], int border) { int l = -1; int r = a.length; while (r - l > 1) { int mid = (l + r) / 2; if (border <= a[mid]) { r = mid; } else { l = mid; } } // r = l + 1 return r; } boolean palindrome(String s) { for (int i = 0; i < s.length() / 2; i++) { if (s.charAt(i) != s.charAt(s.length() - 1 - i)) { return false; } } return true; } class MyScanner { int nextInt() { try { int c = System.in.read(); while (c != '-' && (c < '0' || '9' < c)) c = System.in.read(); if (c == '-') return -nextInt(); int res = 0; do { res *= 10; res += c - '0'; c = System.in.read(); } while ('0' <= c && c <= '9'); return res; } catch (Exception e) { return -1; } } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String next() { try { StringBuilder res = new StringBuilder(""); int c = System.in.read(); while (Character.isWhitespace(c)) c = System.in.read(); do { res.append((char) c); } while (!Character.isWhitespace(c = System.in.read())); return res.toString(); } catch (Exception e) { return null; } } int[] nextIntArray(int n) { int[] in = new int[n]; for (int i = 0; i < n; i++) { in[i] = nextInt(); } return in; } int[][] nextInt2dArray(int n, int m) { int[][] in = new int[n][m]; for (int i = 0; i < n; i++) { in[i] = nextIntArray(m); } return in; } double[] nextDoubleArray(int n) { double[] in = new double[n]; for (int i = 0; i < n; i++) { in[i] = nextDouble(); } return in; } long[] nextLongArray(int n) { long[] in = new long[n]; for (int i = 0; i < n; i++) { in[i] = nextLong(); } return in; } char[][] nextCharField(int n, int m) { char[][] in = new char[n][m]; for (int i = 0; i < n; i++) { String s = sc.next(); for (int j = 0; j < m; j++) { in[i][j] = s.charAt(j); } } return in; } } }
Java
["5 2\n1 1 2 2 4", "3 1\n1 1 1", "10 3\n1 2 6 2 3 6 9 18 3 9"]
1 second
["4", "1", "6"]
NoteIn the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
Java 7
standard input
[ "dp", "binary search", "data structures" ]
bd4b3bfa7511410c8e54658cc1dddb46
The first line of the input contains two integers, n and k (1 ≤ n, k ≤ 2·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — elements of the sequence.
1,700
Output a single number — the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.
standard output
PASSED
637eac36fbbcb633824d07000e7e7a2c
train_000.jsonl
1438790400
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≤ i1 &lt; i2 &lt; i3 ≤ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.A geometric progression with common ratio k is a sequence of numbers of the form b·k0, b·k1, ..., b·kr - 1.Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.
256 megabytes
import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; public class MainC { MyScanner sc = new MyScanner(); Scanner sc2 = new Scanner(System.in); long start = System.currentTimeMillis(); long fin = System.currentTimeMillis(); final int MOD = 1000000007; int[] dx = { 1, 0, 0, -1 }; int[] dy = { 0, 1, -1, 0 }; void run() { int n = sc.nextInt(); long k = sc.nextLong(); long[] a = sc.nextLongArray(n); long ans = 0; HashMap<Long, Long> one = new HashMap<Long, Long>(); HashMap<Long, Long> two = new HashMap<Long, Long>(); for (int i = 0; i < n; i++) { if (a[i] % k == 0 && two.containsKey(a[i] / k)) { ans += two.get(a[i] / k); } if (a[i] % k == 0 && one.containsKey(a[i] / k)) { two.put(a[i], two.containsKey(a[i]) ? two.get(a[i]) + one.get(a[i] / k) : one.get(a[i] / k)); } one.put(a[i], one.containsKey(a[i]) ? one.get(a[i]) + 1 : 1); } System.out.println(ans); } public static void main(String[] args) { new MainC().run(); } void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } void debug2(int[][] array) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { System.out.print(array[i][j]); } System.out.println(); } } boolean inner(int h, int w, int limH, int limW) { return 0 <= h && h < limH && 0 <= w && w < limW; } void swap(int[] x, int a, int b) { int tmp = x[a]; x[a] = x[b]; x[b] = tmp; } // find minimum i (a[i] >= border) int lower_bound(int a[], int border) { int l = -1; int r = a.length; while (r - l > 1) { int mid = (l + r) / 2; if (border <= a[mid]) { r = mid; } else { l = mid; } } // r = l + 1 return r; } boolean palindrome(String s) { for (int i = 0; i < s.length() / 2; i++) { if (s.charAt(i) != s.charAt(s.length() - 1 - i)) { return false; } } return true; } class MyScanner { int nextInt() { try { int c = System.in.read(); while (c != '-' && (c < '0' || '9' < c)) c = System.in.read(); if (c == '-') return -nextInt(); int res = 0; do { res *= 10; res += c - '0'; c = System.in.read(); } while ('0' <= c && c <= '9'); return res; } catch (Exception e) { return -1; } } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String next() { try { StringBuilder res = new StringBuilder(""); int c = System.in.read(); while (Character.isWhitespace(c)) c = System.in.read(); do { res.append((char) c); } while (!Character.isWhitespace(c = System.in.read())); return res.toString(); } catch (Exception e) { return null; } } int[] nextIntArray(int n) { int[] in = new int[n]; for (int i = 0; i < n; i++) { in[i] = nextInt(); } return in; } int[][] nextInt2dArray(int n, int m) { int[][] in = new int[n][m]; for (int i = 0; i < n; i++) { in[i] = nextIntArray(m); } return in; } double[] nextDoubleArray(int n) { double[] in = new double[n]; for (int i = 0; i < n; i++) { in[i] = nextDouble(); } return in; } long[] nextLongArray(int n) { long[] in = new long[n]; for (int i = 0; i < n; i++) { in[i] = nextLong(); } return in; } char[][] nextCharField(int n, int m) { char[][] in = new char[n][m]; for (int i = 0; i < n; i++) { String s = sc.next(); for (int j = 0; j < m; j++) { in[i][j] = s.charAt(j); } } return in; } } }
Java
["5 2\n1 1 2 2 4", "3 1\n1 1 1", "10 3\n1 2 6 2 3 6 9 18 3 9"]
1 second
["4", "1", "6"]
NoteIn the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
Java 7
standard input
[ "dp", "binary search", "data structures" ]
bd4b3bfa7511410c8e54658cc1dddb46
The first line of the input contains two integers, n and k (1 ≤ n, k ≤ 2·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — elements of the sequence.
1,700
Output a single number — the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.
standard output
PASSED
14f70ce691b8181805b11cfe5c399d5d
train_000.jsonl
1438790400
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≤ i1 &lt; i2 &lt; i3 ≤ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.A geometric progression with common ratio k is a sequence of numbers of the form b·k0, b·k1, ..., b·kr - 1.Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.
256 megabytes
import java.io.File; import java.io.FileNotFoundException; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Hashtable; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Scanner; import java.util.SortedMap; import java.util.Stack; import java.util.TreeMap; import java.util.Vector; public class Main { static long count; public static void main(String[] args) throws FileNotFoundException { //Scanner sc = new Scanner (new File("in.in")); Scanner sc = new Scanner (System.in); int n = sc.nextInt(); int k = sc.nextInt(); long []tab = new long [n]; Map<Long, Long> r = new HashMap<Long,Long>(); Map<Long, Long> l = new HashMap<Long,Long>(); for(int i=0;i<n;i++){ tab[i]=sc.nextLong(); if(r.get(tab[i])==null) r.put(tab[i], (long)1); else r.put(tab[i], r.get(tab[i])+1); } long s=0,xr,xl; for(int i=0;i<n;i++){ if(tab[i]%k==0){ xl = l.get(tab[i]/k)==null?0:l.get(tab[i]/k) ; } else xl=0; r.put(tab[i], r.get(tab[i])-1); xr = r.get(tab[i]*k)==null?0:r.get(tab[i]*k) ; s+=xl*xr; if(l.get(tab[i])==null) l.put(tab[i], (long)1); else l.put(tab[i], l.get(tab[i])+1); } System.out.println(s); } }
Java
["5 2\n1 1 2 2 4", "3 1\n1 1 1", "10 3\n1 2 6 2 3 6 9 18 3 9"]
1 second
["4", "1", "6"]
NoteIn the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
Java 7
standard input
[ "dp", "binary search", "data structures" ]
bd4b3bfa7511410c8e54658cc1dddb46
The first line of the input contains two integers, n and k (1 ≤ n, k ≤ 2·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — elements of the sequence.
1,700
Output a single number — the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.
standard output
PASSED
21059ddad2c1a35f93078f652a25c027
train_000.jsonl
1438790400
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≤ i1 &lt; i2 &lt; i3 ≤ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.A geometric progression with common ratio k is a sequence of numbers of the form b·k0, b·k1, ..., b·kr - 1.Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.HashMap; /** * @author: Ashok Rajpurohit * problem: Geometric Progression * Link: http://codeforces.com/contest/567/problem/C */ public class CPiC { private static PrintWriter out; private static InputStream in; public static void main(String[] args) throws IOException { OutputStream outputStream = System.out; in = System.in; out = new PrintWriter(outputStream); CPiC a = new CPiC(); a.solve(); out.close(); } public void solve() throws IOException { InputReader in = new InputReader(); int n = in.readInt(); out.println(process(in.readInt(), in.readLongArray(n))); } private static long countGP(int k, long[] ar) { if (ar.length < 3) return 0; long res = 0; HashMap<Long, Integer> left = new HashMap<Long, Integer>(ar.length); HashMap<Long, Integer> right = new HashMap<Long, Integer>(ar.length); for (int i = 0; i < ar.length; i++) { left.put(ar[i], 0); right.put(ar[i], 0); } // let's populate left. left.put(ar[0], 1); // let's populate right. for (int i = 2; i < ar.length; i++) right.put(ar[i], right.get(ar[i]) + 1); for (int i = 1; i < ar.length - 1; i++) { if (ar[i] % k == 0) { if (left.containsKey(ar[i] / k) && right.containsKey(ar[i] * k)) res += 1L * left.get(ar[i] / k) * right.get(ar[i] * k); } int value = left.get(ar[i]); left.put(ar[i], value + 1); value = right.get(ar[i + 1]); right.put(ar[i + 1], value - 1); } return res; } private static long process(int k, long[] ar) { if (ar.length < 3) return 0; if (k == 1) return getThree(ar); int pos_count = 0; // count of positive numbers int neg_count = 0; // count of negative numbers for (int i = 0; i < ar.length; i++) if (ar[i] > 0) pos_count++; for (int i = 0; i < ar.length; i++) if (ar[i] < 0) neg_count++; long[] pos_ar = new long[pos_count]; for (int i = 0, j = 0; i < ar.length && j < pos_count; i++) if (ar[i] > 0) { pos_ar[j] = ar[i]; j++; } long[] neg_ar = new long[neg_count]; for (int i = 0, j = 0; i < ar.length && j < neg_count; i++) if (ar[i] < 0) { neg_ar[j] = -ar[i]; j++; } long res = 0, zero_count = ar.length - pos_count - neg_count; if (zero_count > 2) res = zero_count * (zero_count - 1) * (zero_count - 2) / 6; res += countGP(k, pos_ar) + countGP(k, neg_ar); return res; } private static long getThree(long[] ar) { sort(ar); int i = 0; long res = 0; while (i < ar.length) { int count = 0; int j = i; while (j < ar.length && ar[j] == ar[i]) { j++; count++; } if (count > 2) res += (1L * count * (count - 1) * (count - 2) / 6); i = j; } return res; } private static void sort(long[] a) { long[] b = new long[a.length]; sort(a, b, 0, a.length - 1); } private static void sort(long[] a, long[] b, int begin, int end) { if (begin == end) { return; } int mid = (begin + end) / 2; sort(a, b, begin, mid); sort(a, b, mid + 1, end); merge(a, b, begin, end); } private static void merge(long[] a, long[] b, int begin, int end) { int mid = (begin + end) / 2; int i = begin; int j = mid + 1; int k = begin; while (i <= mid && j <= end) { if (a[i] > a[j]) { b[k] = a[j]; j++; } else { b[k] = a[i]; i++; } k++; } if (j <= end) { while (j <= end) { b[k] = a[j]; k++; j++; } } if (i <= mid) { while (i <= mid) { b[k] = a[i]; i++; k++; } } i = begin; while (i <= end) { a[i] = b[i]; i++; } } final static class InputReader { byte[] buffer = new byte[8192]; int offset = 0; int bufferSize = 0; public int readInt() throws IOException { int number = 0; int s = 1; if (offset == bufferSize) { offset = 0; bufferSize = in.read(buffer); } if (bufferSize == -1) throw new IOException("No new bytes"); for (; buffer[offset] < 0x30 || buffer[offset] == '-'; ++offset) { if (buffer[offset] == '-') s = -1; if (offset == bufferSize - 1) { offset = -1; bufferSize = in.read(buffer); } } for (; offset < bufferSize && buffer[offset] > 0x2f; ++offset) { number = (number << 3) + (number << 1) + buffer[offset] - 0x30; if (offset == bufferSize - 1) { offset = -1; bufferSize = in.read(buffer); } } ++offset; return number * s; } public int[] readIntArray(int n) throws IOException { int[] ar = new int[n]; for (int i = 0; i < n; i++) ar[i] = readInt(); return ar; } public long readLong() throws IOException { long res = 0; int s = 1; if (offset == bufferSize) { offset = 0; bufferSize = in.read(buffer); } for (; buffer[offset] < 0x30 || buffer[offset] == '-'; ++offset) { if (buffer[offset] == '-') s = -1; if (offset == bufferSize - 1) { offset = -1; bufferSize = in.read(buffer); } } for (; offset < bufferSize && buffer[offset] > 0x2f; ++offset) { res = (res << 3) + (res << 1) + buffer[offset] - 0x30; if (offset == bufferSize - 1) { offset = -1; bufferSize = in.read(buffer); } } ++offset; if (s == -1) res = -res; return res; } public long[] readLongArray(int n) throws IOException { long[] ar = new long[n]; for (int i = 0; i < n; i++) ar[i] = readLong(); return ar; } } }
Java
["5 2\n1 1 2 2 4", "3 1\n1 1 1", "10 3\n1 2 6 2 3 6 9 18 3 9"]
1 second
["4", "1", "6"]
NoteIn the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
Java 7
standard input
[ "dp", "binary search", "data structures" ]
bd4b3bfa7511410c8e54658cc1dddb46
The first line of the input contains two integers, n and k (1 ≤ n, k ≤ 2·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — elements of the sequence.
1,700
Output a single number — the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.
standard output
PASSED
6b93311c394d26cd3aee5dc255523026
train_000.jsonl
1438790400
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≤ i1 &lt; i2 &lt; i3 ≤ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.A geometric progression with common ratio k is a sequence of numbers of the form b·k0, b·k1, ..., b·kr - 1.Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.HashMap; /** * @author: Ashok Rajpurohit * problem: Geometric Progression * Link: http://codeforces.com/contest/567/problem/C */ public class CPiC { private static PrintWriter out; private static InputStream in; public static void main(String[] args) throws IOException { OutputStream outputStream = System.out; in = System.in; out = new PrintWriter(outputStream); CPiC a = new CPiC(); a.solve(); out.close(); } public void solve() throws IOException { InputReader in = new InputReader(); int n = in.readInt(); out.println(process(in.readInt(), in.readLongArray(n))); } private static long countGP(int k, long[] ar) { if (ar.length < 3) return 0; long res = 0; HashMap<Long, Integer> left = new HashMap<Long, Integer>(ar.length); HashMap<Long, Integer> right = new HashMap<Long, Integer>(ar.length); for (int i = 0; i < ar.length; i++) { left.put(ar[i], 0); right.put(ar[i], 0); } // let's populate left. left.put(ar[0], 1); // let's populate right. for (int i = 2; i < ar.length; i++) right.put(ar[i], right.get(ar[i]) + 1); for (int i = 1; i < ar.length - 1; i++) { if (ar[i] % k == 0) { if (left.containsKey(ar[i] / k) && right.containsKey(ar[i] * k)) res += 1L * left.get(ar[i] / k) * right.get(ar[i] * k); } int value = left.get(ar[i]); left.put(ar[i], value + 1); value = right.get(ar[i + 1]); right.put(ar[i + 1], value - 1); } return res; } private static long process(int k, long[] ar) { if (ar.length < 3) return 0; if (k == 1) return getThree(ar); int pos_count = 0; // count of positive numbers int neg_count = 0; // count of negative numbers for (int i = 0; i < ar.length; i++) if (ar[i] > 0) pos_count++; for (int i = 0; i < ar.length; i++) if (ar[i] < 0) neg_count++; long[] pos_ar = new long[pos_count]; for (int i = 0, j = 0; i < ar.length && j < pos_count; i++) if (ar[i] > 0) { pos_ar[j] = ar[i]; j++; } long[] neg_ar = new long[neg_count]; for (int i = 0, j = 0; i < ar.length && j < neg_count; i++) if (ar[i] < 0) { neg_ar[j] = -ar[i]; j++; } long res = 0, zero_count = ar.length - pos_count - neg_count; if (zero_count > 2) res = zero_count * (zero_count - 1) * (zero_count - 2) / 6; res += countGP(k, pos_ar) + countGP(k, neg_ar); return res; } private static long getThree(long[] ar) { sort(ar); int i = 0; long res = 0; while (i < ar.length) { int count = 0; int j = i; while (j < ar.length && ar[j] == ar[i]) { j++; count++; } if (count > 2) res += (1L * count * (count - 1) * (count - 2) / 6); i = j; } return res; } private static int compute(int k, int[] ar) { if (ar.length < 3) return 0; int res = 0; int[] sort = sortIndex(ar); int max_start = ar[sort[ar.length - 1]] / (k * k); if (ar[sort[0]] * k * k > ar[sort[ar.length - 1]]) return 0; for (int i = 0; ar[sort[i]] <= max_start; i++) { int two = find(ar[sort[i]] * k, ar, sort); int three = find(ar[sort[i]] * k * k, ar, sort); if (two != -1 && three != -1) { for (int j = two; j < ar.length && ar[sort[j]] == ar[sort[two]]; j++) { if (sort[j] > sort[i]) { for (int m = three; m < ar.length && ar[sort[m]] == ar[sort[three]]; m++) { if (sort[m] > sort[j]) res++; } } } } } return res; } private static int find(int value, int[] ar, int[] sort) { int start = 0, end = ar.length - 1, mid = (start + end) >>> 1; if (ar[sort[0]] == value) return 0; while (start < mid) { if (ar[sort[mid]] < value) start = mid; else end = mid; mid = (start + end) >>> 1; } if (ar[sort[end]] != value) return -1; // while (end > mid && ar[sort[end]] == value) end--; return end + 1; } private static void sort(long[] a) { long[] b = new long[a.length]; sort(a, b, 0, a.length - 1); } private static void sort(long[] a, long[] b, int begin, int end) { if (begin == end) { return; } int mid = (begin + end) / 2; sort(a, b, begin, mid); sort(a, b, mid + 1, end); merge(a, b, begin, end); } private static void merge(long[] a, long[] b, int begin, int end) { int mid = (begin + end) / 2; int i = begin; int j = mid + 1; int k = begin; while (i <= mid && j <= end) { if (a[i] > a[j]) { b[k] = a[j]; j++; } else { b[k] = a[i]; i++; } k++; } if (j <= end) { while (j <= end) { b[k] = a[j]; k++; j++; } } if (i <= mid) { while (i <= mid) { b[k] = a[i]; i++; k++; } } i = begin; while (i <= end) { a[i] = b[i]; i++; } } public static int[] sortIndex(int[] a) { int[] b = new int[a.length]; int[] c = new int[a.length]; for (int i = 0; i < a.length; i++) { c[i] = i; } sort(a, b, c, 0, a.length - 1); return c; } private static void sort(int[] a, int[] b, int[] c, int begin, int end) { if (begin == end) { return; } int mid = (begin + end) / 2; sort(a, b, c, begin, mid); sort(a, b, c, mid + 1, end); merge(a, b, c, begin, end); } public static void merge(int[] a, int[] b, int[] c, int begin, int end) { int mid = (begin + end) / 2; int i = begin; int j = mid + 1; int k = begin; while (i <= mid && j <= end) { if (a[c[i]] > a[c[j]]) { b[k] = c[j]; j++; } else { b[k] = c[i]; i++; } k++; } if (j <= end) { while (j <= end) { b[k] = c[j]; k++; j++; } } if (i <= mid) { while (i <= mid) { b[k] = c[i]; i++; k++; } } i = begin; while (i <= end) { c[i] = b[i]; i++; } } final static class InputReader { byte[] buffer = new byte[8192]; int offset = 0; int bufferSize = 0; public int readInt() throws IOException { int number = 0; int s = 1; if (offset == bufferSize) { offset = 0; bufferSize = in.read(buffer); } if (bufferSize == -1) throw new IOException("No new bytes"); for (; buffer[offset] < 0x30 || buffer[offset] == '-'; ++offset) { if (buffer[offset] == '-') s = -1; if (offset == bufferSize - 1) { offset = -1; bufferSize = in.read(buffer); } } for (; offset < bufferSize && buffer[offset] > 0x2f; ++offset) { number = (number << 3) + (number << 1) + buffer[offset] - 0x30; if (offset == bufferSize - 1) { offset = -1; bufferSize = in.read(buffer); } } ++offset; return number * s; } public int[] readIntArray(int n) throws IOException { int[] ar = new int[n]; for (int i = 0; i < n; i++) ar[i] = readInt(); return ar; } public long readLong() throws IOException { long res = 0; int s = 1; if (offset == bufferSize) { offset = 0; bufferSize = in.read(buffer); } for (; buffer[offset] < 0x30 || buffer[offset] == '-'; ++offset) { if (buffer[offset] == '-') s = -1; if (offset == bufferSize - 1) { offset = -1; bufferSize = in.read(buffer); } } for (; offset < bufferSize && buffer[offset] > 0x2f; ++offset) { res = (res << 3) + (res << 1) + buffer[offset] - 0x30; if (offset == bufferSize - 1) { offset = -1; bufferSize = in.read(buffer); } } ++offset; if (s == -1) res = -res; return res; } public long[] readLongArray(int n) throws IOException { long[] ar = new long[n]; for (int i = 0; i < n; i++) ar[i] = readLong(); return ar; } } }
Java
["5 2\n1 1 2 2 4", "3 1\n1 1 1", "10 3\n1 2 6 2 3 6 9 18 3 9"]
1 second
["4", "1", "6"]
NoteIn the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
Java 7
standard input
[ "dp", "binary search", "data structures" ]
bd4b3bfa7511410c8e54658cc1dddb46
The first line of the input contains two integers, n and k (1 ≤ n, k ≤ 2·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — elements of the sequence.
1,700
Output a single number — the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.
standard output
PASSED
0a9b9d342c7a0b95daffdf0c89b3f20b
train_000.jsonl
1438790400
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≤ i1 &lt; i2 &lt; i3 ≤ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.A geometric progression with common ratio k is a sequence of numbers of the form b·k0, b·k1, ..., b·kr - 1.Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.
256 megabytes
import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.*; public class Main { public static void solve() { int n = IO.readInt(); int k = IO.readInt(); Map<Integer, Long> s = new HashMap<Integer, Long>(); Map<Integer, Long> p = new HashMap<Integer, Long>(); long result = 0; while (n-- > 0) { int a = IO.readInt(); Long sn; if (a % k == 0) { Long pn = p.get(a / k); if (pn != null) { result += pn; } sn = s.get(a / k); if (sn != null) { pn = p.get(a); if (pn == null) { pn = 0l; } p.put(a, pn + sn); } } sn = s.get(a); if (sn == null) { sn = 0l; } s.put(a, sn + 1); } IO.println(result); } // Input/Output ================================ public static class IO { private static Scanner scanner; private static PrintWriter writer; public static void setUp(InputStream in, OutputStream out) { scanner = new Scanner(new java.io.BufferedInputStream(in)); writer = new PrintWriter(out); } public static boolean isEmpty() { return !scanner.hasNext(); } public static boolean hasNextLine() { return scanner.hasNextLine(); } public static String readLine() { String line; try { line = scanner.nextLine(); } catch (Exception e) { line = null; } return line; } public static String readString() { return scanner.next(); } public static int readInt() { return scanner.nextInt(); } public static double readDouble() { return scanner.nextDouble(); } public static float readFloat() { return scanner.nextFloat(); } public static long readLong() { return scanner.nextLong(); } public static char readChar() { return scanner.findInLine("[^\\s]").charAt(0); } public static void print(Object o) { writer.print(o); writer.flush(); } public static void println(Object o) { writer.println(o); writer.flush(); } } // Algorithms ================================ private static class Algo { private static int binSearch(int[] array, int n, int lo, int hi) { if (lo > hi) { return lo; } int mid = lo + (hi - lo) / 2; int cmp = (int) java.lang.Math.signum(n - array[mid]); if (cmp < 0) { return binSearch(array, n, lo, mid - 1); } else if (cmp == 0) { return mid; } else { return binSearch(array, n, mid + 1, hi); } } private static void permutations(int n) { int[] p = new int[n]; for (int index = 0; index < n; ++index) { p[index] = index + 1; } while (true) { IO.println(Arrays.toString(p)); int k = n - 1; while (k > 0) { if (p[k] < p[k - 1]) { k--; } else { break; } } if (k == 0) { break; } int j = n - 1; while (p[j] < p[k - 1]) { j--; } int t = p[j]; p[j] = p[k - 1]; p[k - 1] = t; int i = 0; while (k + i < n - 1 - i) { t = p[k + i]; p[k + i] = p[n - i - 1]; p[n - i - 1] = t; i++; } } } private static final boolean isPrime(int number) { if (number <= 1) { return false; } if (number <= 3) { return true; } if (number % 2 == 0 || number % 3 == 0) { return false; } int i = 5; while (i * i <= number) { if (number % i == 0 || number % (i + 2) == 0) { return false; } i += 6; } return true; } private static boolean isPalindrome(int number) { int n = number; int reverse = 0; while (n > 0) { reverse *= 10; reverse += (n % 10); n /= 10; } return reverse == number; } public static int gcd(int a,int b) { while (b != 0) { int tmp = a % b; a = b; b = tmp; } return a; } } private static class Math { static long c(int n, int k) { int d = 1000; int l = 1000000007; long[][] c = new long[d + 1][d + 1]; for (int i = 1; i <= d; ++i) { for (int j = 0; j <= i; ++j) { if (i == j || j == 0) { c[i][j] = 1; } else { c[i][j] = (c[i - 1][j - 1] + c[i - 1][j]) % l; } } } return c[n][k]; } } public static void main(String[] args) { IO.setUp(System.in, System.out); /* try { IO.setUp(new FileInputStream("encode.in"), new FileOutputStream("encode.out")); } catch (FileNotFoundException e) { e.printStackTrace(); return; } */ solve(); } }
Java
["5 2\n1 1 2 2 4", "3 1\n1 1 1", "10 3\n1 2 6 2 3 6 9 18 3 9"]
1 second
["4", "1", "6"]
NoteIn the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
Java 7
standard input
[ "dp", "binary search", "data structures" ]
bd4b3bfa7511410c8e54658cc1dddb46
The first line of the input contains two integers, n and k (1 ≤ n, k ≤ 2·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — elements of the sequence.
1,700
Output a single number — the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.
standard output
PASSED
d3cb460b388c8c6efcb600fc87b3a19c
train_000.jsonl
1438790400
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≤ i1 &lt; i2 &lt; i3 ≤ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.A geometric progression with common ratio k is a sequence of numbers of the form b·k0, b·k1, ..., b·kr - 1.Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.
256 megabytes
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub int n, k; long ans = 0; Map <Long, Long> l = new HashMap<Long, Long> (); Map <Long, Long> r = new HashMap<Long, Long> (); long [] arr = new long[200005]; Scanner sc = new Scanner (System.in); n = sc.nextInt(); k = sc.nextInt(); for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); if (l.containsKey(arr[i])) { long x = l.get(arr[i]); x++; l.put(arr[i], x); } else { l.put(arr[i], 1L); } } for (int i = 0; i < n; i++) { long a = 0, b = 0, j = 0; if (arr[i]%k == 0) { if (r.containsKey(arr[i]/k)) { a = r.get(arr[i]/k); } if (r.containsKey(arr[i])) { r.put(arr[i], r.get(arr[i])+1); } else { r.put(arr[i], 1L); } l.put(arr[i], l.get(arr[i])-1); if (l.containsKey(arr[i]*k)) { b = l.get(arr[i]*k); } ans += a*b; } else { if (r.containsKey(arr[i])) { r.put(arr[i], r.get(arr[i])+1); } else { r.put(arr[i], 1L); } if(l.containsKey(arr[i])) { l.put(arr[i], l.get(arr[i])-1); } } } System.out.println(ans); } }
Java
["5 2\n1 1 2 2 4", "3 1\n1 1 1", "10 3\n1 2 6 2 3 6 9 18 3 9"]
1 second
["4", "1", "6"]
NoteIn the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
Java 7
standard input
[ "dp", "binary search", "data structures" ]
bd4b3bfa7511410c8e54658cc1dddb46
The first line of the input contains two integers, n and k (1 ≤ n, k ≤ 2·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — elements of the sequence.
1,700
Output a single number — the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.
standard output
PASSED
11a76f2c282e72457530558e88a5c9b5
train_000.jsonl
1438790400
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≤ i1 &lt; i2 &lt; i3 ≤ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.A geometric progression with common ratio k is a sequence of numbers of the form b·k0, b·k1, ..., b·kr - 1.Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.
256 megabytes
import java.io.*; import java.io.PrintWriter; import java.util.*; import java.io.InputStream; import java.io.DataInputStream; public class Main {//static{ System.out.println("hello");} public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader scn = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); HashMap<Long,ArrayList<Integer>> hm=new HashMap<Long,ArrayList<Integer>>(); int n=scn.ni(); int k=scn.ni(); int a[]=new int[n]; int cnt=0; for (int i=0; i<n; i++) { a[i]=scn.ni(); if (hm.containsKey(a[i]*1l)) { hm.get(a[i]*1l).add(i); } else { hm.put(a[i]*1l,new ArrayList<Integer>() ); hm.get(a[i]*1l).add(i); } } long ans=0l; for (int i=0; i<n; i++) {long idx1=0; if (hm.containsKey(a[i]*1l*k)) { idx1=Collections.binarySearch(hm.get(a[i]*1l*k),i); // System.out.println(idx1+"hi"+i); if (idx1<0){ idx1=-idx1-1; idx1=hm.get(a[i]*1l*k).size()-idx1; } else { idx1=hm.get(a[i]*1l).size()-1-idx1; } } long idx2=0; if (a[i]%k==0 && hm.containsKey(1l*a[i]/k)) { idx2=Collections.binarySearch(hm.get(1l*a[i]/k),i); if (idx2<0){ idx2=-idx2-1; } else { idx2=Math.max(idx2,0);} } // out.println(idx1+" "+idx2); ans+=(idx1*idx2); } out.println(ans); out.close(); } } class num implements Comparator<num> { public int ff; public int ss; num() { } num(int x,int y) { this.ff = x; this.ss =y; } public int getff() { return ff; } public int getss() { return ss; } public boolean equals(Object n1) {num n=(num)n1; if (this.ff==n.ff && this.ss==n.ss) return true; else return false; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ff; result = prime * result+ss; return result; } public int compare(num o1, num o2) { if (o1.ff!=o2.ff) return o1.ff-o2.ff; else return o1.ss-o2.ss; } } class FastReader { public InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public FastReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException (); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read (buf); } catch (IOException e) { throw new InputMismatchException (); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public char nc() { int c = read (); while (isSpaceChar (c)) c = read (); return (char) c; } public int ni() { 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') { } res *= 10; res += c - '0'; c = read (); } while (!isSpaceChar (c)); return res * sgn; } public long nl() { int c = read (); while (isSpaceChar (c)) c = read (); int sgn = 1; if (c == '-') { sgn = -1; c = read (); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException (); } res *= 10; res += c - '0'; c = read (); } while (!isSpaceChar (c)); return res * sgn; } public String ns() { int c = read (); while (isSpaceChar (c)) c = read (); StringBuilder res = new StringBuilder (); do { res.appendCodePoint (c); c = read (); } while (!isSpaceChar (c)); return res.toString (); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar (c); } return isWhitespace (c); } public static boolean isWhitespace(int c) { return c==' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return ns (); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["5 2\n1 1 2 2 4", "3 1\n1 1 1", "10 3\n1 2 6 2 3 6 9 18 3 9"]
1 second
["4", "1", "6"]
NoteIn the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
Java 7
standard input
[ "dp", "binary search", "data structures" ]
bd4b3bfa7511410c8e54658cc1dddb46
The first line of the input contains two integers, n and k (1 ≤ n, k ≤ 2·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — elements of the sequence.
1,700
Output a single number — the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.
standard output
PASSED
3871439b2236713b69874d9171daf76c
train_000.jsonl
1438790400
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≤ i1 &lt; i2 &lt; i3 ≤ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.A geometric progression with common ratio k is a sequence of numbers of the form b·k0, b·k1, ..., b·kr - 1.Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.
256 megabytes
import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Hashtable; import java.util.InputMismatchException; import java.util.PriorityQueue; import java.util.Scanner; import java.util.TreeSet; public class Solution { public static void main(String args[]) { FasterScanner s=new FasterScanner (); int n=s.nextInt(); int k=s.nextInt(); long a[]=s.nextLongArray(n); long ans=0; Hashtable<Long, Long> hash=new Hashtable<>(); if(k==1) { for(int i=n-1;i>=0;i--) { if(hash.containsKey(a[i])) hash.put(a[i],hash.get(a[i])+1); else hash.put(a[i], 1l); } for(Long key:hash.keySet()) { long x=hash.get(key); ans+=x*(x-1)*(x-2)/3/2; } System.out.println(ans); return; } Hashtable<Long,Long> count=new Hashtable<>(); for(int i=n-1;i>=0;i--) { if(count.containsKey(a[i]*k)) ans+=count.get(a[i]*k); if(hash.containsKey(a[i]*k)) { if(count.containsKey(a[i])) count.put(a[i], count.get(a[i])+hash.get(a[i]*k)); else count.put(a[i], hash.get(a[i]*k)); } if(hash.containsKey(a[i])) hash.put(a[i],hash.get(a[i])+1); else hash.put(a[i], 1l); } System.out.println(ans); } static class Node implements Comparable<Node> { char c; int d; int x; int y; @Override public int compareTo(Node o) { if(d>o.d) return 1; if(d<o.d) return -1; if(x>o.x) return 1; if(x<o.x) return -1; if(y>o.y) return 1; if(y<o.y) return -1; return 0; } } public static class FasterScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { 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; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["5 2\n1 1 2 2 4", "3 1\n1 1 1", "10 3\n1 2 6 2 3 6 9 18 3 9"]
1 second
["4", "1", "6"]
NoteIn the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
Java 7
standard input
[ "dp", "binary search", "data structures" ]
bd4b3bfa7511410c8e54658cc1dddb46
The first line of the input contains two integers, n and k (1 ≤ n, k ≤ 2·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — elements of the sequence.
1,700
Output a single number — the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.
standard output
PASSED
c67117d843e364edb0b3d35522778929
train_000.jsonl
1438790400
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≤ i1 &lt; i2 &lt; i3 ≤ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.A geometric progression with common ratio k is a sequence of numbers of the form b·k0, b·k1, ..., b·kr - 1.Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.Map; import java.util.HashMap; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Hieu Le */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int k = in.nextInt(); Map<Integer, TaskC.Ways> map = new HashMap<Integer, TaskC.Ways>(); long cnt = 0; for (int i = 0; i < n; i++) { int cur = in.nextInt(); long two = 0; if (cur % k == 0 && map.containsKey(cur / k)) { two = map.get(cur / k).one; cnt += map.get(cur / k).two; } if (!map.containsKey(cur)) map.put(cur, new TaskC.Ways()); map.get(cur).one = map.get(cur).one + 1; map.get(cur).two = map.get(cur).two + two; } out.println(cnt); } private static class Ways { long one; long two; } } 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()); } } }
Java
["5 2\n1 1 2 2 4", "3 1\n1 1 1", "10 3\n1 2 6 2 3 6 9 18 3 9"]
1 second
["4", "1", "6"]
NoteIn the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
Java 7
standard input
[ "dp", "binary search", "data structures" ]
bd4b3bfa7511410c8e54658cc1dddb46
The first line of the input contains two integers, n and k (1 ≤ n, k ≤ 2·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — elements of the sequence.
1,700
Output a single number — the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.
standard output
PASSED
86b55afbbd9c71e3efa130395b91de61
train_000.jsonl
1438790400
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≤ i1 &lt; i2 &lt; i3 ≤ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.A geometric progression with common ratio k is a sequence of numbers of the form b·k0, b·k1, ..., b·kr - 1.Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.StringTokenizer; public class Main { public static void main(String [] args) throws IOException{ BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tkn = new StringTokenizer(input.readLine()); int N = Integer.parseInt(tkn.nextToken()); int K = Integer.parseInt(tkn.nextToken()); long answer = 0; HashMap<Long,Long> firstLayer = new HashMap<Long,Long>(); HashMap<Long,Long> secondLayer = new HashMap<Long,Long>(); tkn = new StringTokenizer(input.readLine()); for(int i=0;i<N;i++) { long rakam = Long.parseLong(tkn.nextToken()); if(secondLayer.containsKey(rakam)) answer+= secondLayer.get(rakam); if(firstLayer.containsKey(rakam)){ if(secondLayer.containsKey(rakam*K)) secondLayer.put(rakam*K, secondLayer.get(rakam*K)+firstLayer.get(rakam)); else secondLayer.put(rakam*K, firstLayer.get(rakam)); } if(firstLayer.containsKey(rakam*K)) firstLayer.put(rakam*K, firstLayer.get(rakam*K)+1); else firstLayer.put(rakam*K,(long) 1); } System.out.println(answer); } }
Java
["5 2\n1 1 2 2 4", "3 1\n1 1 1", "10 3\n1 2 6 2 3 6 9 18 3 9"]
1 second
["4", "1", "6"]
NoteIn the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
Java 7
standard input
[ "dp", "binary search", "data structures" ]
bd4b3bfa7511410c8e54658cc1dddb46
The first line of the input contains two integers, n and k (1 ≤ n, k ≤ 2·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — elements of the sequence.
1,700
Output a single number — the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.
standard output
PASSED
77e11aae933f5a22afcbd7474cdf40f4
train_000.jsonl
1438790400
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≤ i1 &lt; i2 &lt; i3 ≤ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.A geometric progression with common ratio k is a sequence of numbers of the form b·k0, b·k1, ..., b·kr - 1.Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.
256 megabytes
import java.util.*; import java.util.Map.Entry; import java.io.*; import java.lang.*; import java.math.*; import static java.lang.Math.*; public class Solution implements Runnable { void solve() throws Exception { int n = sc.nextInt(); int k = sc.nextInt(); HashMap<Integer, Long>[] cnt = new HashMap[3]; for (int i = 0; i < 3; i++) { cnt[i] = new HashMap<Integer, Long>(); } long ans = 0; for (int i = 0; i < n; i++) { int x = sc.nextInt(); for (int j = 0; j < 3; j++) { if (!cnt[j].containsKey(x)) cnt[j].put(x, 0L); } if (x % k == 0) { int y = x / k; if (cnt[1].containsKey(y)) { cnt[2].put(x, cnt[2].get(x) + cnt[1].get(y)); } if (cnt[0].containsKey(y)) { cnt[1].put(x, cnt[1].get(x) + cnt[0].get(y)); } } cnt[0].put(x, cnt[0].get(x) + 1); } for (Entry<Integer, Long> x : cnt[2].entrySet()) { ans += x.getValue(); } out.println(ans); } BufferedReader in; PrintWriter out; FastScanner sc; final String INPUT_FILE = "stdin"; final String OUTPUT_FILE = "stdout"; static Throwable throwable; public static void main(String[] args) throws Throwable { Thread thread = new Thread(null, new Solution(), "", (1 << 26)); thread.start(); thread.join(); thread.run(); if (throwable != null) throw throwable; } public void run() { try { if (INPUT_FILE.equals("stdin")) in = new BufferedReader(new InputStreamReader(System.in)); else in = new BufferedReader(new FileReader(INPUT_FILE)); if (OUTPUT_FILE.equals("stdout")) out = new PrintWriter(System.out); else out = new PrintWriter(new FileWriter(OUTPUT_FILE)); sc = new FastScanner(in); solve(); } catch (Exception e) { throwable = e; } finally { out.close(); } } } class FastScanner { BufferedReader reader; StringTokenizer strTok; FastScanner(BufferedReader reader) { this.reader = reader; } public String nextToken() throws Exception { while (strTok == null || !strTok.hasMoreTokens()) strTok = new StringTokenizer(reader.readLine()); return strTok.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
Java
["5 2\n1 1 2 2 4", "3 1\n1 1 1", "10 3\n1 2 6 2 3 6 9 18 3 9"]
1 second
["4", "1", "6"]
NoteIn the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
Java 7
standard input
[ "dp", "binary search", "data structures" ]
bd4b3bfa7511410c8e54658cc1dddb46
The first line of the input contains two integers, n and k (1 ≤ n, k ≤ 2·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — elements of the sequence.
1,700
Output a single number — the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.
standard output
PASSED
858252124a6fcf07671a0c36471a9497
train_000.jsonl
1438790400
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≤ i1 &lt; i2 &lt; i3 ≤ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.A geometric progression with common ratio k is a sequence of numbers of the form b·k0, b·k1, ..., b·kr - 1.Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.
256 megabytes
import java.awt.Point; import java.awt.Rectangle; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.ObjectInputStream.GetField; import java.lang.reflect.Array; import java.math.BigInteger; import java.security.KeyStore.Entry; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Random; import java.util.Set; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; public class Solution { static FastReader in = new FastReader(new BufferedReader(new InputStreamReader(System.in))); static PrintWriter out = new PrintWriter(System.out); static boolean file = false; static final int maxn = (int)2e5+111; static int inf = (int)1e9; static int n,k; static int a[] = new int[maxn]; static long ans = 0; static HashMap<Integer,Integer> cnt = new HashMap<Integer,Integer>(); static HashMap<Integer,Long> M = new HashMap<Integer,Long>(); private static void solve() throws Exception { n = in.nextInt(); k = in.nextInt(); for (int i=1; i<=n; i++) { a[i] = in.nextInt(); } for (int i=1; i<=n; i++) { if (a[i]%(k*1L*k)==0) { int x = a[i]/k/k; if (!M.containsKey(x)) M.put(x, 0L); ans+=M.get(x); } if (a[i]%k==0) { int x = a[i]/k; if (!M.containsKey(x)) M.put(x, 0L); if (!cnt.containsKey(x)) cnt.put(x, 0); M.put(x,M.get(x)+cnt.get(x)); } if (!cnt.containsKey(a[i])) cnt.put(a[i], 0); cnt.put(a[i], cnt.get(a[i])+1); } out.println(ans); } public static void main (String [] args) throws Exception { if (file) { in = new FastReader(new BufferedReader(new FileReader("input.txt"))); out = new PrintWriter ("output.txt"); } solve(); out.close(); } } class Pair implements Comparable<Pair> { int x,y; public Pair(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object obj) { Pair p = (Pair)obj; if (p.x == x && p.y==y) return true; return false; } @Override public int compareTo(Pair p) { if (x<p.x)return 1; else if (x==p.x) return 0; else return -1; } } class FastReader { BufferedReader bf; StringTokenizer tk = null; public FastReader(BufferedReader bf) { this.bf = bf; } public String nextToken () throws Exception { if (tk==null || !tk.hasMoreTokens()) { tk = new StringTokenizer(bf.readLine()); } return tk.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(nextToken()); } public long nextLong() throws Exception { return Long.parseLong(nextToken()); } public double nextDouble() throws Exception { return Double.parseDouble(nextToken()); } }
Java
["5 2\n1 1 2 2 4", "3 1\n1 1 1", "10 3\n1 2 6 2 3 6 9 18 3 9"]
1 second
["4", "1", "6"]
NoteIn the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
Java 7
standard input
[ "dp", "binary search", "data structures" ]
bd4b3bfa7511410c8e54658cc1dddb46
The first line of the input contains two integers, n and k (1 ≤ n, k ≤ 2·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — elements of the sequence.
1,700
Output a single number — the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.
standard output
PASSED
e057c2ed678ccc4f0486158127d24edd
train_000.jsonl
1438790400
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≤ i1 &lt; i2 &lt; i3 ≤ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.A geometric progression with common ratio k is a sequence of numbers of the form b·k0, b·k1, ..., b·kr - 1.Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.
256 megabytes
import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; public class Main { public void solve() { Scanner scanner = new Scanner(System.in); int N = scanner.nextInt(); int K = scanner.nextInt(); int[] a = new int[N]; for (int i = 0; i < N; i++) { a[i] = scanner.nextInt(); } scanner.close(); if (K == 1) { Arrays.sort(a); long ans = 0; long cnt = 0; for (int i = 0; i < N; i++) { cnt++; if (i == N - 1 || a[i] != a[i + 1]) { if (cnt >= 3) { long tmp = 1; tmp *= cnt * (cnt - 1) * (cnt - 2); tmp /= 6; ans += tmp; } cnt = 0; } } System.out.println(ans); return; } long ans = 0; long zeroCnt = 0; HashMap<Integer, Long> countMap = new HashMap<>(); HashMap<Integer, Long> dimMap = new HashMap<>(); for (int i = 0; i < N; i++) { // ゼロの時は別途対応 if (a[i] == 0) { zeroCnt++; continue; } // 一番下の時 if (countMap.containsKey(a[i])) { countMap.put(a[i], countMap.get(a[i]) + 1); } else { countMap.put(a[i], 1L); } // 真ん中の時 if (a[i] % K != 0) { continue; } int child = a[i] / K; if (dimMap.containsKey(a[i]) && countMap.containsKey(child)) { dimMap.put(a[i], dimMap.get(a[i]) + countMap.get(child)); } else if (countMap.containsKey(child)) { dimMap.put(a[i], countMap.get(child)); } // 一番上の時 if (dimMap.containsKey(child)) { ans += dimMap.get(child); } } // ゼロの中から3つゼロを取り出す組み合わせ long tmp = zeroCnt * (zeroCnt - 1) * (zeroCnt - 2); tmp /= 6; ans += tmp; System.out.println(ans); } public static void main(String[] args) { new Main().solve(); } }
Java
["5 2\n1 1 2 2 4", "3 1\n1 1 1", "10 3\n1 2 6 2 3 6 9 18 3 9"]
1 second
["4", "1", "6"]
NoteIn the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
Java 7
standard input
[ "dp", "binary search", "data structures" ]
bd4b3bfa7511410c8e54658cc1dddb46
The first line of the input contains two integers, n and k (1 ≤ n, k ≤ 2·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — elements of the sequence.
1,700
Output a single number — the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.
standard output
PASSED
eedb761df226ee0fccf25a2bc2e18e63
train_000.jsonl
1438790400
Polycarp loves geometric progressions very much. Since he was only three years old, he loves only the progressions of length three. He also has a favorite integer k and a sequence a, consisting of n integers.He wants to know how many subsequences of length three can be selected from a, so that they form a geometric progression with common ratio k.A subsequence of length three is a combination of three such indexes i1, i2, i3, that 1 ≤ i1 &lt; i2 &lt; i3 ≤ n. That is, a subsequence of length three are such groups of three elements that are not necessarily consecutive in the sequence, but their indexes are strictly increasing.A geometric progression with common ratio k is a sequence of numbers of the form b·k0, b·k1, ..., b·kr - 1.Polycarp is only three years old, so he can not calculate this number himself. Help him to do it.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.text.*; public class Main3 { public static int n, k, nk, b; public static void fact(int value) { nk = 0; if ( value != 0) { while( value % k == 0 ) { nk++; value /= k; } } b = value; } public static long maxL( long a, long b) { if ( a > b) return a; return b; } public static void main(String[] args) throws IOException { BufferedReader in; StringBuilder out = new StringBuilder(); File file = new File("in"); if (file.exists()) in = new BufferedReader(new FileReader(file)); else in = new BufferedReader(new InputStreamReader(System.in)); String line, lines[]; lines = in.readLine().split(" "); n = Integer.parseInt(lines[0]); k = Integer.parseInt(lines[1]); lines = in.readLine().split(" "); int arr[] = new int[n]; ArrayList<Integer> ls[] = new ArrayList[n]; int keys[] = new int[n]; int count= 0; long countZ = 0; for ( int i = 0; i < n; i++ ) { arr[i] = Integer.parseInt(lines[i]); if ( arr[i] == 0) countZ++; } countZ = countZ*(countZ-1)*(countZ-2); countZ /= 6l; if ( k != 1) { HashMap<Integer,Integer> map = new HashMap<Integer, Integer>(); int value; for ( int i = 0; i < n; i++ ) { fact(arr[i]); if ( map.containsKey(b)) { value = map.get(b); ls[value].add(nk); } else { ls[count] = new ArrayList<Integer>(); ls[count].add(nk); map.put(b, count); count++; } } long result = 0l; int l; long pow[]; long pares[]; for ( int i = 0; i < count; i++ ) { pow = new long[30]; pares = new long[30]; for (int auxL : ls[i]) { if ( auxL >= 2) { result += (long)(pares[auxL-1]); } if ( auxL >= 1) { pares[auxL] += pow[auxL-1]; } pow[auxL]++; } } System.out.println(maxL(result, countZ)); } else { HashMap<Integer,Long> mapV = new HashMap<Integer, Long>(); long r = 0l; long ot = 0l; BigInteger resp = new BigInteger("0"); for ( int i = 0; i < n; i++ ) { if ( !mapV.containsKey(arr[i])) { mapV.put(arr[i], 1l); } else { long aux = mapV.get(arr[i]); mapV.put(arr[i], aux+1l); if ( aux>= 2) { ot = (long)(aux); BigInteger auxB1 = new BigInteger(ot+""); BigInteger auxB2 = new BigInteger((ot-1)+""); auxB1 = auxB1.multiply(auxB2); auxB1 = auxB1.divide(new BigInteger("2")); resp = resp.add(auxB1); } } } System.out.println(maxL(Long.parseLong(resp.toString()), countZ)); } } }
Java
["5 2\n1 1 2 2 4", "3 1\n1 1 1", "10 3\n1 2 6 2 3 6 9 18 3 9"]
1 second
["4", "1", "6"]
NoteIn the first sample test the answer is four, as any of the two 1s can be chosen as the first element, the second element can be any of the 2s, and the third element of the subsequence must be equal to 4.
Java 7
standard input
[ "dp", "binary search", "data structures" ]
bd4b3bfa7511410c8e54658cc1dddb46
The first line of the input contains two integers, n and k (1 ≤ n, k ≤ 2·105), showing how many numbers Polycarp's sequence has and his favorite number. The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — elements of the sequence.
1,700
Output a single number — the number of ways to choose a subsequence of length three, such that it forms a geometric progression with a common ratio k.
standard output
PASSED
19c8c46338b1478c70d99f3b006d53cc
train_000.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class Main { static int[] wins; static int[] pwins; static int[] gwins; static boolean valid(int sets, int games) { for (int set = 0; set < sets; set++) { int sum = 0; int offset = set * games; for (int game = 0; game < games; game++) { sum += wins[offset + game]; } if (sum == 0) { return false; } } return true; } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //BufferedReader br = new BufferedReader(new FileReader("data")); int seq = Integer.parseInt(br.readLine()); pwins = new int[seq]; gwins = new int[seq]; StringTokenizer st = new StringTokenizer(br.readLine()); int p = 0, g = 0; char ch = '0'; for (int i = 0; i < seq; i++) { ch = st.nextToken().charAt(0); if (ch == '1') { p++; } else { g++; } pwins[i] = p; gwins[i] = g; } int max = p > g ? p : g; TreeMap<Integer, TreeSet<Integer>> solutions = new TreeMap<>(); int setp = 0, setg = 0, minusp = 0, minusg = 0; int totalsolutions = 0; for (int games = max; games >= 1; games--) { int index = games - 1; setp = setg = minusp = minusg = 0; boolean valid = true; while (true) { if (index >= seq) { valid = false; break; } if (pwins[index] - minusp == games || gwins[index] - minusg == games) { if (pwins[index] - minusp == games) { setp++; } else { setg++; } minusp = pwins[index]; minusg = gwins[index]; if (index == seq - 1) { valid = (setp > setg && ch == '1') || (setg > setp && ch == '2'); break; } else { index += games; } } else { index += games - Math.max(pwins[index] - minusp, gwins[index] - minusg); } } if (valid) { totalsolutions++; int sets = Math.max(setp, setg); TreeSet<Integer> sol; if (solutions.containsKey(sets)) { sol = solutions.get(sets); } else { sol = new TreeSet<>(); } sol.add(games); solutions.put(sets, sol); } } System.out.println(totalsolutions); for (int setno : solutions.keySet()) { TreeSet<Integer> sol = solutions.get(setno); for (int gameno : sol) { System.out.println(setno + " " + gameno); } } } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 8
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
85b68bca8b8482aae1155f21aa38c747
train_000.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author aryssoncf */ 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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { try { int n = in.readInt(); int[] a = in.readIntArray(n); MiscUtils.decreaseByOne(a); int[][] counter = new int[2][n]; for (int i = 0; i < 2; i++) { for (int j = 0; j < n; j++) { counter[i][j] = a[j] == i ? 1 : 0; if (j > 0) { counter[i][j] += counter[i][j - 1]; } } } List<IntIntPair> res = new ArrayList<>(); for (int t = n; t > 0; t--) { int s = f(counter, t); if (s != -1) { res.add(IntIntPair.makePair(s, t)); } } Collections.sort(res); out.printLine(res.size()); out.printPairList(res); } catch (Exception e) { e.printStackTrace(); } } int f(int[][] counter, int t) { int[] score = new int[2]; int n = counter[0].length, pos = 0, chosen = -1; while (pos < n) { int end = n; chosen = -1; for (int type = 0; type < 2; type++) { int finalType = type; int finalPos = pos; LongFilter filter = i -> { int prev = finalPos == 0 ? 0 : counter[finalType][finalPos - 1]; return i == n || counter[finalType][(int) i] >= prev + t; }; int aux = (int) MiscUtils.binarySearch(0, n, filter); if (aux < end) { end = aux; chosen = type; } } if (chosen == -1) { return -1; } pos = end + 1; score[chosen]++; } if (score[0] == score[1]) { return -1; } int best = score[0] > score[1] ? 0 : 1; return chosen == best ? score[best] : -1; } } static class MiscUtils { public static long binarySearch(long from, long to, LongFilter function) { while (from < to) { long argument = from + ((to - from) >> 1); if (function.accept(argument)) { to = argument; } else { from = argument + 1; } } return from; } public static void decreaseByOne(int[]... arrays) { for (int[] array : arrays) { for (int i = 0; i < array.length; i++) { array[i]--; } } } } static class IntIntPair implements Comparable<IntIntPair> { public final int first; public final int second; public static IntIntPair makePair(int first, int second) { return new IntIntPair(first, second); } public IntIntPair(int first, int second) { this.first = first; this.second = second; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IntIntPair pair = (IntIntPair) o; return first == pair.first && second == pair.second; } public int hashCode() { int result = first; result = 31 * result + second; return result; } public String toString() { return "(" + first + "," + second + ")"; } public int compareTo(IntIntPair o) { int value = Integer.compare(first, o.first); if (value != 0) { return value; } return Integer.compare(second, o.second); } } static interface LongFilter { public boolean accept(long value); } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } public void printPairList(List<IntIntPair> answer) { for (IntIntPair pair : answer) { printLine(pair.first, pair.second); } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int[] readIntArray(int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = readInt(); } return array; } 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 { boolean isSpaceChar(int ch); } } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 8
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
afd9c5469b7e18d8d9c4168986ee8c38
train_000.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Iterator; public class Main { //removing columns // public static char[][] readEntrance() throws IOException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // String line = br.readLine(); // String[] numbers = line.split(" "); // int n = Integer.parseInt(numbers[0]); // int m = Integer.parseInt(numbers[1]); // // char[][] A = new char[n][m]; // // for (int i = 0; i < n; i++) { // line = br.readLine(); // for (int j = 0; j < m; j++) { // A[i][j] = line.charAt(j); // } // } // return A; // } // // public static void main (String[] args) throws IOException { // char[][] A = readEntrance(); // int toRemove = 0; // if (A.length < 2) { // System.out.println(0); // return; // } // if (A[0].length == 0) { // System.out.println(0); // return; // } // boolean[] wasSame = new boolean[A.length]; // // for (int i = 0; i < wasSame.length; i++) { // wasSame[i] = true; // } // // for (int j = 0; j < A[0].length; j++) { // int i = 1; boolean good = true; // boolean[] isSame = new boolean[A.length]; // while (i < A.length && good) { // if (wasSame[i]) { // if (A[i][j] < A[i-1][j]) { // toRemove++; // good = false; // } else if (A[i][j] == A[i-1][j]) { // isSame[i] = true; // } // } // i++; // } // for (int k = 0; k < A.length; k++) { // if (good) { // wasSame[k] = isSame[k]; // } // } // } // System.out.println(toRemove); // } public static void main (String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); int n = Integer.parseInt(line); int[] A = new int[n]; line = br.readLine(); String[] serves = line.split(" "); ArrayList<ArrayList<Integer>> advSc = new ArrayList<ArrayList<Integer>>(2); advSc.add(new ArrayList<Integer>()); advSc.get(0).add(0); advSc.add(new ArrayList<Integer>()); advSc.get(1).add(0); int[] scores = new int[2]; for (int j = 0; j < n; j++) { int tmp = Integer.parseInt(serves[j]); A[j] = tmp; scores[tmp-1]++; advSc.get(tmp-1).add(scores[2-tmp]); } ArrayList<Integer> sSet = new ArrayList<Integer>(); ArrayList<Integer> tSet = new ArrayList<Integer>(); int counter = 0; for (int t = Math.max(scores[0], scores[1]); t > 0; t--) { int[] tmpSets = new int[2]; int better = 0; int[] index = new int[2]; int act = (scores[0] > scores[1]) ? 0 : 1; while (advSc.get(act).size() > index[act]+t) { // System.out.println("index " + index[act] + " value " + advSc.get(act).get(index[act])); better = (advSc.get(act).get(index[act]+t) - index[1-act] >= t) ? 1-act : act; index[better] += t; index[1-better] = advSc.get(better).get(index[better]); tmpSets[better]++; act = (index[act]+t < advSc.get(act).size()) ? act : 1-act; // System.out.println("sets: " + tmpSets[0] + ", " + tmpSets[1]); } // System.out.println("after while"); // System.out.println("t: " + t + " index[0]: " + index[0] + " index[1]: " + index[1] + " sets: " + tmpSets[longer]); if (index[better] == advSc.get(better).size()-1 && index[1-better] == advSc.get(1-better).size()-1 && tmpSets[better] > tmpSets[1-better]) { // System.out.println("here"); counter++; tSet.add(t); sSet.add(Math.max(tmpSets[0], tmpSets[1])); } } System.out.println(counter); Iterator<Integer> it1 = sSet.iterator(); Iterator<Integer> it2 = tSet.iterator(); int lastS = 0; ArrayList<Integer> sLast = new ArrayList<Integer>(); ArrayList<Integer> tLast = new ArrayList<Integer>(); if (it1.hasNext()) { lastS = it1.next(); sLast.add(lastS); tLast.add(it2.next()); } while (it1.hasNext()) { int a = it1.next(); if (a != lastS) { for (int i = sLast.size()-1; i >= 0; i--) { System.out.println(sLast.get(i) + " " + tLast.get(i)); } sLast.clear(); tLast.clear(); } sLast.add(a); tLast.add(it2.next()); lastS = a; } for (int i = sLast.size()-1; i >= 0; i--) { System.out.println(sLast.get(i) + " " + tLast.get(i)); sLast.remove(i); tLast.remove(i); } } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 6
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
193692e8638d14bde8281db6c2a138db
train_000.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Scanner; public class CF283D1 { private static class Result implements Comparable<Result> { Integer s; Integer t; public Result(final Integer s, final Integer t) { this.s = s; this.t = t; } @Override public int compareTo(final Result o) { if (s.compareTo(o.s) == 0) { return t.compareTo(o.t); } return s.compareTo(o.s); } } public static void main(final String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); List<Integer> posOnesList = new LinkedList<Integer>(); List<Integer> posTwosList = new LinkedList<Integer>(); int[] meetOnes = new int[n]; int[] meetTwos = new int[n]; int last = -1; for (int i = 0; i < n; i++) { int curr = sc.nextInt(); meetOnes[i] = i > 0 ? meetOnes[i - 1] : 0; meetTwos[i] = i > 0 ? meetTwos[i - 1] : 0; if (curr == 1) { posOnesList.add(i); meetOnes[i]++; } else { posTwosList.add(i); meetTwos[i]++; } if (i == n - 1) { last = curr; } } Integer[] posOnes = posOnesList.toArray(new Integer[0]); Integer[] posTwos = posTwosList.toArray(new Integer[0]); List<Result> results = new LinkedList<Result>(); for (int t = 1; t <= n; t++) { int currPos = -1; int onesWins = 0; int twosWins = 0; while (currPos < n) { int metOnes = currPos >= 0 ? meetOnes[currPos] : 0; int metTwos = currPos >= 0 ? meetTwos[currPos] : 0; int i1 = 3 * n; if (metOnes + t - 1 < posOnes.length) { i1 = posOnes[metOnes + t - 1]; } int i2 = 3 * n; if (metTwos + t - 1 < posTwos.length) { i2 = posTwos[metTwos + t - 1]; } if (i1 < i2) { currPos = i1; onesWins++; } else if (i2 < i1) { currPos = i2; twosWins++; } else { break; } } if (currPos == n - 1 && onesWins != twosWins) { if (onesWins > twosWins && last == 1) { results.add(new Result(onesWins, t)); } if (twosWins > onesWins && last == 2) { results.add(new Result(twosWins, t)); } } } Result[] res = results.toArray(new Result[0]); Arrays.sort(res); StringBuilder sb = new StringBuilder(); for (Result r : res) { if (sb.length() > 0) { sb.append("\n"); } sb.append(r.s + " " + r.t); } System.out.println(res.length); if (res.length > 0) { System.out.println(sb.toString()); } } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 6
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
03c7d588494ed278276e5d8dac6dcbf7
train_000.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
256 megabytes
import java.util.Scanner; import java.util.List; import java.io.IOException; import java.util.ArrayList; import java.util.Comparator; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author 你猜 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); int[] winner = new int[n]; int[] numPetyaWins = new int[n + 1]; for (int i = 0; i < n; ++i) { winner[i] = in.nextInt(); numPetyaWins[i + 1] = numPetyaWins[i]; if (winner[i] == 1) { ++numPetyaWins[i + 1]; } } int lastWin = 0; List<int[]> answer = new ArrayList<int[]>(); outer: for (int setUnit = 1; setUnit <= n; ++setUnit) { int win1 = 0, win2 = 0; for (int i = 0; i < n; ) { int left = i, right = n - 1; while (left < right) { int mid = ((left + right) >> 1) + 1; if (numPetyaWins[mid] - numPetyaWins[i] >= setUnit || mid - i - (numPetyaWins[mid] - numPetyaWins[i]) >= setUnit) { right = mid - 1; } else { left = mid; } } if (numPetyaWins[left + 1] - numPetyaWins[i] == setUnit) { ++win1; lastWin = 1; } else if (left + 1 - i - (numPetyaWins[left + 1] - numPetyaWins[i]) == setUnit) { ++win2; lastWin = 2; } else continue outer; i = left + 1; } if (win1 > win2 && lastWin == 1 || win1 < win2 && lastWin == 2) { answer.add(new int[]{Math.max(win1, win2), setUnit}); } } Collections.sort(answer, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { if (o1[0] != o2[0]) { return o1[0] - o2[0]; } return o1[1] - o2[1]; } }); out.println(answer.size()); for (int[] answerItem : answer) { out.println(answerItem[0] + " " + answerItem[1]); } } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 6
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
fd2e4742242d6ecaf090acf52561a78c
train_000.jsonl
1418833800
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the next set starts and scores of both players are being set to 0. As soon as one of the players wins the total of s sets, he wins the match and the match is over. Here s and t are some positive integer numbers.To spice it up, Petya and Gena choose new numbers s and t before every match. Besides, for the sake of history they keep a record of each match: that is, for each serve they write down the winner. Serve winners are recorded in the chronological order. In a record the set is over as soon as one of the players scores t points and the match is over as soon as one of the players wins s sets.Petya and Gena have found a record of an old match. Unfortunately, the sequence of serves in the record isn't divided into sets and numbers s and t for the given match are also lost. The players now wonder what values of s and t might be. Can you determine all the possible options?
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 Solution { static class an implements Comparable<an> { int s,t; public an(int s, int t) { this.s=s; this.t=t; } public int compareTo(an o){ if (s!=o.s) return s-o.s; return t-o.t; } } public static void main (String[] args) throws java.lang.Exception { // your code goes here Scanner in = new Scanner(System.in); int n=Integer.parseInt(in.nextLine()); String[] a=in.nextLine().split(" "); //for (int i=0;i<n;i++) System.out.println(a[i]); int[][] ct=new int[2][n+1]; ct[0][0]=0; ct[1][0]=0; for(int i=1;i<=n;i++){ if(a[i-1].equals("1")){ ct[0][i]=ct[0][i-1]+1; ct[1][i]=ct[1][i-1]; } else{ ct[0][i]=ct[0][i-1]; ct[1][i]=ct[1][i-1]+1; } } //for (int i=0;i<=n;i++) System.out.println(ct[0][i]+" "+ct[1][i]); ArrayList<an> ans = new ArrayList<an>(); for(int t=1;t<=n;t++) { int[] w={0,0}; int i=0; int wl=0; while(i<n){ int l=i; int r=Math.min(n,l+2*t); while(l+1<r){ int m=(l+r)/2; int w1=ct[0][m]-ct[0][i]; int w2=ct[1][m]-ct[1][i]; if(Math.max(w1,w2)<t) l=m; else r=m; } int w1=ct[0][r]-ct[0][i]; int w2=ct[1][r]-ct[1][i]; if (w1==t) { w[0]+=1; wl=1; } else if (w2==t) { w[1]+=1; wl=2; } else break; i=r; } if (i!=n || w[0]==w[1]) continue; int s=Math.max(w[0],w[1]); if (wl==1 && s!=w[0]) continue; if (wl==2 && s!=w[1]) continue; ans.add(new an(s,t)); } Collections.sort(ans); System.out.println(ans.size()); for (an i: ans) System.out.println(i.s+" "+i.t); } }
Java
["5\n1 2 1 2 1", "4\n1 1 1 1", "4\n1 2 1 2", "8\n2 1 2 1 1 1 1 1"]
2 seconds
["2\n1 3\n3 1", "3\n1 4\n2 2\n4 1", "0", "3\n1 6\n2 3\n6 1"]
null
Java 6
standard input
[ "binary search" ]
eefea51c77b411640a3b92b9f2dd2cf1
The first line contains a single integer n — the length of the sequence of games (1 ≤ n ≤ 105). The second line contains n space-separated integers ai. If ai = 1, then the i-th serve was won by Petya, if ai = 2, then the i-th serve was won by Gena. It is not guaranteed that at least one option for numbers s and t corresponds to the given record.
1,900
In the first line print a single number k — the number of options for numbers s and t. In each of the following k lines print two integers si and ti — the option for numbers s and t. Print the options in the order of increasing si, and for equal si — in the order of increasing ti.
standard output
PASSED
e89f31c8a35e4b302ac22e1b88a4d3b7
train_000.jsonl
1294733700
The Hedgehog likes to give presents to his friend, but no less he likes to receive them.Having received another present today, the Hedgehog suddenly understood that he has no place to put it as there was no room left on the special shelf in the cupboard. He will have to choose another shelf, but which one should he choose, how large should it be?In order to get to know this, the Hedgehog asks you to write him a program that will count the estimated number of presents that he will receive during the following N days. Besides, he is guided by the principle: on each holiday day the Hedgehog will necessarily receive a present, he receives presents at least every K days (i.e., if he received a present on the i-th day, he will receive the next present no later than on the i + K-th day). For the given N and K, as well as the list of holidays among the following N days count the minimal number of presents that could be given to the Hedgehog. The number of today's day is zero, and you should regard today's present as already given (i.e., you shouldn't count it in the answer).
256 megabytes
import java.util.*; //warm-up public class Presents { static Set<Integer> s = new HashSet<Integer>(); static void solve(){ Scanner sc = new Scanner(System.in); int n=sc.nextInt(), k=sc.nextInt(),NOC=sc.nextInt(),i=0,no=0,gap=1; while (NOC-->0) s.add(sc.nextInt()); while (++i<=n) { if (s.contains(i)||gap==k) { no++; gap=0; } gap++; } System.out.println(no); sc.close(); } public static void main(String args[]) { solve(); } }
Java
["5 2\n1 3", "10 1\n3 6 7 8"]
2 seconds
["3", "10"]
null
Java 11
standard input
[ "implementation" ]
07b750dbf7f942eab80d4260103c7472
The first line contains integers N and K (1 ≤ N ≤ 365, 1 ≤ K ≤ N). The second line contains a number C which represents the number of holidays (0 ≤ C ≤ N). Then in the same line follow C numbers ranging from 1 to N which are the numbers of holiday days. The numbers are given in the increasing order, without repeating numbers among them.
1,300
Print a single number — the minimal number of presents the Hedgehog will receive over the following N days.
standard output
PASSED
e8e697b31f61deff4faefe824ed88d92
train_000.jsonl
1294733700
The Hedgehog likes to give presents to his friend, but no less he likes to receive them.Having received another present today, the Hedgehog suddenly understood that he has no place to put it as there was no room left on the special shelf in the cupboard. He will have to choose another shelf, but which one should he choose, how large should it be?In order to get to know this, the Hedgehog asks you to write him a program that will count the estimated number of presents that he will receive during the following N days. Besides, he is guided by the principle: on each holiday day the Hedgehog will necessarily receive a present, he receives presents at least every K days (i.e., if he received a present on the i-th day, he will receive the next present no later than on the i + K-th day). For the given N and K, as well as the list of holidays among the following N days count the minimal number of presents that could be given to the Hedgehog. The number of today's day is zero, and you should regard today's present as already given (i.e., you shouldn't count it in the answer).
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.util.InputMismatchException; import java.io.InputStreamReader; import java.io.BufferedOutputStream; import java.util.StringTokenizer; import java.io.Closeable; import java.io.BufferedReader; import java.io.InputStream; import java.io.Flushable; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; Input in = new Input(inputStream); Output out = new Output(outputStream); APresents solver = new APresents(); solver.solve(1, in, out); out.close(); } } public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1<<29); thread.start(); thread.join(); } static class APresents { public APresents() { } public void solve(int kase, Input in, Output pw) { int n = in.nextInt(), k = in.nextInt(), c = in.nextInt(); int[] arr = new int[c]; for(int i = 0; i<c; i++) { arr[i] = in.nextInt(); } int prev = 0, j = 0, ans = 0; for(int i = 1; i<=n; i++) { if(j<c&&arr[j]==i) { prev = i; ans++; j++; }else if(prev+k==i) { prev = i; ans++; } } pw.println(ans); } } static class Input { BufferedReader br; StringTokenizer st; public Input(InputStream is) { this(is, 1<<20); } public Input(InputStream is, int bs) { br = new BufferedReader(new InputStreamReader(is), bs); st = null; } public boolean hasNext() { try { while(st==null||!st.hasMoreTokens()) { String s = br.readLine(); if(s==null) { return false; } st = new StringTokenizer(s); } return true; }catch(Exception e) { return false; } } public String next() { if(!hasNext()) { throw new InputMismatchException(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } static class Output implements Closeable, Flushable { public StringBuilder sb; public OutputStream os; public int BUFFER_SIZE; public boolean autoFlush; public String LineSeparator; public Output(OutputStream os) { this(os, 1<<16); } public Output(OutputStream os, int bs) { BUFFER_SIZE = bs; sb = new StringBuilder(BUFFER_SIZE); this.os = new BufferedOutputStream(os, 1<<17); autoFlush = false; LineSeparator = System.lineSeparator(); } public void println(int i) { println(String.valueOf(i)); } public void println(String s) { sb.append(s); println(); if(autoFlush) { flush(); }else if(sb.length()>BUFFER_SIZE >> 1) { flushToBuffer(); } } public void println() { sb.append(LineSeparator); } private void flushToBuffer() { try { os.write(sb.toString().getBytes()); }catch(IOException e) { e.printStackTrace(); } sb = new StringBuilder(BUFFER_SIZE); } public void flush() { try { flushToBuffer(); os.flush(); }catch(IOException e) { e.printStackTrace(); } } public void close() { flush(); try { os.close(); }catch(IOException e) { e.printStackTrace(); } } } }
Java
["5 2\n1 3", "10 1\n3 6 7 8"]
2 seconds
["3", "10"]
null
Java 11
standard input
[ "implementation" ]
07b750dbf7f942eab80d4260103c7472
The first line contains integers N and K (1 ≤ N ≤ 365, 1 ≤ K ≤ N). The second line contains a number C which represents the number of holidays (0 ≤ C ≤ N). Then in the same line follow C numbers ranging from 1 to N which are the numbers of holiday days. The numbers are given in the increasing order, without repeating numbers among them.
1,300
Print a single number — the minimal number of presents the Hedgehog will receive over the following N days.
standard output
PASSED
dd9e2780e59c7e85cd0bcbea28a21c11
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
import java.util.Scanner; public class CodeForce { public static void main(String[] args) { Scanner s = new Scanner(System.in); int t = s.nextInt(); while(t>0) { String n = s.next(); System.out.println(n.length()); t--; } } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
4572d810772d50f0bb925cf05c1e73b1
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
import java.util.Scanner; public class cp2 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); int t = in.nextInt(); for(int i = 0;i<t;i++) { String n = in.next(); int l = n.length(); System.out.println(l); } } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
fbbb546aa2dd1ea532c013978474014b
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
import java.math.BigInteger; import java.util.*; import java.util.Scanner; public class StrangeFunctions { public static int getCount(BigInteger number) { double factor = Math.log(2) / Math.log(10); int Count = (int) (factor * number.bitLength() + 1); if (BigInteger.TEN.pow(Count - 1).compareTo(number) > 0) { return Count - 1; } return Count; } public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0) { BigInteger n = sc.nextBigInteger(); System.out.println(getCount(n)); } } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
56c285445720b577db43cfdd9a7569dd
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
import java.util.*; public class Main{ public static void main(String[]args){ Scanner sc=new Scanner(System.in); int t=sc.nextInt(); String z=sc.nextLine(); while(t-->0){ String n=sc.nextLine(); System.out.println(n.length()); } } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
a716178ad8e2f89283603380c24926d0
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
import java.util.*; public class problems { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t>0) { String s=sc.next(); solve(s); t--; } } static void solve(String n) { System.out.println(n.length()); } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
952e79e495d92d27bd64c9c9d7f1cebb
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class A { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static FastReader s = new FastReader(); static PrintWriter out = new PrintWriter(System.out); private static int[] rai(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = s.nextInt(); } return arr; } private static int[][] rai(int n, int m) { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = s.nextInt(); } } return arr; } private static long[] ral(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = s.nextLong(); } return arr; } private static long[][] ral(int n, int m) { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = s.nextLong(); } } return arr; } private static int ri() { return s.nextInt(); } private static long rl() { return s.nextLong(); } private static String rs() { return s.next(); } public static void main(String[] args) { // TODO Auto-generated method stub FastReader sc=new FastReader(); int t,i,j,sum=0,c=0; BigInteger n; t=sc.nextInt(); while(t-->0) { String s; s=sc.next(); System.out.println(s.length()); } } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
2240fca3d13541a129a98f79b2b0e2d2
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class E { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); int t,i,j,sum=0,c=0; BigInteger n; t=sc.nextInt(); while(t-->0) { n=sc.nextBigInteger(); while(!n.equals(BigInteger.valueOf(0))) { c++; n=n.divide(BigInteger.valueOf(10)); } System.out.println(c); c=0; } } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
b87f31991d2e212e1f3dad915bf2d59f
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
import java.util.*; // import java.lang.*; import java.io.*; // THIS TEMPLATE MADE BY AKSH BANSAL. public class Solution { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) throws IOException { FastReader sc = new FastReader(); // ________________________________ int t = sc.nextInt(); StringBuilder output = new StringBuilder(); while (t-- > 0) { String s = sc.nextLine(); output.append(solver(s)).append("\n"); } System.out.println(output); // _______________________________ // int n = sc.nextInt(); // int[] arr = new int[n]; // // for(int i=0;i<n;i++){ // arr[i] = sc.nextInt(); // } // System.out.println(solver(arr,n)); // ________________________________ } public static int solver(String s) { return s.length(); } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
4da29ba0852684bc5c892302cdb7db9e
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
import java.util.Scanner; import java.math.BigDecimal; import java.util.Arrays; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); long t=sc.nextLong(); while(t>0){ String n=sc.next(); long sum=0; long len=n.length(); for(;len!=0;sum++) { len--; } t--; System.out.println(sum); } } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
d379d6b26b26e76898bc31e22a6beeb2
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
import java.util.Scanner; public class Codeforces { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); sc.nextLine(); while(t-- >0){ String str = sc.nextLine(); int len = str.length(); System.out.println(len); } } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
34dbbb43bafda5eca5feafc3d73b217e
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class strange { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // Scanner sc=new Scanner(System.in); int t = Integer.parseInt(br.readLine()); // int t=sc.nextInt(); while(t-->0) { String line = br.readLine(); // long n=sc.nextLong(); // int count=0; // // while(n>0) { // count++; // n/=10; // } System.out.println(line.length()); // String s=Long.toString(n); // int i=0; // boolean flag=false; // while(s.charAt(i)=='0') { // flag=true; // i++; // } // if(flag) // { // System.out.println(1); // continue; // } //// StringBuilder str=new StringBuilder(s.substring(i,s.length())); //// String sn=new String(str.reverse()); // long n2=Long.parseLong(s.substring(i,s.length())); // System.out.pri } } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
8a2898e604832f8ee947bedacbf3d021
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
// Rezk import java.util.Scanner; public class Codeforces { public static void main(String[] args) { Scanner input = new Scanner(System.in); int n,m; String str; n = input.nextInt(); str = input.nextLine(); for(int i=0;i<n;++i){ str = input.nextLine();// if(s.length()) System.out.println(str.length()); } } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
4be838af8f560fc209ad19f314263e54
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
import java.io.*; import java.util.*; public class abc { public static void main(String arg[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); StringBuilder sb=new StringBuilder(); while(t-->0) { String s=br.readLine(); sb.append(String.valueOf(s.length())+"\n"); } System.out.println(sb); } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
9998b05e1eb5575ab597cb28d8fa2ce4
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
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 Codeforces { public static void main (String[] args) throws java.lang.Exception { // your code goes here BufferedReader buf=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(buf.readLine()); StringBuilder sb=new StringBuilder(); for(int i=0;i<t;i++) { String s=buf.readLine(); char ch[]=s.toCharArray(); sb.append(ch.length+"\n"); } System.out.println(sb); } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
c6dd7b3c8893b3c281475dfeeff34270
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
import java.io.*; import java.util.*; public class Func { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { String n=sc.next(); int c=n.length(); char ch=n.charAt(0); System.out.println(c); } } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
a4098dc6074867d507a7abed1d489b9d
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
import java.math.BigInteger; //public class eferf { // //} import java.util.Scanner; public class eferf { public static void main(String args[]) { Scanner s = new Scanner(System.in); long t = s.nextLong(); for (int i=0;i<t;i++) { BigInteger n = s.nextBigInteger(); BigInteger A = new BigInteger("10"); BigInteger B = new BigInteger("0"); int a =0; while(n.compareTo(B)>0) { n = n.divide(A); a+=1; } System.out.println(a); } //s.close(); } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
908b5a65a832be6c4006aa57cca4ac6a
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
import java.util.*; public class hello { public static void main(String args[]) { Scanner sc= new Scanner(System.in); int t=sc.nextInt(); sc.nextLine(); while(t-->0) { String s=sc.nextLine(); System.out.println(s.length()); } } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
d1cfdbacd1edc7b2d8e31221c368dcd0
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { public static int total(BigInteger a){ BigInteger temp = a; int b = 0; int r = 10; do{ temp = temp.divide(BigInteger.valueOf(r)); b ++; }while (temp != BigInteger.ZERO); return b; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); BigInteger in [] = new BigInteger [t]; for (int i = 0; i < t; i ++){ in[i] = sc.nextBigInteger(); } for(int i = 0; i < t; i ++){ int s = total(in[i]); System.out.println(s); } } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
bbfd62d4db4de8c769eb62d36bec150e
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
import java.util.*; public class function { public static void main(String args[]){ Scanner sc = new Scanner (System.in); int t = sc.nextInt(); while (t-- > 0){ int count=0; String n = sc.next(); System.out.println(n.length()); } } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
ec7baf4e1300033564917c3d5ca805e4
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
//package codeforcesEC99; import java.util.Scanner; public class A { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); StringBuilder answer = new StringBuilder(); int t = sc.nextInt(); sc.nextLine(); while(t-->0) { String s = sc.nextLine(); answer.append(s.length() + "\n"); } System.out.println(answer); sc.close(); } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
27c2c55a210c47cad7b09e18e9548b3e
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.PriorityQueue; import java.util.Stack; import java.util.StringTokenizer; public class Skaba { BufferedReader br; StringTokenizer st; public Skaba() { br = new BufferedReader(new InputStreamReader(System.in)); } public static void main(String[] args) { Skaba r = new Skaba(); int maara = r.nextInt(); for (int i = 0; i < maara; i++) { System.out.println(check(r.nextLine())); } } public static long check(String k) { StringBuilder build = new StringBuilder().append(k).reverse(); int firstZero = 0; return build.toString().length(); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException 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 str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
f48d572c77c2d4445f8bc62931cf986c
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
import java.io.*; import java.util.*; public class bye { static class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } String next() { // reads in the next string while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { // reads in the next int return Integer.parseInt(next()); } public long nextLong() { // reads in the next long return Long.parseLong(next()); } public double nextDouble() { // reads in the next double return Double.parseDouble(next()); } } static InputReader r = new InputReader(System.in); static PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) { int t = r.nextInt(); for (int i = 0; i <= t - 1; i ++) { String n = r.next(); pw.println(n.length()); } pw.close(); } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
0920370c97371a3317721f415b571f3c
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
import java.util.*; public class Test { public static void main(String[] args) { Scanner in=new Scanner (System.in); int t=in.nextInt(); for (int i = 0; i < t; i++) { String s=in.next(); System.out.println(s.length()); } } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
de0e06861b2ae7b94ee2f5f32facdba7
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
import java.io.*; import java.util.*; public class stf { public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int t=0; t=Integer.parseInt(br.readLine()); while(t-->0) { String a=br.readLine().trim(); System.out.println(a.length()); } } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
05fd54d660c73f2ed0ed2c5264e942f8
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main { InputStream is; PrintWriter out; String INPUT = ""; void solve(int TC) throws Exception { pn(ns().length()); } boolean TestCases = true; public static void main(String[] args) throws Exception { new Main().run(); } void holds(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");} static void dbg(Object... o){System.err.println(Arrays.deepToString(o));} void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); int T = TestCases ? ni() : 1; for(int t=1;t<=T;t++) solve(t); out.flush(); if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms"); } void p(Object o) { out.print(o); } void pn(Object o) { out.println(o); } void pni(Object o) { out.println(o);out.flush(); } 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(); } } 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(); } } double nd() { return Double.parseDouble(ns()); } char nc() { return (char)skip(); } int BUF_SIZE = 1024 * 8; byte[] inbuf = new byte[BUF_SIZE]; int lenbuf = 0, ptrbuf = 0; 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++]; } boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } 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); } void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
7a76df80d7e16e8db9f79133bc437ca9
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); int t; String s; t = sc.nextInt(); for (int i = 1; i <= t; i++) { s = sc.next(); System.out.println(s.length()); } } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
65b96174c8f1f141fe8584ca0df21506
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner in=new Scanner(System.in); int t=in.nextInt(); in.nextLine(); for(int z=0;z<t;z++) { String n=in.nextLine(); long sum=n.length(); System.out.println(sum); } } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output
PASSED
bfdf6e9ca0f083f1756e0ef398d7da10
train_000.jsonl
1606746900
Let's define a function $$$f(x)$$$ ($$$x$$$ is a positive integer) as follows: write all digits of the decimal representation of $$$x$$$ backwards, then get rid of the leading zeroes. For example, $$$f(321) = 123$$$, $$$f(120) = 21$$$, $$$f(1000000) = 1$$$, $$$f(111) = 111$$$.Let's define another function $$$g(x) = \dfrac{x}{f(f(x))}$$$ ($$$x$$$ is a positive integer as well).Your task is the following: for the given positive integer $$$n$$$, calculate the number of different values of $$$g(x)$$$ among all numbers $$$x$$$ such that $$$1 \le x \le n$$$.
256 megabytes
import java.util.Scanner; public class Always_Newbie { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int iop=0;iop<t;iop++) { String s = sc.next(); System.out.println(s.length()); } } }
Java
["5\n4\n37\n998244353\n1000000007\n12345678901337426966631415"]
2 seconds
["1\n2\n9\n10\n26"]
NoteExplanations for the two first test cases of the example: if $$$n = 4$$$, then for every integer $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$; if $$$n = 37$$$, then for some integers $$$x$$$ such that $$$1 \le x \le n$$$, $$$\dfrac{x}{f(f(x))} = 1$$$ (for example, if $$$x = 23$$$, $$$f(f(x)) = 23$$$,$$$\dfrac{x}{f(f(x))} = 1$$$); and for other values of $$$x$$$, $$$\dfrac{x}{f(f(x))} = 10$$$ (for example, if $$$x = 30$$$, $$$f(f(x)) = 3$$$, $$$\dfrac{x}{f(f(x))} = 10$$$). So, there are two different values of $$$g(x)$$$.
Java 11
standard input
[ "constructive algorithms", "number theory", "math" ]
ea011f93837fdf985f7eaa7a43e22cc8
The first line contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of one line containing one integer $$$n$$$ ($$$1 \le n &lt; 10^{100}$$$). This integer is given without leading zeroes.
null
For each test case, print one integer — the number of different values of the function $$$g(x)$$$, if $$$x$$$ can be any integer from $$$[1, n]$$$.
standard output