exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
βŒ€
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
listlengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
βŒ€
difficulty
int64
-1
3.5k
βŒ€
prob_desc_output_spec
stringlengths
17
1.47k
βŒ€
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
1b8ab2a2ae8e192f327f8f6283cd985a
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class code2 { InputStream is; PrintWriter out; ArrayList<Integer> al[]; long mod=(int)Math.pow(10,9)+7; void solve() { int n=ni(); int a[]=na(n); int max=100000; long freq[]=new long[max+1]; for(int i=0;i<n;i++) freq[a[i]]++; long ans[]=new long[max+1]; for(int i=max;i>=1;i--) { long total=0,sub=0; for(int j=i;j<=max;j+=i) { total+=freq[j]; sub+=ans[j]; sub%=mod; } //System.out.println(total+" "+sub+" "+i); ans[i]=(pow(2,total,mod)-1-sub+mod)%mod; } out.println(ans[1]); } boolean isPrime(int num) { for(int i=2;i*i<=num;i++) { if(num%i==0) return false; } return true; } public static void mergeSort(int[] arr, int l ,int r){ if((r-l)>=1){ int mid = (l+r)/2; mergeSort(arr,l,mid); mergeSort(arr,mid+1,r); merge(arr,l,r,mid); } } public static void merge(int arr[], int l, int r, int mid){ int n1 = (mid-l+1), n2 = (r-mid); int left[] = new int[n1]; int right[] = new int[n2]; for(int i =0 ;i<n1;i++) left[i] = arr[l+i]; for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i]; int i =0, j =0, k = l; while(i<n1 && j<n2){ if(left[i]>right[j]){ arr[k++] = right[j++]; } else{ arr[k++] = left[i++]; } } while(i<n1) arr[k++] = left[i++]; while(j<n2) arr[k++] = right[j++]; } public static void mergeSort(long[] arr, int l ,int r){ if((r-l)>=1){ int mid = (l+r)/2; mergeSort(arr,l,mid); mergeSort(arr,mid+1,r); merge(arr,l,r,mid); } } public static void merge(long arr[], int l, int r, int mid){ int n1 = (mid-l+1), n2 = (r-mid); long left[] = new long[n1]; long right[] = new long[n2]; for(int i =0 ;i<n1;i++) left[i] = arr[l+i]; for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i]; int i =0, j =0, k = l; while(i<n1 && j<n2){ if(left[i]>right[j]){ arr[k++] = right[j++]; } else{ arr[k++] = left[i++]; } } while(i<n1) arr[k++] = left[i++]; while(j<n2) arr[k++] = right[j++]; } static class Pair implements Comparable<Pair>{ int x,y,k,i; Pair (int x,int y){ this.x=x; this.y=y; } public int compareTo(Pair o) { return this.y-o.y; } public boolean equals(Object o) { if (o instanceof Pair) { Pair p = (Pair)o; return p.x == x && p.y == y && p.k==k; } return false; } @Override public String toString() { return "("+x + " " + y +" "+k+" "+i+" )"; } } public static boolean isPal(String s){ for(int i=0, j=s.length()-1;i<=j;i++,j--){ if(s.charAt(i)!=s.charAt(j)) return false; } return true; } public static String rev(String s){ StringBuilder sb=new StringBuilder(s); sb.reverse(); return sb.toString(); } public static long gcd(long x,long y){ if(x%y==0) return y; else return gcd(y,x%y); } public static int gcd(int x,int y){ if(x%y==0) return y; else return gcd(y,x%y); } public static long gcdExtended(long a,long b,long[] x){ if(a==0){ x[0]=0; x[1]=1; return b; } long[] y=new long[2]; long gcd=gcdExtended(b%a, a, y); x[0]=y[1]-(b/a)*y[0]; x[1]=y[0]; return gcd; } public static int abs(int a,int b){ return (int)Math.abs(a-b); } public static long abs(long a,long b){ return (long)Math.abs(a-b); } public static int max(int a,int b){ if(a>b) return a; else return b; } public static int min(int a,int b){ if(a>b) return b; else return a; } public static long max(long a,long b){ if(a>b) return a; else return b; } public static long min(long a,long b){ if(a>b) return b; else return a; } public static long pow(long n,long p,long m){ long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; if(result>=m) result%=m; p >>=1; n*=n; if(n>=m) n%=m; } return result; } public static long pow(long n,long p){ long result = 1; if(p==0) return 1; if (p==1) return n; while(p!=0) { if(p%2==1) result *= n; p >>=1; n*=n; } return result; } public static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } void run() throws Exception { is = System.in; out = new PrintWriter(System.out); solve(); out.flush(); } public static void main(String[] args) throws Exception { new Thread(null, new Runnable() { public void run() { try { new code2().run(); } catch (Exception e) { e.printStackTrace(); } } }, "1", 1 << 26).start(); //new code2().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
c6858971b7c5f48f86abc29601499671
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
//package ECR20; import java.util.*; public class F803 { static final int MODULO = (int)1e9 + 7; static final int MAX = (int)1e5 + 5; static int n; static int f[] = new int[MAX]; static int mu[] = new int[MAX]; /** * * @param a 0 <= a < MODULO * @param b 0 <= b < MODULO * @return sum modulo MODULO */ static int add(int a, int b) { return (a+b) % MODULO; } /** * * @param a 0 <= a < MODULO * @param b 0 <= b < MODULO * @return difference modulo MODULO */ static int sub(int a, int b) { return (a - b + MODULO) % MODULO; } /** * * @param a 0 <= a < MODULO * @param b 0 <= b < MODULO * @return product modulo MODULO */ static int mult(int a, int b) { long prod = a; prod *= b; prod %= MODULO; return (int) ((prod + MODULO) % MODULO); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); Arrays.fill(f, 1); int foo; for(int i = 0; i < n; ++i) { foo = sc.nextInt(); f[foo] = add(f[foo], f[foo]); } for(int i = 1; i < MAX; ++i) { for(int j = i * 2; j < MAX; j += i) { f[i] = mult(f[i], f[j]); } } mu[1] = 1; for(int i = 1; i < MAX; ++i) { for(int j = i * 2; j < MAX; j += i) { mu[j] = sub(mu[j], mu[i]); } } int ans = 0; for(int i = 1; i < MAX; ++i) { ans = add(ans, mult(mu[i], f[i] - 1)); } System.out.println(ans); } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
da1ec22c5a824fec0675d228173794cb
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.io.*; import java.util.*; public class Main implements Runnable { FastReader scn; PrintWriter out; String INPUT = ""; void solve() { int n = scn.nextInt(), max = 100000 + 1, mod = 1000_000_007; int[] arr = new int[max]; for (int i = 0; i < n; i++) { arr[scn.nextInt()]++; } int[] count = new int[max]; for (int i = 1; i < max; i++) { for (int j = i; j < max; j += i) { count[i] += arr[j]; } } long[] f = new long[max]; for (int i = 1; i < max; i++) { f[i] = pow(2, count[i], mod) - 1; } int[] mob = mobius(max); long ans = 0; for (int i = 1; i < max; i++) { ans += f[i] * mob[i]; } out.println((ans % mod + mod) % mod); } int[] mobius(int n) { int[] arr = new int[n + 1]; arr[1] = 1; for (int i = 1; i <= n; i++) { if (arr[i] == 0) { continue; } for (int j = 2 * i; j <= n; j += i) { arr[j] -= arr[i]; } } return arr; } long pow(long a, long x, long m) { long rv = 1; while (x != 0) { if ((x & 1) == 1) { rv = (rv * a) % m; } a = (a * a) % m; x = x >> 1; } return rv; } public void run() { long time = System.currentTimeMillis(); boolean oj = System.getProperty("ONLINE_JUDGE") != null; out = new PrintWriter(System.out); scn = new FastReader(oj); solve(); out.flush(); if (!oj) { System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" })); } } public static void main(String[] args) { new Thread(null, new Main(), "Main", 1 << 26).start(); } class FastReader { InputStream is; public FastReader(boolean onlineJudge) { is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes()); } byte[] inbuf = new byte[1024]; public 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; } double nextDouble() { return Double.parseDouble(next()); } char nextChar() { return (char) skip(); } String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nextLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } char[] next(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n && !(isSpaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } long nextLong() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } char[][] nextMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = next(m); return map; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] next2DInt(int n, int m) { int[][] arr = new int[n][]; for (int i = 0; i < n; i++) { arr[i] = nextIntArray(m); } return arr; } long[][] next2DLong(int n, int m) { long[][] arr = new long[n][]; for (int i = 0; i < n; i++) { arr[i] = nextLongArray(m); } return arr; } int[] shuffle(int[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); arr[i] = arr[i] ^ arr[j]; arr[j] = arr[i] ^ arr[j]; arr[i] = arr[i] ^ arr[j]; } return arr; } int[] uniq(int[] arr) { Arrays.sort(arr); int[] rv = new int[arr.length]; int pos = 0; rv[pos++] = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] != arr[i - 1]) { rv[pos++] = arr[i]; } } return Arrays.copyOf(rv, pos); } } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
e764149f4889cf856dea6e4b16455f8a
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Omar Yasser */ 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); TaskF solver = new TaskF(); solver.solve(1, in, out); out.close(); } static class TaskF { static long modular_exponentiation(long a, long b, long c) { long ans = 1L; while (b != 0) { if ((b & (1)) == 1) ans = (ans * a) % c; a = (a * a) % c; b >>= 1L; } return ans; } public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = in.nextInt(); int mod = (int) 1e9 + 7; int MAX = (int) 1e5; int[] pow = new int[MAX + 1]; for (int i = 0; i <= MAX; i++) pow[i] = (int) modular_exponentiation(2, i, mod) - 1; int[] cntMultiples = new int[MAX + 1]; for (int i = 0; i < n; i++) { int num = arr[i]; cntMultiples[1]++; if (num != 1) cntMultiples[num]++; for (int j = 2; j * j <= num; j++) { if (num % j == 0) { cntMultiples[j]++; if (num / j != j) cntMultiples[num / j]++; } } } int[] res = new int[MAX + 1]; for (int gcd = MAX; gcd >= 1; gcd--) { int resHere = pow[cntMultiples[gcd]]; for (int times = 2; ; times++) { if ((long) gcd * times > MAX) break; resHere = resHere - res[gcd * times]; if (resHere < 0) { resHere += mod; } } res[gcd] = ((resHere % mod) + mod) % mod; } out.println(res[1]); } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader f) { br = new BufferedReader(f); } public String next() { while (st == null || !st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
97f9ad74329127789b5854ce0045fb4f
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.util.*; import java.io.*; import static java.lang.Math.*; public class MainS { static final long MOD = 1_000_000_007, INF = 1_000_000_000_000_000_000L; static final int INf = 1_000_000_000; static FastReader reader; static PrintWriter writer; public static void main(String[] args) { Thread t = new Thread(null, new O(), "Integer.MAX_VALUE", 100000000); t.start(); } static class O implements Runnable { public void run() { try { magic(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } } public 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 long two[] = new long[100001]; static void magic() throws IOException { reader = new FastReader(); writer = new PrintWriter(System.out, true); two[0] = 1; for(int i=1;i<=100000;++i) { two[i] = two[i-1] + two[i-1]; if(two[i]>=MOD) { two[i]-=MOD; } } long no_of_subsequences_having_gcd_i[] = new long[100001]; int number_of_multiples[] = new int[100001]; int freq[] = new int[100001]; int n = reader.nextInt(); for(int i=0;i<n;++i) { ++freq[reader.nextInt()]; } for(int i=1;i<=100000;++i) { for(int j=i;j<=100000;j+=i) { number_of_multiples[i] += freq[j]; } } for(int i=100000;i>0;--i) { no_of_subsequences_having_gcd_i[i] = (two[number_of_multiples[i]] - 1 + MOD)%MOD; long invalid = 0; for(int j=i+i;j<=100000;j+=i) { invalid+=no_of_subsequences_having_gcd_i[j]; if(invalid>=MOD) { invalid-=MOD; } } no_of_subsequences_having_gcd_i[i] = (no_of_subsequences_having_gcd_i[i] - invalid + MOD)%MOD; } // writer.println("No of subsequences having GCD i array: "); // for(int i=1;i<=10;++i) { // writer.print(no_of_subsequences_having_gcd_i[i]+" "); // } // writer.println(); writer.println(no_of_subsequences_having_gcd_i[1]); } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
25c4117a2aa0d7e5f664b2e6501203fb
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); TaskF solver = new TaskF(); solver.solve(1, in, out); out.close(); } } static class TaskF { public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); Modular mod = new Modular(1e9 + 7); Power pow = new Power(mod); int limit = 1000000; int[] dp = new int[limit + 1]; int[] cnts = new int[limit + 1]; for (int i = 0; i < n; i++) { cnts[in.readInt()]++; } for (int i = 1; i <= limit; i++) { int cnt = 0; for (int j = i; j <= limit; j += i) { cnt += cnts[j]; } dp[i] = mod.subtract(pow.pow(2, cnt), 1); } for (int i = limit; i >= 1; i--) { for (int j = i + i; j <= limit; j += i) { dp[i] = mod.subtract(dp[i], dp[j]); } } out.println(dp[1]); } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } } static class Modular { int m; public Modular(int m) { this.m = m; } public Modular(long m) { this.m = (int) m; if (this.m != m) { throw new IllegalArgumentException(); } } public Modular(double m) { this.m = (int) m; if (this.m != m) { throw new IllegalArgumentException(); } } public int valueOf(int x) { x %= m; if (x < 0) { x += m; } return x; } public int valueOf(long x) { x %= m; if (x < 0) { x += m; } return (int) x; } public int subtract(int x, int y) { return valueOf(x - y); } public String toString() { return "mod " + m; } } static class FastOutput implements AutoCloseable, Closeable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput println(int c) { cache.append(c).append('\n'); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static class Power { final Modular modular; public Power(Modular modular) { this.modular = modular; } public int pow(int x, long n) { if (n == 0) { return modular.valueOf(1); } long r = pow(x, n >> 1); r = modular.valueOf(r * r); if ((n & 1) == 1) { r = modular.valueOf(r * x); } return (int) r; } } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
e295bd53b631a38337054981cf942933
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.util.Scanner; public class Main { public static void main(String args[]) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = 100000; int p = 1000000007; int c[] = new int[m + 1]; int s[] = new int[m + 1]; int b[] = new int[m + 1]; for (int i = 0; i < n; i++) { c[in.nextInt()]++; } b[0] = 1; for (int i = 1; i <= m; i++) { b[i] = b[i - 1] * 2 % p; for (int j = i; j <= m; j += i) { s[i] += c[j]; } } int v[] = new int[m + 1]; int u[] = new int[m + 1]; for (int i = 2; i <= m; i++) { if (v[i] > 0) { continue; } for (int j = i; j <= m; j += i) { v[j] = i; } } u[1] = 1; for (int i = 2; i <= m; i++) { if (v[i] == v[i / v[i]]) { u[i] = 0; } else { u[i] = -u[i / v[i]]; } } int z = 0; for (int i = 1; i <= m; i++) { z += u[i] * (b[s[i]] - 1); if (z >= p) { z -= p; } if (z < 0) { z += p; } } System.out.println(z); } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
5034ddd165697f51ac39bed5e87675dd
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.util.*; import java.io.*; public class EdB { static ArrayList<Integer> primes; public static void main(String[] args) throws Exception{ long num = 1000000007; // TODO Auto-generated method stub BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(bf.readLine()); StringTokenizer st = new StringTokenizer(bf.readLine()); int[] array = new int[n]; int[] freq = new int[100001]; for(int j = 0;j<n;j++){ array[j] = Integer.parseInt(st.nextToken()); freq[array[j]]++; } long[] dp = new long[100001]; for(long gcd = 100000;gcd>=1;gcd--){ long count = freq[(int)(gcd)]; long subtract = 0; for(long k = 2L*gcd;k<=100000;k+=gcd){ count+=freq[(int)(k)]; subtract+=dp[(int)(k)]; } dp[(int)(gcd)] = ((power(2, count, num)-1-subtract)%num+num)%num; } out.println(dp[1]); out.close(); } public static int power(long x, long y, long mod){ long ans = 1; while(y>0){ if (y%2==1) ans = (ans*x)%mod; x = (x*x)%mod; y/=2; } return (int)(ans); } public static void sieveOfEratosthenes(int n) { boolean prime[] = new boolean[n+1]; for(int i=0;i<n;i++) prime[i] = true; for(int p = 2; p*p <=n; p++) { if(prime[p]){ for(int i = p*p; i <= n; i += p) prime[i] = false; } } for(int i = 3; i <= n; i++){ if(prime[i] == true) primes.add(i); } } } //StringJoiner sj = new StringJoiner(" "); //sj.add(strings) //sj.toString() gives string of those stuff w spaces or whatever that sequence is
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
e125da02272570cb04d37c9fc40f4078
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskF solver = new TaskF(); solver.solve(1, in, out); out.close(); } static class TaskF { public static final int MAXN = (int) 1e5; int np; int[] div = new int[MAXN]; int[] prime = new int[100]; int nprime = 0; int[] lprime = new int[100]; int[] lcnt = new int[100]; int ndiv; void getDiv(int n) { np = 0; for (int i = 0; i < nprime; ++i) { if (n % prime[i] == 0) { lprime[np] = prime[i]; lcnt[np] = 0; while (n % prime[i] == 0) { n /= prime[i]; lcnt[np]++; } np++; if (n == 1) break; } } if (n > 1) { lprime[np] = n; lcnt[np] = 1; np++; } ndiv = 0; rec(1, 0); //for(int i = 0; i < ndiv; ++i) System.err.println(div[i]); } private void rec(int mul, int id) { if (mul != 1) { div[ndiv++] = mul; } for (int i = id; i < np; ++i) { int lastMul = 1; for (int mu = 1; mu <= lcnt[i]; mu++) { lastMul *= lprime[i]; rec(mul * lastMul, i + 1); } } } public void solve(int testNumber, InputReader in, PrintWriter out) { int sqrt = (int) Math.sqrt(MAXN) + 1; nprime = 0; for (int i = 2; i <= sqrt; ++i) if (IntMath.isPrime(i)) { prime[nprime++] = i; } int n = in.nextInt(); int[] cnt = new int[MAXN + 1]; for (int i = 0; i < n; ++i) { int val = in.nextInt(); getDiv(val); for (int j = 0; j < ndiv; ++j) { cnt[div[j]]++; } } int[] pow2 = new int[MAXN + 1]; pow2[0] = 1; for (int i = 1; i < MAXN + 1; ++i) { pow2[i] = Mod.mulMod(pow2[i - 1], 2); } int[] f = new int[MAXN + 1]; for (int i = 0; i < MAXN + 1; ++i) { f[i] = Mod.subMod(pow2[cnt[i]], 1); } int su = 0; for (int i = MAXN; i > 1; --i) if (f[i] != 0) { getDiv(i); for (int j = 0; j < ndiv; ++j) if (div[j] != i) { f[div[j]] = Mod.subMod(f[div[j]], f[i]); } su = Mod.addMod(su, f[i]); } out.println(Mod.subMod(Mod.subMod(pow2[n], 1), su)); } } static final class Longs { private Longs() { } public static int compare(long a, long b) { return (a < b) ? -1 : ((a > b) ? 1 : 0); } } static class Mod { public static final long MOD = 1000000007L; public static final boolean DEBUG = false; public static int addMod(int a, int b) { if (DEBUG) return a + b; while (a < 0) a += MOD; while (b < 0) b += MOD; return (int) (((long) a + (long) b) % MOD); } public static int subMod(int a, int b) { if (DEBUG) return a - b; while (a < 0) a += MOD; while (b < 0) b += MOD; long temp = (long) a - (long) b; while (temp < 0) temp += MOD; return (int) temp; } public static int mulMod(int a, int b) { if (DEBUG) return a * b; while (a < 0) a += MOD; while (b < 0) b += MOD; return (int) (((long) a) * ((long) b) % MOD); } } static final class MathPreconditions { static long checkNonNegative(String role, long x) { if (x < 0) { throw new IllegalArgumentException(role + " (" + x + ") must be >= 0"); } return x; } private MathPreconditions() { } } static final class IntMath { public static boolean isPrime(int n) { return LongMath.isPrime(n); } private IntMath() { } } static final class UnsignedLongs { private UnsignedLongs() { } private static long flip(long a) { return a ^ Long.MIN_VALUE; } public static int compare(long a, long b) { return Longs.compare(flip(a), flip(b)); } public static long remainder(long dividend, long divisor) { if (divisor < 0) { // i.e., divisor >= 2^63: if (compare(dividend, divisor) < 0) { return dividend; // dividend < divisor } else { return dividend - divisor; // dividend >= divisor } } // Optimization - use signed modulus if dividend < 2^63 if (dividend >= 0) { return dividend % divisor; } /* * Otherwise, approximate the quotient, check, and correct if necessary. Our approximation is * guaranteed to be either exact or one less than the correct value. This follows from the fact * that floor(floor(x)/i) == floor(x/i) for any real x and integer i != 0. The proof is not * quite trivial. */ long quotient = ((dividend >>> 1) / divisor) << 1; long rem = dividend - quotient * divisor; return rem - (compare(rem, divisor) >= 0 ? divisor : 0); } } static final class LongMath { static final long FLOOR_SQRT_MAX_LONG = 3037000499L; private static final int SIEVE_30 = ~((1 << 1) | (1 << 7) | (1 << 11) | (1 << 13) | (1 << 17) | (1 << 19) | (1 << 23) | (1 << 29)); private static final long[][] millerRabinBaseSets = { {291830, 126401071349994536L}, {885594168, 725270293939359937L, 3569819667048198375L}, {273919523040L, 15, 7363882082L, 992620450144556L}, {47636622961200L, 2, 2570940, 211991001, 3749873356L}, { 7999252175582850L, 2, 4130806001517L, 149795463772692060L, 186635894390467037L, 3967304179347715805L }, { 585226005592931976L, 2, 123635709730000L, 9233062284813009L, 43835965440333360L, 761179012939631437L, 1263739024124850375L }, {Long.MAX_VALUE, 2, 325, 9375, 28178, 450775, 9780504, 1795265022} }; public static boolean isPrime(long n) { if (n < 2) { MathPreconditions.checkNonNegative("n", n); return false; } if (n == 2 || n == 3 || n == 5 || n == 7 || n == 11 || n == 13) { return true; } if ((SIEVE_30 & (1 << (n % 30))) != 0) { return false; } if (n % 7 == 0 || n % 11 == 0 || n % 13 == 0) { return false; } if (n < 17 * 17) { return true; } for (long[] baseSet : millerRabinBaseSets) { if (n <= baseSet[0]) { for (int i = 1; i < baseSet.length; i++) { if (!LongMath.MillerRabinTester.test(baseSet[i], n)) { return false; } } return true; } } throw new AssertionError(); } private LongMath() { } private enum MillerRabinTester { /** * Works for inputs ≀ FLOOR_SQRT_MAX_LONG. */ SMALL { long mulMod(long a, long b, long m) { /* * NOTE(lowasser, 2015-Feb-12): Benchmarks suggest that changing this to * UnsignedLongs.remainder and increasing the threshold to 2^32 doesn't pay for itself, and * adding another enum constant hurts performance further -- I suspect because bimorphic * implementation is a sweet spot for the JVM. */ return (a * b) % m; } long squareMod(long a, long m) { return (a * a) % m; } }, /** * Works for all nonnegative signed longs. */ LARGE { /** Returns (a + b) mod m. Precondition: {@code 0 <= a}, {@code b < m < 2^63}. */ private long plusMod(long a, long b, long m) { return (a >= m - b) ? (a + b - m) : (a + b); } /** * Returns (a * 2^32) mod m. a may be any unsigned long. */ private long times2ToThe32Mod(long a, long m) { int remainingPowersOf2 = 32; do { int shift = Math.min(remainingPowersOf2, Long.numberOfLeadingZeros(a)); // shift is either the number of powers of 2 left to multiply a by, or the biggest shift // possible while keeping a in an unsigned long. a = UnsignedLongs.remainder(a << shift, m); remainingPowersOf2 -= shift; } while (remainingPowersOf2 > 0); return a; } long mulMod(long a, long b, long m) { long aHi = a >>> 32; // < 2^31 long bHi = b >>> 32; // < 2^31 long aLo = a & 0xFFFFFFFFL; // < 2^32 long bLo = b & 0xFFFFFFFFL; // < 2^32 /* * a * b == aHi * bHi * 2^64 + (aHi * bLo + aLo * bHi) * 2^32 + aLo * bLo. * == (aHi * bHi * 2^32 + aHi * bLo + aLo * bHi) * 2^32 + aLo * bLo * * We carry out this computation in modular arithmetic. Since times2ToThe32Mod accepts any * unsigned long, we don't have to do a mod on every operation, only when intermediate * results can exceed 2^63. */ long result = times2ToThe32Mod(aHi * bHi /* < 2^62 */, m); // < m < 2^63 result += aHi * bLo; // aHi * bLo < 2^63, result < 2^64 if (result < 0) { result = UnsignedLongs.remainder(result, m); } // result < 2^63 again result += aLo * bHi; // aLo * bHi < 2^63, result < 2^64 result = times2ToThe32Mod(result, m); // result < m < 2^63 return plusMod( result, UnsignedLongs.remainder(aLo * bLo /* < 2^64 */, m), m); } long squareMod(long a, long m) { long aHi = a >>> 32; // < 2^31 long aLo = a & 0xFFFFFFFFL; // < 2^32 /* * a^2 == aHi^2 * 2^64 + aHi * aLo * 2^33 + aLo^2 * == (aHi^2 * 2^32 + aHi * aLo * 2) * 2^32 + aLo^2 * We carry out this computation in modular arithmetic. Since times2ToThe32Mod accepts any * unsigned long, we don't have to do a mod on every operation, only when intermediate * results can exceed 2^63. */ long result = times2ToThe32Mod(aHi * aHi /* < 2^62 */, m); // < m < 2^63 long hiLo = aHi * aLo * 2; if (hiLo < 0) { hiLo = UnsignedLongs.remainder(hiLo, m); } // hiLo < 2^63 result += hiLo; // result < 2^64 result = times2ToThe32Mod(result, m); // result < m < 2^63 return plusMod( result, UnsignedLongs.remainder(aLo * aLo /* < 2^64 */, m), m); } },; static boolean test(long base, long n) { // Since base will be considered % n, it's okay if base > FLOOR_SQRT_MAX_LONG, // so long as n <= FLOOR_SQRT_MAX_LONG. return ((n <= FLOOR_SQRT_MAX_LONG) ? SMALL : LARGE).testWitness(base, n); } abstract long mulMod(long a, long b, long m); abstract long squareMod(long a, long m); private long powMod(long a, long p, long m) { long res = 1; for (; p != 0; p >>= 1) { if ((p & 1) != 0) { res = mulMod(res, a, m); } a = squareMod(a, m); } return res; } private boolean testWitness(long base, long n) { int r = Long.numberOfTrailingZeros(n - 1); long d = (n - 1) >> r; base %= n; if (base == 0) { return true; } // Calculate a := base^d mod n. long a = powMod(base, d, n); // n passes this test if // base^d = 1 (mod n) // or base^(2^j * d) = -1 (mod n) for some 0 <= j < r. if (a == 1) { return true; } int j = 0; while (a != n - 1) { if (++j == r) { return false; } a = squareMod(a, n); } return true; } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
006348744eabad86d58af0d003085566
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskF solver = new TaskF(); solver.solve(1, in, out); out.close(); } static class TaskF { public static final int MAXN = (int) 1e5; int np; int[] div = new int[MAXN]; int[] prime = new int[100]; int nprime = 0; int[] lprime = new int[100]; int[] lcnt = new int[100]; int ndiv; void getDiv(int n) { np = 0; for (int i = 0; i < nprime; ++i) { if (n % prime[i] == 0) { lprime[np] = prime[i]; lcnt[np] = 0; while (n % prime[i] == 0) { n /= prime[i]; lcnt[np]++; } np++; if (n == 1) break; } } if (n > 1) { lprime[np] = n; lcnt[np] = 1; np++; } ndiv = 0; rec(1, 0); //for(int i = 0; i < ndiv; ++i) System.err.println(div[i]); } private void rec(int mul, int id) { if (mul != 1) { div[ndiv++] = mul; } for (int i = id; i < np; ++i) { int lastMul = 1; for (int mu = 1; mu <= lcnt[i]; mu++) { lastMul *= lprime[i]; rec(mul * lastMul, i + 1); } } } public void solve(int testNumber, InputReader in, PrintWriter out) { int sqrt = (int) Math.sqrt(MAXN) + 1; nprime = 0; for (int i = 2; i <= sqrt; ++i) if (IntMath.isPrime(i)) { prime[nprime++] = i; } int n = in.nextInt(); int[] cnt = new int[MAXN + 1]; for (int i = 0; i < n; ++i) { int val = in.nextInt(); getDiv(val); for (int j = 0; j < ndiv; ++j) { cnt[div[j]]++; } } int[] pow2 = new int[MAXN + 1]; pow2[0] = 1; for (int i = 1; i < MAXN + 1; ++i) { pow2[i] = Mod.mulMod(pow2[i - 1], 2); } int[] f = new int[MAXN + 1]; for (int i = 0; i < MAXN + 1; ++i) { f[i] = pow2[cnt[i]] - 1; } int su = 0; for (int i = MAXN; i > 1; --i) if (f[i] != 0) { getDiv(i); for (int j = 0; j < ndiv; ++j) if (div[j] != i) { f[div[j]] = Mod.subMod(f[div[j]], f[i]); } su = Mod.addMod(su, f[i]); } out.println(Mod.subMod(Mod.subMod(pow2[n], 1), su)); } } static final class UnsignedLongs { private UnsignedLongs() { } private static long flip(long a) { return a ^ Long.MIN_VALUE; } public static int compare(long a, long b) { return Longs.compare(flip(a), flip(b)); } public static long remainder(long dividend, long divisor) { if (divisor < 0) { // i.e., divisor >= 2^63: if (compare(dividend, divisor) < 0) { return dividend; // dividend < divisor } else { return dividend - divisor; // dividend >= divisor } } // Optimization - use signed modulus if dividend < 2^63 if (dividend >= 0) { return dividend % divisor; } /* * Otherwise, approximate the quotient, check, and correct if necessary. Our approximation is * guaranteed to be either exact or one less than the correct value. This follows from the fact * that floor(floor(x)/i) == floor(x/i) for any real x and integer i != 0. The proof is not * quite trivial. */ long quotient = ((dividend >>> 1) / divisor) << 1; long rem = dividend - quotient * divisor; return rem - (compare(rem, divisor) >= 0 ? divisor : 0); } } static class Mod { public static final long MOD = 1000000007L; public static final boolean DEBUG = false; public static int addMod(int a, int b) { if (DEBUG) return a + b; while (a < 0) a += MOD; while (b < 0) b += MOD; return (int) (((long) a + (long) b) % MOD); } public static int subMod(int a, int b) { if (DEBUG) return a - b; while (a < 0) a += MOD; while (b < 0) b += MOD; long temp = (long) a - (long) b; while (temp < 0) temp += MOD; return (int) temp; } public static int mulMod(int a, int b) { if (DEBUG) return a * b; while (a < 0) a += MOD; while (b < 0) b += MOD; return (int) (((long) a) * ((long) b) % MOD); } } static final class IntMath { public static boolean isPrime(int n) { return LongMath.isPrime(n); } private IntMath() { } } static final class LongMath { static final long FLOOR_SQRT_MAX_LONG = 3037000499L; private static final int SIEVE_30 = ~((1 << 1) | (1 << 7) | (1 << 11) | (1 << 13) | (1 << 17) | (1 << 19) | (1 << 23) | (1 << 29)); private static final long[][] millerRabinBaseSets = { {291830, 126401071349994536L}, {885594168, 725270293939359937L, 3569819667048198375L}, {273919523040L, 15, 7363882082L, 992620450144556L}, {47636622961200L, 2, 2570940, 211991001, 3749873356L}, { 7999252175582850L, 2, 4130806001517L, 149795463772692060L, 186635894390467037L, 3967304179347715805L }, { 585226005592931976L, 2, 123635709730000L, 9233062284813009L, 43835965440333360L, 761179012939631437L, 1263739024124850375L }, {Long.MAX_VALUE, 2, 325, 9375, 28178, 450775, 9780504, 1795265022} }; public static boolean isPrime(long n) { if (n < 2) { MathPreconditions.checkNonNegative("n", n); return false; } if (n == 2 || n == 3 || n == 5 || n == 7 || n == 11 || n == 13) { return true; } if ((SIEVE_30 & (1 << (n % 30))) != 0) { return false; } if (n % 7 == 0 || n % 11 == 0 || n % 13 == 0) { return false; } if (n < 17 * 17) { return true; } for (long[] baseSet : millerRabinBaseSets) { if (n <= baseSet[0]) { for (int i = 1; i < baseSet.length; i++) { if (!LongMath.MillerRabinTester.test(baseSet[i], n)) { return false; } } return true; } } throw new AssertionError(); } private LongMath() { } private enum MillerRabinTester { /** * Works for inputs ≀ FLOOR_SQRT_MAX_LONG. */ SMALL { long mulMod(long a, long b, long m) { /* * NOTE(lowasser, 2015-Feb-12): Benchmarks suggest that changing this to * UnsignedLongs.remainder and increasing the threshold to 2^32 doesn't pay for itself, and * adding another enum constant hurts performance further -- I suspect because bimorphic * implementation is a sweet spot for the JVM. */ return (a * b) % m; } long squareMod(long a, long m) { return (a * a) % m; } }, /** * Works for all nonnegative signed longs. */ LARGE { /** Returns (a + b) mod m. Precondition: {@code 0 <= a}, {@code b < m < 2^63}. */ private long plusMod(long a, long b, long m) { return (a >= m - b) ? (a + b - m) : (a + b); } /** * Returns (a * 2^32) mod m. a may be any unsigned long. */ private long times2ToThe32Mod(long a, long m) { int remainingPowersOf2 = 32; do { int shift = Math.min(remainingPowersOf2, Long.numberOfLeadingZeros(a)); // shift is either the number of powers of 2 left to multiply a by, or the biggest shift // possible while keeping a in an unsigned long. a = UnsignedLongs.remainder(a << shift, m); remainingPowersOf2 -= shift; } while (remainingPowersOf2 > 0); return a; } long mulMod(long a, long b, long m) { long aHi = a >>> 32; // < 2^31 long bHi = b >>> 32; // < 2^31 long aLo = a & 0xFFFFFFFFL; // < 2^32 long bLo = b & 0xFFFFFFFFL; // < 2^32 /* * a * b == aHi * bHi * 2^64 + (aHi * bLo + aLo * bHi) * 2^32 + aLo * bLo. * == (aHi * bHi * 2^32 + aHi * bLo + aLo * bHi) * 2^32 + aLo * bLo * * We carry out this computation in modular arithmetic. Since times2ToThe32Mod accepts any * unsigned long, we don't have to do a mod on every operation, only when intermediate * results can exceed 2^63. */ long result = times2ToThe32Mod(aHi * bHi /* < 2^62 */, m); // < m < 2^63 result += aHi * bLo; // aHi * bLo < 2^63, result < 2^64 if (result < 0) { result = UnsignedLongs.remainder(result, m); } // result < 2^63 again result += aLo * bHi; // aLo * bHi < 2^63, result < 2^64 result = times2ToThe32Mod(result, m); // result < m < 2^63 return plusMod( result, UnsignedLongs.remainder(aLo * bLo /* < 2^64 */, m), m); } long squareMod(long a, long m) { long aHi = a >>> 32; // < 2^31 long aLo = a & 0xFFFFFFFFL; // < 2^32 /* * a^2 == aHi^2 * 2^64 + aHi * aLo * 2^33 + aLo^2 * == (aHi^2 * 2^32 + aHi * aLo * 2) * 2^32 + aLo^2 * We carry out this computation in modular arithmetic. Since times2ToThe32Mod accepts any * unsigned long, we don't have to do a mod on every operation, only when intermediate * results can exceed 2^63. */ long result = times2ToThe32Mod(aHi * aHi /* < 2^62 */, m); // < m < 2^63 long hiLo = aHi * aLo * 2; if (hiLo < 0) { hiLo = UnsignedLongs.remainder(hiLo, m); } // hiLo < 2^63 result += hiLo; // result < 2^64 result = times2ToThe32Mod(result, m); // result < m < 2^63 return plusMod( result, UnsignedLongs.remainder(aLo * aLo /* < 2^64 */, m), m); } },; static boolean test(long base, long n) { // Since base will be considered % n, it's okay if base > FLOOR_SQRT_MAX_LONG, // so long as n <= FLOOR_SQRT_MAX_LONG. return ((n <= FLOOR_SQRT_MAX_LONG) ? SMALL : LARGE).testWitness(base, n); } abstract long mulMod(long a, long b, long m); abstract long squareMod(long a, long m); private long powMod(long a, long p, long m) { long res = 1; for (; p != 0; p >>= 1) { if ((p & 1) != 0) { res = mulMod(res, a, m); } a = squareMod(a, m); } return res; } private boolean testWitness(long base, long n) { int r = Long.numberOfTrailingZeros(n - 1); long d = (n - 1) >> r; base %= n; if (base == 0) { return true; } // Calculate a := base^d mod n. long a = powMod(base, d, n); // n passes this test if // base^d = 1 (mod n) // or base^(2^j * d) = -1 (mod n) for some 0 <= j < r. if (a == 1) { return true; } int j = 0; while (a != n - 1) { if (++j == r) { return false; } a = squareMod(a, n); } return true; } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } static final class MathPreconditions { static long checkNonNegative(String role, long x) { if (x < 0) { throw new IllegalArgumentException(role + " (" + x + ") must be >= 0"); } return x; } private MathPreconditions() { } } static final class Longs { private Longs() { } public static int compare(long a, long b) { return (a < b) ? -1 : ((a > b) ? 1 : 0); } } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
2f909afad951c17d2c1cfebfbe5eee40
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; 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()); } } public static void main(String[] args) { setup(); xuly(); } private static final int mod = 1000000007, mn = 100005; private static int num[] = new int[mn], divisor[] = new int[10], numDivisor; private static long ans = 0, power[] = new long[mn]; private static void listDivisor(int x) { numDivisor = 0; int temp = x; double limit = Math.sqrt(temp); for (int i = 2; i <= limit; i ++) if (temp % i == 0) { divisor[numDivisor ++] = i; while (temp % i == 0) temp /= i; limit = Math.sqrt(temp); } if (temp != 1) divisor[numDivisor ++] = temp; } private static void setup() { power[0] = 1; for (int i = 1; i < mn; i ++) power[i] = (power[i - 1] << 1) % mod; } private static void dfs(int curVal, int mul, int id) { if (curVal != 1) ans = (ans + power[num[curVal]] * mul) % mod; num[curVal] ++; for (int i = id + 1; i < numDivisor; i ++) dfs(curVal * divisor[i], - mul, i); } private static void xuly() { FastReader fastReader = new FastReader(); int n = fastReader.nextInt(); for (int i = 0; i < n; i ++) { int a = fastReader.nextInt(); listDivisor(a); dfs(1, -1, -1); } ans = ((power[n] - 1 - ans) % mod + mod) % mod; System.out.print(ans); } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
6651bbb0aee2b420e1c205578581ac4a
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
/*Author: Satyajeet Singh, Delhi Technological University*/ import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.math.*; public class Main{ /*********************************************Constants******************************************/ static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out)); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static long mod=(long)1e9+7; static long mod1=998244353; static boolean sieve[]; static ArrayList<Integer> primes; static long factorial[],invFactorial[]; static ArrayList<Pair> graph[]; static int pptr=0; static String st[]; /****************************************Solutions Begins***************************************/ public static void main(String args[]) throws Exception{ nl(); int n=pi(); int m=100001; long f[]=new long[m+1]; nl(); for(int i=0;i<n;i++){ f[pi()]++; } for(int i=1;i<=m;i++){ for(int j=2*i;j<=m;j+=i){ f[i]+=f[j]; } } for(int i=1;i<=m;i++){ f[i]=modulo(2,f[i],mod)-1; if(f[i]<0)f[i]+=mod; } for(int i=m;i>=1;i--){ for(int j=2*i;j<=m;j+=i){ f[i]-=f[j]; if(f[i]<0)f[i]+=mod; } } // debug(f); out.println(f[1]); /****************************************Solutions Ends**************************************************/ out.flush(); out.close(); } /****************************************Template Begins************************************************/ static void nl() throws Exception{ pptr=0; st=br.readLine().split(" "); } static void nls() throws Exception{ pptr=0; st=br.readLine().split(""); } static int pi(){ return Integer.parseInt(st[pptr++]); } static long pl(){ return Long.parseLong(st[pptr++]); } static double pd(){ return Double.parseDouble(st[pptr++]); } static String ps(){ return st[pptr++]; } /***************************************Precision Printing**********************************************/ static void printPrecision(double d){ DecimalFormat ft = new DecimalFormat("0.000000000000"); out.print(ft.format(d)); } /**************************************Bit Manipulation**************************************************/ static void printMask(long mask){ System.out.println(Long.toBinaryString(mask)); } static int countBit(long mask){ int ans=0; while(mask!=0){ mask&=(mask-1); ans++; } return ans; } /******************************************Graph*********************************************************/ static void Makegraph(int n){ graph=new ArrayList[n]; for(int i=0;i<n;i++){ graph[i]=new ArrayList<>(); } } static void addEdge(int a,int b){ graph[a].add(new Pair(b,1)); } static void addEdge(int a,int b,int c){ graph[a].add(new Pair(b,c)); } /*********************************************PAIR********************************************************/ static class Pair implements Comparable<Pair> { int u; int v; int index=-1; public Pair(int u, int v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return u == other.u && v == other.v; } public int compareTo(Pair other) { if(index!=other.index) return Long.compare(index, other.index); return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } /******************************************Long Pair*******************************************************/ static class Pairl implements Comparable<Pairl> { long u; long v; int index=-1; public Pairl(long u, long v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pairl other = (Pairl) o; return u == other.u && v == other.v; } public int compareTo(Pairl other) { if(index!=other.index) return Long.compare(index, other.index); return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } /*****************************************DEBUG***********************************************************/ public static void debug(Object... o){ System.out.println(Arrays.deepToString(o)); } /************************************MODULAR EXPONENTIATION***********************************************/ static long modulo(long a,long b,long c){ long x=1; long y=a%c; while(b > 0){ if(b%2 == 1){ x=(x*y)%c; } y = (y*y)%c; // squaring the base b /= 2; } return x%c; } /********************************************GCD**********************************************************/ static long gcd(long x, long y){ if(x==0) return y; if(y==0) return x; long r=0, a, b; a = (x > y) ? x : y; // a is greater number b = (x < y) ? x : y; // b is smaller number r = b; while(a % b != 0){ r = a % b; a = b; b = r; } return r; } /******************************************SIEVE**********************************************************/ static void sieveMake(int n){ sieve=new boolean[n]; Arrays.fill(sieve,true); sieve[0]=false; sieve[1]=false; for(int i=2;i*i<n;i++){ if(sieve[i]){ for(int j=i*i;j<n;j+=i){ sieve[j]=false; } } } primes=new ArrayList<Integer>(); for(int i=0;i<n;i++){ if(sieve[i]){ primes.add(i); } } } /********************************************End***********************************************************/ }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
32419c6cd81128a5afbc53bf44adbe46
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.util.*; import java.io.*; import java.text.*; public class Main{ //SOLUTION BEGIN //Into the Hardware Mode void pre() throws Exception{} void solve(int TC) throws Exception{ int n = ni(), mx = 100000; int[] f = new int[1+mx]; for(int i = 0; i< n; i++)f[ni()]++; long[] ans = new long[1+mx]; for(int i = mx; i>= 1; i--){ int c = 0; for(int j = i; j<= mx; j+=i)c+=f[j]; ans[i] = (pow(2, c)+mod-1)%mod; for(int j = i+i; j<= mx; j+= i)ans[i] = (ans[i]+mod-ans[j])%mod; } pn(ans[1]); } long pow(long a, long p){ long o = 1; while(p>0){ if((p&1)==1)o = (o*a)%mod; a = (a*a)%mod; p>>=1; } return o; } //SOLUTION END void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");} long IINF = (long)1e18, mod = (long)1e9+7; final int INF = (int)1e9, MX = (int)2e5+5; DecimalFormat df = new DecimalFormat("0.00"); double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-6; static boolean multipleTC = false, memory = false, fileIO = false; FastReader in;PrintWriter out; void run() throws Exception{ if(fileIO){ in = new FastReader("input.txt"); out = new PrintWriter("output.txt"); }else { in = new FastReader(); out = new PrintWriter(System.out); } //Solution Credits: Taranpreet Singh int T = (multipleTC)?ni():1; pre();for(int t = 1; t<= T; t++)solve(t); out.flush(); out.close(); } public static void main(String[] args) throws Exception{ if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start(); else new Main().run(); } long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));} void p(Object o){out.print(o);} void pn(Object o){out.println(o);} void pni(Object o){out.println(o);out.flush();} String n()throws Exception{return in.next();} String nln()throws Exception{return in.nextLine();} int ni()throws Exception{return Integer.parseInt(in.next());} long nl()throws Exception{return Long.parseLong(in.next());} double nd()throws Exception{return Double.parseDouble(in.next());} class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next() throws Exception{ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ throw new Exception(e.toString()); } } return st.nextToken(); } String nextLine() throws Exception{ String str = ""; try{ str = br.readLine(); }catch (IOException e){ throw new Exception(e.toString()); } return str; } } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
4b73b025b62f8b7c92b7104506917184
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.util.*; import java.io.*; import java.text.*; public class Main{ //SOLUTION BEGIN //Into the Hardware Mode void pre() throws Exception{} void solve(int TC) throws Exception{ int n = ni(), mx = 100000; int[] f = new int[mx+1]; for(int i = 0; i< n; i++)f[ni()]++; long[] ans = new long[mx+1]; for(int i = mx; i>= 1; i--){ ans[i] = 0; int cnt = 0; for(int j = 1; j*i <= mx; j++){ ans[i] = add(ans[i], mod-ans[i*j]); cnt += f[i*j]; } ans[i] = add(ans[i]+mod-1, pow(2, cnt)); } pn(ans[1]); } long mul(long a, long b){ if(a>=mod)a%=mod; if(b>=mod)b%=mod; a*=b; if(a>=mod)a%=mod; return a; } long add(long a, long b){ if(Math.abs(a)>=mod)a%=mod; if(a<0)a+=mod; if(Math.abs(b)>=mod)b%=mod; if(b<0)b+=mod; a+=b; if(Math.abs(a)>=mod)a%=mod; return a; } long pow(long a, long p){ long o = 1; while(p>0){ if(p%2==1)o = (a*o)%mod; a = (a*a)%mod; p>>=1; } return o; } //SOLUTION END void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");} long IINF = (long)1e18, mod = (long)1e9+7; final int INF = (int)1e9, MX = (int)2e5+5; DecimalFormat df = new DecimalFormat("0.00000000000"); double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-6; static boolean multipleTC = false, memory = false; FastReader in;PrintWriter out; void run() throws Exception{ in = new FastReader(); out = new PrintWriter(System.out); //Solution Credits: Taranpreet Singh int T = (multipleTC)?ni():1; pre();for(int t = 1; t<= T; t++)solve(t); out.flush(); out.close(); } public static void main(String[] args) throws Exception{ if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start(); else new Main().run(); } long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);} int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));} void p(Object o){out.print(o);} void pn(Object o){out.println(o);} void pni(Object o){out.println(o);out.flush();} String n()throws Exception{return in.next();} String nln()throws Exception{return in.nextLine();} int ni()throws Exception{return Integer.parseInt(in.next());} long nl()throws Exception{return Long.parseLong(in.next());} double nd()throws Exception{return Double.parseDouble(in.next());} class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception{ br = new BufferedReader(new FileReader(s)); } String next() throws Exception{ while (st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch (IOException e){ throw new Exception(e.toString()); } } return st.nextToken(); } String nextLine() throws Exception{ String str = ""; try{ str = br.readLine(); }catch (IOException e){ throw new Exception(e.toString()); } return str; } } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
35681d56388709de33fd8e3b245b8e96
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author beginner1010 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskF solver = new TaskF(); solver.solve(1, in, out); out.close(); } static class TaskF { final int mod = (int) 1e9 + 7; final int maxN = (int) (1e5 + 5); int subtract(int x, int y) { x -= y; if (x < 0) x += mod; return x; } int mul(long x, int y) { x *= y; x %= mod; return (int) x; } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n]; int[] freq = new int[maxN]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); freq[a[i]]++; } int[] two = new int[n + 1]; two[0] = 1; for (int i = 1; i <= n; i++) { two[i] = mul(two[i - 1], 2); } int[] numSize = new int[maxN]; for (int i = 1; i < maxN; i++) { for (int j = i; j < maxN; j += i) { numSize[i] += freq[j]; } } int[] ways = new int[maxN]; for (int i = maxN - 1; i >= 1; i--) { ways[i] = subtract(two[numSize[i]], 1); for (int j = i + i; j < maxN; j += i) ways[i] = subtract(ways[i], ways[j]); } out.println(ways[1]); } } static class InputReader { private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputStream stream; public InputReader(InputStream stream) { this.stream = stream; } private boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isWhitespace(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isWhitespace(c)); return res * sgn; } } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
5a40f70541b1fc93dc916d57ef80b54b
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author beginner1010 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskF solver = new TaskF(); solver.solve(1, in, out); out.close(); } static class TaskF { final int mod = (int) (1e9 + 7); final int maxN = (int) (1e5 + 5); int mul(int a, int b) { long ans = a; ans *= b; ans %= mod; if (ans < 0) ans += mod; return (int) (ans); } int add(int a, int b) { a += b; a %= mod; if (a < 0) a += mod; return a; } int pow(int a, int b) { if (b == 0) return 1; if ((b & 1) == 1) return mul(a, pow(a, b - 1)); else { int aux = pow(a, b >> 1); return mul(aux, aux); } } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } int[] mu = new int[maxN]; boolean[] prime = new boolean[maxN]; Arrays.fill(mu, 1); Arrays.fill(prime, true); for (int i = 2; i < maxN; i++) if (prime[i] == true) { for (int j = i; j < maxN; j += i) { if (j > i) prime[j] = false; if (j % (i * i) == 0) mu[j] = 0; else mu[j] = -mu[j]; } } ArrayList<Integer>[] factors = new ArrayList[maxN]; for (int i = 0; i < maxN; i++) { factors[i] = new ArrayList<>(); } for (int i = 1; i < maxN; i++) { for (int j = i; j < maxN; j += i) { factors[j].add(i); } } int[] cnt = new int[maxN]; for (int i = 0; i < n; i++) { for (int d : factors[a[i]]) { cnt[d]++; } } int ans = 0; for (int d = 1; d < maxN; d++) { int cur = add(pow(2, cnt[d]), -1); cur = mul(mu[d], cur); ans = add(ans, cur); } out.println(ans); } } static class InputReader { private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputStream stream; public InputReader(InputStream stream) { this.stream = stream; } private boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isWhitespace(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isWhitespace(c)); return res * sgn; } } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
85e26ac4dc596a462e0b30c43e17438f
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author beginner1010 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskF solver = new TaskF(); solver.solve(1, in, out); out.close(); } static class TaskF { final int mod = (int) (1e9 + 7); final int maxN = (int) (1e5 + 5); int mul(int a, int b) { long ans = a; ans *= b; return (int) (ans % mod); } int add(int a, int b) { a += b; a %= mod; if (a < 0) a += mod; return a; } int pow(int a, int b) { if (b == 0) return 1; if ((b & 1) == 1) return mul(a, pow(a, b - 1)); else { int aux = pow(a, b >> 1); return mul(aux, aux); } } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } ArrayList<Integer>[] factors = new ArrayList[maxN]; for (int i = 0; i < maxN; i++) { factors[i] = new ArrayList<>(); } for (int i = 1; i < maxN; i++) { for (int j = i; j < maxN; j += i) { factors[j].add(i); } } int[] freq = new int[maxN]; for (int i = 0; i < n; i++) { for (int f : factors[a[i]]) freq[f]++; } int[] res = new int[maxN]; int ans = add(pow(2, n), -1); for (int d = maxN - 1; d > 1; d--) { res[d] = add(pow(2, freq[d]), -1); for (int j = d + d; j < maxN; j += d) res[d] = add(res[d], -res[j]); ans = add(ans, -res[d]); } out.println(ans); } } static class InputReader { private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputStream stream; public InputReader(InputStream stream) { this.stream = stream; } private boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isWhitespace(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isWhitespace(c)); return res * sgn; } } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
ca24394f7e29658eaa40e55500cc4190
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
//package educational.round20; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class F { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int[] a = na(n); int[] f = new int[100001]; for(int v : a){ for(int d = 1;d*d <= v;d++){ if(v % d == 0){ f[d]++; if(d*d < v)f[v/d]++; } } } long[] dp = new long[100001]; int mod = 1000000007; for(int i = 100000;i >= 1;i--){ dp[i] = pow(2, f[i], mod)-1; for(int j = 2*i;j <= 100000;j+=i){ dp[i] -= dp[j]; if(dp[i] < 0)dp[i] += mod; } } out.println(dp[1]); } public static long pow(long a, long n, long mod) { // a %= mod; long ret = 1; int x = 63 - Long.numberOfLeadingZeros(n); for (; x >= 0; x--) { ret = ret * ret % mod; if (n << 63 - x < 0) ret = ret * a % mod; } return ret; } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new F().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
38bb0db94fb0446dfe46797d62db6269
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.*; public class q5 { static long modPow(long x, long pow,long mod) { long res=1; x%=mod; while(pow>0) { if((pow&1)!=0) res*=x; pow>>=1; x*=x; x%=mod; res%=mod; } return res; } public static void main(String[] args) throws IOException { Reader.init(System.in); PrintWriter out=new PrintWriter(System.out); ArrayList<Integer>[] pf=new ArrayList[100001]; for(int i=1;i<=100000;i++) pf[i]=new ArrayList<Integer>(); int n=Reader.nextInt(); int[] isp=new int[100001]; isp[1]=1; int[] count=new int[100001]; int[] c2=new int[100001]; long mod=1000000007; for(int i=2;i<=100000;i++) { if(isp[i]==0) { for(int j=i;j<=100000;j+=i) { isp[j]=1; count[j]++; pf[j].add(i); } } } long ans=q5.modPow(2, n, mod)-1+mod; ans%=mod; for(int i=0;i<n;i++) { int a=Reader.nextInt(); int k=pf[a].size(); for(int j=1;j<(1<<k);j++) { int prod=1; for(int l=0;l<k;l++) { if(((1<<l)&j)!=0){ prod*=pf[a].get(l); } } c2[prod]++; } } for(int i=2;i<=100000;i++) { if(c2[i]>0) { long v=q5.modPow(2, c2[i], mod)-1; if(count[i]%2==0) { ans+=v; } else { ans-=v; } ans+=mod; ans%=mod; } } out.println(ans); out.flush(); } } class NoD{ } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String nextLine() throws IOException{ return reader.readLine(); } static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static long nextLong() throws IOException { return Long.parseLong( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
ea91eea82abde749d209012c4f52940d
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class h { public static void main(String[] args) throws Exception { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(f.readLine()); int[] a = new int[n], cnt = new int[100100]; String[] split = f.readLine().split(" "); for(int i = 0; i < n; i++) cnt[a[i] = Integer.parseInt(split[i])]++; long MOD = (long)1e9+7; //first pre-compute all powers of two under modulo so that I can use them later long[] twoPower = new long[100100]; twoPower[0] = 1L; for(int i = 1; i < 100100; i++) { twoPower[i] = (twoPower[i-1] * 2l) % MOD; } //If I were to calculate the number of subsets where the gcd //is x, it would be the 2 ^ number of multiples of x - 1. //Ex: if the array was {4, 16, 20}, 4 has three multiples //(including itself) so there can be 2^3 - 1 subsets where it //is the gcd. //This over counts though. Using the previous example, the subsets are: //{4} {16} {20} {4, 16} {4, 20} {16, 20} {4, 16, 20} //The number of sets where the gcd is 4 is not 7 but is 4. //That's because I'm over counting the sets where 4 is not //a part of the set. So the answer for 4 is 2 ^ cnt - 1 // - the answer for all multiples of 4. long[] res = new long[100100]; //answer will be ans[1] for(int i = 100100-1; i >= 1; i--) { int total = 0; for(int j = i ; j < 100100; j += i) { total += cnt[j]; } res[i] = twoPower[total] - 1; for(int j = i * 2; j < 100100; j += i) { res[i] = (res[i] - res[j]) % MOD; if(res[i] < 0) res[i] += MOD; } } System.out.println(res[1] % MOD); } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
3dc5603433e565e9c5a5f799762540b5
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskF solver = new TaskF(); solver.solve(1, in, out); out.close(); } static class TaskF { public int mod = 1000000007; public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int[] arr = in.readIntArray(n); int[] freq = new int[1000010]; for (int x : arr) { for (int i = 1; i * i <= x; i++) { if (x % i == 0) { freq[i]++; if (i * i != x) freq[x / i]++; } } } for (int i = 0; i < freq.length; i++) { freq[i] = (int) (Utils.mod_exp(2, freq[i], mod) - 1); } for (int i = freq.length - 1; i >= 1; i--) { for (int j = i + i; j < freq.length; j += i) { freq[i] -= freq[j]; if (freq[i] < 0) freq[i] += mod; } } out.println(freq[1]); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int[] readIntArray(int tokens) { int[] ret = new int[tokens]; for (int i = 0; i < tokens; i++) { ret[i] = nextInt(); } return ret; } public int read() { if (this.numChars == -1) { throw new InputMismatchException(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException var2) { throw new InputMismatchException(); } if (this.numChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { ; } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { res *= 10; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public static boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == -1; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(int i) { writer.println(i); } } static class Utils { public static long mod_exp(long b, long e, long mod) { long res = 1; while (e > 0) { if ((e & 1) == 1) res = (res * b) % mod; b = (b * b) % mod; e >>= 1; } return res; } } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
adca2b7c2320223c563638f0c48ac1ed
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
/** * @author prakhar28 * */ import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class Main{ static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[200005]; // line length+1 int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static class FastScanner { private final BufferedReader bufferedReader; private StringTokenizer stringTokenizer; public FastScanner() { bufferedReader = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (stringTokenizer == null || !stringTokenizer.hasMoreElements()) { try { stringTokenizer = new StringTokenizer(bufferedReader.readLine()); } catch (IOException e) { throw new RuntimeException("Can't read next value", e); } } return stringTokenizer.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 = bufferedReader.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static void closeall() throws IOException{ printWriter.close(); sc.close(); in.close(); } static Scanner sc = new Scanner(System.in); static Reader in = new Reader(); static FastScanner fastScanner = new FastScanner(); static PrintWriter printWriter = new PrintWriter(new BufferedOutputStream(System.out)); static BufferedReader read = new BufferedReader(new InputStreamReader(System.in)); static long INF = (long)(1e18); int V,E; ArrayList<Integer> adj[]; ArrayList<Integer> path; Main(){ } Main(int v,int e){ V=v; E=e; adj=new ArrayList[v]; path = new ArrayList<>(); for(int i=0;i<v;i++) adj[i] = new ArrayList<>(); } void addEdge(int u,int v){ adj[u].add(v); adj[v].add(u); } static long power(long a,long k) { long m = 1000000007; long ans=1; long tmp=a%m; while(k>0) { if(k%2==1) ans=ans*tmp%m; tmp=tmp*tmp%m; k>>=1; } return ans; } static class Pair /*implements Comparable<Pair>*/{ long F,S; Pair(long x,long y){ F = x; S = y; } /*public int compareTo(Pair ob){ return this.num-ob.num; }*/ } static long gcd(long a,long b) { if(a<b) { long t = a; a = b; b = t; } long r = a%b; if(r==0) return b; return gcd(b,r); } static int lower_bound(int[] a,int low,int high,int val) { while(low!=high) { int mid = (low+high)/2; if(a[mid]<val) low=mid+1; else high=mid; } return low; } static int max(int a,int b) { return (int)Math.max(a, b); } static long max(long a,long b) { return (long)Math.max(a, b); } static long min(long a,long b) { if(a<b) return a; return b; } static long mod = 1000000007; public static void main(String args[])throws IOException{ Reader in = new Reader(); int n = in.nextInt(); int[] a = new int[n]; for(int i=0;i<n;i++) a[i] = in.nextInt(); boolean[] prime = new boolean[100001]; Arrays.fill(prime, true); prime[1]=false; for(int i=2;i<=100000;i++) { if(!prime[i]) continue; for(int j=i+i;j<=100000;j+=i) prime[j]=false; } int[] sign = new int[100001]; Arrays.fill(sign, 1); sign[1]=1; for(int i=2;i<=100000;i++) { if(prime[i]) sign[i]=-1; } for(int i=2;i<=100000;i++) { if(sign[i]==0) continue; if(!prime[i]) { sign[i]=-sign[i]; } for(int j=i+i;j<=100000;j+=i) sign[j]+=sign[i]; } int[] cnt = new int[100001]; for(int i=0;i<n;i++) { for(int j=1;j*j<=a[i];j++) { if(a[i]%j==0) cnt[j]++; if(a[i]%j==0 && j*j!=a[i]) cnt[a[i]/j]++; } } long sum = 0,x = 0; sign[1]=1; for(int i=1;i<=100000;i++) { if(sign[i]==0) continue; x = power(2,cnt[i]); x=(x%mod-1+mod)%mod; //printWriter.println(i+" "+x); if(sign[i]==1) sum=(sum%mod+x%mod)%mod; else sum=(sum%mod-x%mod+mod)%mod; } printWriter.println(sum); closeall(); }//1 3 5 15 3 105 35 }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
1f4480ff3605d2b202e18f6e849b4fcd
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
/* If you want to aim high, aim high Don't let that studying and grades consume you Just live life young ****************************** What do you think? What do you think? 1st on Billboard, what do you think of it Next is a Grammy, what do you think of it However you think, I’m sorry, but shit, I have no fcking interest ******************************* I'm standing on top of my Monopoly board That means I'm on top of my game and it don't stop til my hip don't hop anymore https://www.a2oj.com/Ladder16.html ******************************* 300iq as writer = Sad! */ import java.util.*; import java.io.*; import java.math.*; public class x803F { static long MOD = 1000000007L; public static void main(String hi[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); int[] arr = new int[N]; st = new StringTokenizer(infile.readLine()); for(int i=0; i < N; i++) arr[i] = Integer.parseInt(st.nextToken()); long[] pow2 = new long[N+1]; pow2[0] = 1L; for(int i=1; i <= N; i++) pow2[i] = (pow2[i-1]*2)%MOD; int[] freq = new int[100001]; for(int x: arr) { ArrayList<Integer> div = findDiv(x); for(int d: div) freq[d]++; } long res = 0L; for(int i=1; i <= 100000; i++) { if(freq[i] == 0) continue; int tag = squarefree(i); if(tag == 0) { res += pow2[freq[i]]-1; if(res >= MOD) res -= MOD; } else if(tag == 1) { res -= pow2[freq[i]]-1; if(res < 0) res += MOD; } } System.out.println(res%MOD); } public static int squarefree(int N) { if(N == 1) return 0; int res = 0; if(N%2 == 0) { if(N%4 == 0) return -1; N /= 2; res = 1; } for(int i=3; i <= (int)(Math.sqrt(N)+0.0001); i+=2) if(N%i == 0) { N /= i; if(N%i == 0) return -1; res++; } if(N > 1) res++; return res%2; } public static ArrayList<Integer> findDiv(int N) { //gens all divisors of N ArrayList<Integer> ls1 = new ArrayList<Integer>(); ArrayList<Integer> ls2 = new ArrayList<Integer>(); for(int i=1; i <= (int)(Math.sqrt(N)+0.00000001); i++) if(N%i == 0) { ls1.add(i); ls2.add(N/i); } Collections.reverse(ls2); for(int b: ls2) if(b != ls1.get(ls1.size()-1)) ls1.add(b); return ls1; } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
d5050c4bf62a6013e4d604da684619ff
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
/* 合 */ import java.io.*; import java.util.*; import java.math.*; public final class co_prime_subs { static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static FastScanner sc=new FastScanner(br); static PrintWriter out=new PrintWriter(System.out); static Random rnd=new Random(); static int maxn=(int)(1e5+5); static long mod=(long)(1e9+7); static long pow(long a,long b) { long x=1,y=a%mod; while(b>0) { if(b%2==1) { x=(x*y)%mod; } y=(y*y)%mod;b=b/2; } return x; } public static void main(String args[]) throws Exception { int n=sc.nextInt();int[] a=new int[n],cnt=new int[maxn]; for(int i=0;i<n;i++) { a[i]=sc.nextInt();cnt[a[i]]++; } long[] val=new long[maxn]; for(int i=1;i<maxn;i++) { for(int j=i;j<maxn;j+=i) { val[i]+=cnt[j]; } val[i]=(pow(2,val[i])-1+mod)%mod; } long[] res=new long[maxn]; for(int i=maxn-1;i>=1;i--) { res[i]=val[i]; for(int j=i+i;j<maxn;j+=i) { res[i]=(res[i]-res[j]+mod)%mod; } } out.println(res[1]);out.close(); } } class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() throws Exception { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public String next() throws Exception { return nextToken().toString(); } 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
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
e4c836a9b175f60277a9ffc269bbdc23
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { new Main().solve(); } }, "1", 1 << 26).start(); } void solve() { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); FCoprimeSubsequences solver = new FCoprimeSubsequences(); solver.solve(1, in, out); out.close(); } static class FCoprimeSubsequences { long mod = 1_000_000_000 + 7; public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); int[] ar = new int[100005]; for (int i = 0; i < n; i++) ar[in.scanInt()]++; long[] dp = new long[100005]; for (int i = 100000; i >= 1; i--) { int count = 0; long no = 0; for (int j = i; j <= 100000; j += i) { count += ar[j]; no = (no + dp[j]) % mod; } dp[i] = (CodeHash.pow(2, count, mod) - 1 - no) % mod; while (dp[i] < mod) dp[i] += mod; } out.println(dp[1] % mod); } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int index; private BufferedInputStream in; private int total; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (index >= total) { index = 0; try { total = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (total <= 0) return -1; } return buf[index++]; } public int scanInt() { int integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } } return neg * integer; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } static class CodeHash { public static long pow(long a, long b, long m) { long res = 1; a %= m; while (b > 0) { if ((b & 1) == 1) res = (res * a) % m; a = (a * a) % m; b >>= 1; } return res; } } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
d095b1ca035d3ccd718d422565799fc9
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.util.*; import java.io.*; public class CFA { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; private static final long MOD = 1000L * 1000L * 1000L + 7; private static final int[] dx = {0, -1, 0, 1}; private static final int[] dy = {1, 0, -1, 0}; private static final String yes = "Yes"; private static final String no = "No"; void solve() { // int T = nextInt(); int T = 1; for (int i = 0; i < T; i++) { helper(); } } void helper() { int n = nextInt(); int[] arr = nextIntArr(n); int LIMIT = 100 * 1000 + 10; int[] mu = new int[LIMIT]; for (int i = 1; i < LIMIT; i++) { int target = i == 1 ? 1 : 0; int delta = target - mu[i]; mu[i] = delta; for(int j = i + i; j < LIMIT; j += i) { mu[j] += delta; } } int[] factCnt = new int[LIMIT]; for (int v : arr) { for (int i = 1; i * i <= v; i++) { if (v % i == 0) { factCnt[i]++; if (i * i != v) { factCnt[v / i]++; } } } } long res = 0; for (int i = 1; i < LIMIT; i++) { long tmp = powMod(2, factCnt[i], MOD) - 1; if (tmp < 0) { tmp += MOD; } tmp = tmp * mu[i] % MOD; res += tmp; res = res % MOD; } res = (res + MOD) % MOD; outln(res); } // Power Calculate N^M % MOD, N and M can be long (up to 2^64, ~10^18) public long powMod(long N, long M, long MOD){//N^M % MOD if(M == 0L) return 1L; long[] hp = new long[64]; boolean[] bp = new boolean[64]; hp[0] = N; for(int i = 1; i < hp.length; i++) { hp[i] = (hp[i - 1] * hp[i - 1]) % MOD; } for(int j = 0; j < hp.length; j++) { if((M & (1L << j)) != 0) bp[j] = true; } long res = 1; for(int i = 0;i < bp.length; i++){ if(bp[i]) { res = (res * hp[i]) % MOD; } } return res; } void shuffle(long[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); long tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } int gcd(int a, int b) { while(a != 0 && b != 0) { int c = b; b = a % b; a = c; } return a + b; } private void outln(Object o) { out.println(o); } private void out(Object o) { out.print(o); } private void formatPrint(double val) { outln(String.format("%.9f%n", val)); } public CFA() { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) { new CFA(); } public long[] nextLongArr(int n) { long[] res = new long[n]; for(int i = 0; i < n; i++) res[i] = nextLong(); return res; } public int[] nextIntArr(int n) { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } public String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
178a67bdef183eb8ff8759b26fad7740
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Edu_20F { static long MOD = 1_000_000_007; public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int numE = Integer.parseInt(reader.readLine()); int[] elements = new int[numE]; StringTokenizer inputData = new StringTokenizer(reader.readLine()); int[] count = new int[100_001]; for (int i = 0; i < numE; i++) { elements[i] = Integer.parseInt(inputData.nextToken()); count[elements[i]]++; } reader.close(); long[] powers = new long[100_001]; powers[0] = 1; for (int i = 1; i <= 100_000; i++) { powers[i] = (powers[i - 1] * 2) % MOD; } // stores the number of possible subsets whose elements' GCD is... long[] cntSub_GCD = new long[100_001]; // lazy man's PIE for (int cGCD = 100_000; cGCD >= 1; cGCD--) { int cnt_div = 0; for (int mult = cGCD; mult <= 100_000; mult += cGCD) { cnt_div += count[mult]; } // divSetCnt gives the number of sets such that it's GCD is divisible by cGCD long divSetCnt = (powers[cnt_div] - 1 + MOD) % MOD; long fCount = divSetCnt; // exclude all sets such that their GCD is greater than that of cGCD for (int eGCD = cGCD * 2; eGCD <= 100_000; eGCD += cGCD) { fCount = (fCount - cntSub_GCD[eGCD] + MOD) % MOD; } cntSub_GCD[cGCD] = fCount; } System.out.println(cntSub_GCD[1]); } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
bc84541d798e580568961dcc4cd76924
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class A implements Runnable { private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; private BufferedReader in; private PrintWriter out; private StringTokenizer tok = new StringTokenizer(""); private void init() throws FileNotFoundException { Locale.setDefault(Locale.US); String fileName = ""; if (ONLINE_JUDGE && fileName.isEmpty()) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } else { if (fileName.isEmpty()) { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } else { in = new BufferedReader(new FileReader(fileName + ".in")); out = new PrintWriter(fileName + ".out"); } } } String readString() { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine()); } catch (Exception e) { return null; } } return tok.nextToken(); } int readInt() { return Integer.parseInt(readString()); } long readLong() { return Long.parseLong(readString()); } double readDouble() { return Double.parseDouble(readString()); } int[] readIntArray(int size) { int[] a = new int[size]; for (int i = 0; i < size; i++) { a[i] = readInt(); } return a; } public static void main(String[] args) { //new Thread(null, new _Solution(), "", 128 * (1L << 20)).start(); new A().run(); } long timeBegin, timeEnd; void time() { timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } @Override public void run() { try { timeBegin = System.currentTimeMillis(); init(); solve(); out.close(); time(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } final int MAX_VALUE = 1000 * 100; final int MOD = 1000 * 1000 * 1000 + 7; private void solve() { initPrimes(); int n = readInt(); int[] a = readIntArray(n); Arrays.sort(a); int[] countOfSubsequences = new int[n + 1]; countOfSubsequences[0] = 1; for (int size = 1; size <= n; size++) { countOfSubsequences[size] = (countOfSubsequences[size - 1] * 2) % MOD; } int[] countOfDivisableNumbers = new int[MAX_VALUE + 1]; long answer = 0; for (int i = 0; i < n; i++) { for (int divisor = 1; divisor * divisor <= a[i]; divisor++) { if (a[i] % divisor == 0) { countOfDivisableNumbers[divisor]++; if (divisor * divisor < a[i]) { countOfDivisableNumbers[a[i] / divisor]++; } } } } int[] mobius = new int[MAX_VALUE + 1]; for (int i = 1; i <= MAX_VALUE; i++) { mobius[i] = mobius(i); } for (int i = 1; i <= MAX_VALUE; i++) { answer = (answer + (countOfSubsequences[countOfDivisableNumbers[i]] - 1) * mobius[i] + MOD) % MOD; } out.println(answer); } int[] primes; void initPrimes() { boolean[] isPrime = new boolean[MAX_VALUE + 1]; Arrays.fill(isPrime, true); int primesCount = 0; for (int i = 2; i <= MAX_VALUE; i++) { if (isPrime[i]) { primesCount++; if (1l * i * i <= MAX_VALUE) { for (int j = i * i; j <= MAX_VALUE; j += i) { isPrime[j] = false; } } } } primes = new int[primesCount]; int j = 0; for (int i = 2; i <= MAX_VALUE; i++) { if (isPrime[i]) { primes[j++] = i; } } } /** * @return * 1 if n == 1 * 0 if not square free * (-1)^r where r count of prime divisors */ int mobius(int n) { if (n == 1) { return 1; } int r = 0; for (int p : primes) { if (n == 1 || p > n) { break; } if (n % p == 0) { if ((n / p) % p == 0) { return 0; } n /= p; r++; } } if (n > 1) { r++; } return r % 2 == 0 ? 1 : -1; } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
394e9b558cbe24dd6edcd324c1e1b0e9
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ work(); out.flush(); } long mod=1000000007L; long inf=Long.MAX_VALUE; long gcd(long a,long b) { return a==0?b:gcd(b%a,a); } long[] A; int n; long[] pow; int[] count; int[] D; void work() { n=ni(); A=na(n); pow=new long[100003]; long cur=1; for(int i=0;i<100003;i++) { pow[i]=cur; cur*=2; cur%=mod; } count=new int[100003]; D=new int[100003]; for(int i=0;i<n;i++) { long c=A[i]; List<Long> rec=new ArrayList<>(); for(long j=2;j*j<=c;j++) { if(c%j==0) { rec.add(j); while(c%j==0) { c/=j; } } } if(c!=1) { rec.add(c); } if(rec.size()==0)continue; int size=rec.size(); int v=1<<size; for(int j=1;j<v;j++) { int cnt=0; int a=1; for(int b=0;b<size;b++) { if((1<<b&j)>0) { cnt++; a*=rec.get(b); } } count[a]++; D[a]=cnt; } } long ret=pow[n]-1; for(int i=0;i<100003;i++) { if(count[i]>0) { int c=count[i]; long v=pow[c]-1; if(D[i]%2==1) { ret=(ret-v)%mod; }else { ret=(ret+v)%mod; } } } out.println((ret+mod)%mod); } //input @SuppressWarnings("unused") private ArrayList<Integer>[] ng(int n, int m) { ArrayList<Integer>[] graph=(ArrayList<Integer>[])new ArrayList[n]; for(int i=0;i<n;i++) { graph[i]=new ArrayList<>(); } for(int i=1;i<=m;i++) { int s=in.nextInt()-1,e=in.nextInt()-1; graph[s].add(e); graph[e].add(s); } return graph; } private ArrayList<long[]>[] ngw(int n, int m) { ArrayList<long[]>[] graph=(ArrayList<long[]>[])new ArrayList[n]; for(int i=0;i<n;i++) { graph[i]=new ArrayList<>(); } for(int i=1;i<=m;i++) { long s=in.nextLong()-1,e=in.nextLong()-1,w=in.nextLong(); graph[(int)s].add(new long[] {e,w,i}); graph[(int)e].add(new long[] {s,w}); } return graph; } private int ni() { return in.nextInt(); } private long nl() { return in.nextLong(); } private String ns() { return in.next(); } private long[] na(int n) { long[] A=new long[n]; for(int i=0;i<n;i++) { A[i]=in.nextLong(); } return A; } private int[] nia(int n) { int[] A=new int[n]; for(int i=0;i<n;i++) { A[i]=in.nextInt(); } return A; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } 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()); } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
fcc7452c94de8a460d9fa39faf8de566
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.util.*; import java.math.*; import java.io.*; import java.text.*; public class A{ //public static PrintWriter pw; public static PrintWriter pw=new PrintWriter(System.out); public static void solve() throws IOException{ // pw=new PrintWriter(new FileWriter("C:\\Users\\shree\\Downloads\\small_output_in")); FastReader sc=new FastReader(); int n=sc.I(); int a[]=new int [n]; for(int i=0;i<n;i++)a[i]=sc.I(); long pow[]=new long[100001]; pow[0]=1; for(int i=1;i<=n;i++)pow[i]=(pow[i-1]*2)%M; int cnt[]=new int[100001]; for(int i=0;i<n;i++) { int d=a[i]; for(int j=1;j*j<=d;j++) { if(d%j==0){ cnt[j]++; if(d/j!=j) cnt[d/j]++; } } } long ans[]=new long[100001]; for(int i = 100000;i >= 1;i--){ ans[i] = pow[cnt[i]]-1; for(int j = 2*i;j <= 100000;j+=i){ ans[i] -= ans[j]; if(ans[i] < 0)ans[i] +=M; } } pw.println(ans[1]); pw.close(); } public static void main(String[] args) { new Thread(null ,new Runnable(){ public void run(){ try{ solve(); } catch(Exception e){ e.printStackTrace(); } } },"1",1<<26).start(); } static long M=(long)Math.pow(10,9)+7; static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() throws FileNotFoundException{ //br=new BufferedReader(new FileReader("C:\\Users\\shree\\Downloads\\B-small-practice.in")); 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 I(){ return Integer.parseInt(next()); } long L(){ return Long.parseLong(next()); } double D() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
031cf80774331c00a739cd0dcfd68388
train_003.jsonl
1493391900
Let's call a non-empty sequence of positive integers a1, a2... ak coprime if the greatest common divisor of all elements of this sequence is equal to 1.Given an array a consisting of n positive integers, find the number of its coprime subsequences. Since the answer may be very large, print it modulo 109 + 7.Note that two subsequences are considered different if chosen indices are different. For example, in the array [1, 1] there are 3 different subsequences: [1], [1] and [1, 1].
256 megabytes
import java.util.*; import java.io.*; public class Main{ static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); static int[] dp = new int[100001], Mult = new int[100001], C = new int[100001]; static int mod = 1000000007; public static void main(String args[]) throws IOException{ Scanner sc = new Scanner(System.in); int N, M, i, j, k; N = sc.nextInt(); Arrays.fill(dp, -1); for(i = 0; i < N; i++){ M = sc.nextInt(); j = (int)Math.sqrt(M); for(k = 1; k < j; k++){ if(M%k == 0){ Mult[M/k]++; Mult[k]++; } } if(j*j == M) Mult[j]++; else if(M%j == 0){ Mult[M/j]++; Mult[j]++; } } C[0] = 1; for(i = 1; i <= 100000; i++) C[i] = (2*C[i-1])%mod; bw.write(sol(1)+""); bw.close(); } static int sol(int g){ if(dp[g] == -1){ dp[g] = C[Mult[g]]-1; for(int i = 2; i*g <= 100000; i++){ dp[g] -= sol(i*g); if(dp[g] < 0) dp[g] = mod + dp[g]; else if(dp[g] >= mod) dp[g] -= mod; } } return dp[g]; } }
Java
["3\n1 2 3", "4\n1 1 1 1", "7\n1 3 5 15 3 105 35"]
2 seconds
["5", "15", "100"]
NoteIn the first example coprime subsequences are: 1 1, 2 1, 3 1, 2, 3 2, 3 In the second example all subsequences are coprime.
Java 8
standard input
[ "combinatorics", "number theory", "bitmasks" ]
2e6eafc13ff8dc91e6803deeaf2ecea5
The first line contains one integer number n (1 ≀ n ≀ 100000). The second line contains n integer numbers a1, a2... an (1 ≀ ai ≀ 100000).
2,000
Print the number of coprime subsequences of a modulo 109 + 7.
standard output
PASSED
032e089b01118c2f68475787f26942c3
train_003.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.util.*; import java.io.*; import java.text.*; import java.math.*; public class Main{ public static StringTokenizer token = new StringTokenizer(""); public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static PrintWriter output = new PrintWriter(System.out); public static void main(String[] args) throws Exception { String str = ns(); int A[] = new int[str.length()]; int count=0; for(int i=1;i<str.length();i++){ if(str.charAt(i)==str.charAt(i-1)) count++; A[i] = count; } int M = ni(); for(int i=0;i<M;i++){ int a = ni(); int b = ni(); output.println(A[b-1]-A[a-1]); } output.close(); } //Scanning Inputs and Converting data library //Parse Integer public static Integer pi(String str){ return Integer.parseInt(str); } //Parse Long public static Long pl(String str){ return Long.parseLong(str); } //Taking Integer Input public static Integer ni() throws IOException{ if(!token.hasMoreElements()){ token = new StringTokenizer(br.readLine()); } return Integer.parseInt(token.nextToken()); } //Taking Long Input public static Long nl() throws IOException{ if(!token.hasMoreElements()){ token = new StringTokenizer(br.readLine()); } return Long.parseLong(token.nextToken()); } //Taking String Input public static String ns() throws IOException{ return new StringTokenizer(br.readLine()).nextToken(); } //Taking Integer Array public static int[] ai(int N) throws IOException{ int A[] = new int[N]; token = new StringTokenizer(br.readLine()); for(int i=0;i<A.length;i++){ A[i] = pi(token.nextToken()); } return A; } //Taking 2D Char Array public static char[][] acc(int N,int M) throws IOException{ char C[][] = new char[N][M]; for(int i=0;i<N;i++){ token = new StringTokenizer(br.readLine()); String s = token.nextToken(); for(int j=0;j<M;j++){ C[i][j] = s.charAt(j); } } return C; } //Taking String Array public static String[] as(String S[]) throws IOException{ token = new StringTokenizer(br.readLine()); for(int i=0;i<S.length;i++){ S[i] = token.nextToken(); } return S; } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
78cdc08e0f0e05c979c7f47b41819614
train_003.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.lang.reflect.Array; import java.util.*; import javafx.util.Pair; public class Codeforces { public static void main(String[] args) { Scanner s = new Scanner(System.in); String str = s.next(); int[] sum = new int[str.length()]; for (int i = 0; i < str.length()-1; i++) { int equal = 0; if(str.charAt(i) == str.charAt(i+1)) { equal = 1; } sum[i+1] = sum[i] + equal; } int m = s.nextInt(); for (int i = 0; i < m; i++) { int l = s.nextInt()-1; int r = s.nextInt()-1; System.out.println(sum[r] - sum[l]); } } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
9baf51952c4e1ff22876af5d31647f26
train_003.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Scanner; public class IlyaAndQueries { public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String input = bf.readLine(); String input2 = bf.readLine(); char[] mcharArray = input.toCharArray(); int[] isEqualToNext = new int[mcharArray.length]; boolean allZeros = true; boolean allOnes = true; int i = 0; for (int aux = 0; aux < mcharArray.length; aux++) { char mchar = mcharArray[aux]; if (i+1 == mcharArray.length) break; if (mchar == mcharArray[i + 1]) { allZeros = false; isEqualToNext[i] = 1; } else { allOnes = false; isEqualToNext[i] = 0; } i++; } i = 0; int amountOfQueries = Integer.parseInt(input2); int response = 0; int[] sum2 = new int[mcharArray.length]; if (!allZeros && !allOnes) { sum2[0] = 0; sum2[1] = isEqualToNext[0]; for (int aux = 2; aux < sum2.length; aux++) { sum2[aux] = sum2[aux - 1] + isEqualToNext[aux - 1]; } } if (allOnes) { for (int aux = 0; aux < sum2.length; aux++) { sum2[aux] = aux; } } int[] responses = new int[amountOfQueries]; i = 0; while (i < amountOfQueries) { String minput = bf.readLine(); String[] minputArray = minput.split(" "); int number1 = Integer.parseInt(minputArray[0]); int number2 = Integer.parseInt(minputArray[1]); int j = 0; response = 0; //while (j + number1 < number2) { // if (isEqualToNext[j + number1 - 1] == 1) // response++; // j++; //} System.out.println(sum2[number2 - 1] - sum2[number1 - 1]); i++; } } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
fb0fef7863d3567fb7e63c9831d8de12
train_003.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Scanner; public class IlyaAndQueries { public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String input = bf.readLine(); String input2 = bf.readLine(); char[] mcharArray = input.toCharArray(); int[] isEqualToNext = new int[mcharArray.length]; boolean allZeros = true; boolean allOnes = true; int i = 0; for (int aux = 0; aux < mcharArray.length; aux++) { char mchar = mcharArray[aux]; if (i+1 == mcharArray.length) break; if (mchar == mcharArray[i + 1]) { allZeros = false; isEqualToNext[i] = 1; } else { allOnes = false; isEqualToNext[i] = 0; } i++; } i = 0; int amountOfQueries = Integer.parseInt(input2); int response = 0; int[] sum2 = new int[mcharArray.length]; if (!allZeros && !allOnes) { sum2[0] = 0; sum2[1] = isEqualToNext[0]; for (int aux = 2; aux < sum2.length; aux++) { sum2[aux] = sum2[aux - 1] + isEqualToNext[aux - 1]; } } if (allOnes) { for (int aux = 0; aux < sum2.length; aux++) { sum2[aux] = aux; } } int[] responses = new int[amountOfQueries]; i = 0; while (i < amountOfQueries) { String minput = bf.readLine(); String[] minputArray = minput.split(" "); int number1 = Integer.parseInt(minputArray[0]); int number2 = Integer.parseInt(minputArray[1]); int j = 0; response = 0; //while (j + number1 < number2) { // if (isEqualToNext[j + number1 - 1] == 1) // response++; // j++; //} System.out.println(sum2[number2 - 1] - sum2[number1 - 1]); i++; } } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
9c0e2777a784f97c4276f4de7a600f9d
train_003.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import javafx.util.Pair; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner cin = new Scanner(System.in); String str = cin.nextLine(); int n = str.length(); int[] dp = new int[n+1]; dp[1] = 0; for(int i = 2;i <= n; i++){ if(str.charAt(i-2) == str.charAt(i-1)){ dp[i] = dp[i-1] + 1; }else dp[i] = dp[i-1]; } int m = cin.nextInt(); for(int i = 0;i < m; i++){ int l = cin.nextInt(); int r = cin.nextInt(); System.out.println(dp[r] - dp[l]); } } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
793d3620cc503aac2138c2c10e57831f
train_003.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
/** * Created by daeun on 2017-04-28. */ import java.util.Scanner; public class algo313B { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String str = scan.nextLine(); int len = str.length(); int[] check = new int[len]; check[0]=0; for(int i=1;i<len;i++){ check[i]=check[i-1]; if(str.charAt(i-1)==str.charAt(i)){ check[i]++; } } int num = scan.nextInt(); int[]couple = new int[num*2]; int total = 0; for (int i = 0; i < num; i++) { couple[2*i] = scan.nextInt(); couple[2*i+1] = scan.nextInt(); } StringBuilder s = new StringBuilder(); boolean a=false; for (int i = 0; i < num; i++) { if(!a){ total=check[couple[2*i+1] - 1]-check[couple[2*i] - 1]; } // for (int j = couple[2*i] - 1; j <= couple[2*i+1] - 2; j++) { // total+=check[j]; // } s.append(total); s.append("\n"); } System.out.println(s.toString()); } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
4de3749ff41403482e2cd6a1bf2525f3
train_003.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.io.*; public class Main2 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); int len = str.length()-1, n = Integer.parseInt(br.readLine()); int[] matches = new int[len], range = new int[len]; matches[0] = str.charAt(0) == str.charAt(1) ? 1 : 0; range[0] = matches[0]; for(int i = 1; i < len; i++) { matches[i] = str.charAt(i) == str.charAt(i+1) ? 1 : 0; range[i] = range[i-1] + matches[i]; } PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); for(int i = 1; i <= n; i++) { String[] lr = br.readLine().split(" "); int l = Integer.parseInt(lr[0]), r = Integer.parseInt(lr[1]); pw.println(l == 1 ? range[r-2] : range[r-2] - range[l-2]); } br.close(); pw.close(); } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
9c3b370b953fbad9500189752313056c
train_003.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.io.*; public class Main2 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); int len = str.length(), n = Integer.parseInt(br.readLine()); int[] range = new int[len]; range[0] = 0; for(int i = 1; i < len; i++) range[i] = str.charAt(i-1) == str.charAt(i) ? range[i-1] + 1 : range[i-1]; PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); for(int i = 1; i <= n; i++) { String[] lr = br.readLine().split(" "); int l = Integer.parseInt(lr[0])-1, r = Integer.parseInt(lr[1])-1; pw.println(range[r] - range[l]); } br.close(); pw.close(); } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
002e9b6835e4b966dddc8851761ab9d4
train_003.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); int len = str.length(); int[] matches = new int[len+1]; matches[0] = 0; for(int i = 0; i < len-1; i++) { matches[i+1] = matches[i]; if(str.charAt(i) == str.charAt(i+1)) matches[i+1]++; } matches[len] = matches[len-1]; PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int q = Integer.parseInt(br.readLine()); for(int i = 0; i < q; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); pw.println(-matches[Integer.parseInt(st.nextToken())-1] + matches[Integer.parseInt(st.nextToken())-1]); } br.close(); pw.close(); System.exit(0); } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
a51554356d99a4f4c4c5913b7d7e7552
train_003.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; public class Queries{ public static void main(String[] args) throws Exception{ FastScanner reader = new FastScanner(System.in); StringBuilder out = new StringBuilder(); char[] in = reader.next().toCharArray(); int n = in.length; int m = reader.nextInt(); int[] prep = new int[n+1]; for(int i = 1; i < n; i++) prep[i] = in[i-1]==in[i]?1:0; for(int i = 1; i <= n; i++) prep[i] = prep[i]+prep[i-1]; // System.out.println(Arrays.toString(prep)); for(int i = 0; i < m; i++){ int s = reader.nextInt()-1; int t = reader.nextInt()-1; out.append(prep[t]-prep[s]); out.append('\n'); } System.out.println(out); } //Sorry, Antony static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream in) throws Exception{ br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(br.readLine().trim()); } public int numTokens() throws Exception { if(!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine().trim()); return numTokens(); } return st.countTokens(); } public String next() throws Exception { if(!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine().trim()); return next(); } return st.nextToken(); } public double nextDouble() throws Exception { return Double.parseDouble(next()); } public long nextLong() throws Exception { return Long.parseLong(next()); } public int nextInt() throws Exception { return Integer.parseInt(next()); } } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
4fc3dc6d65a29e21d0b3248cc9708685
train_003.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; public class Queries{ public static void main(String[] args) throws Exception{ FastScanner reader = new FastScanner(System.in); StringBuilder out = new StringBuilder(); char[] in = reader.next().toCharArray(); int n = in.length; int m = reader.nextInt(); int[] prep = new int[n+1]; for(int i = 1; i <= n; i++) prep[i] = prep[i-1] + (i < n&&in[i-1]==in[i]?1:0); // System.out.println(Arrays.toString(prep)); for(int i = 0; i < m; i++){ int s = reader.nextInt()-1; int t = reader.nextInt()-1; out.append(prep[t]-prep[s]); out.append('\n'); } System.out.println(out); } //Sorry, Antony static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream in) throws Exception{ br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(br.readLine().trim()); } public int numTokens() throws Exception { if(!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine().trim()); return numTokens(); } return st.countTokens(); } public String next() throws Exception { if(!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine().trim()); return next(); } return st.nextToken(); } public double nextDouble() throws Exception { return Double.parseDouble(next()); } public long nextLong() throws Exception { return Long.parseLong(next()); } public int nextInt() throws Exception { return Integer.parseInt(next()); } } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
08ef96d9df3ab6c0f99f2be92ad62107
train_003.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.util.*; import java.io.*; public class IlyaAndQueries { public static void main(String[] args) { Scanner in = new Scanner(System.in); int x,y,n; String s; s=in.next(); char[] arr = s.toCharArray(); n=in.nextInt(); int length=s.length(); int ans[] = new int[length]; for(int i=1;i<length;i++) { ans[i]=ans[i-1]; if(arr[i]==arr[i-1]) ans[i]++; } while(n-->0) { x=in.nextInt()-1; y=in.nextInt()-1; System.out.println(ans[y]-ans[x]); } } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
ddb712c2a607f2c315d38a79c2e6829d
train_003.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.io.*; public class CF313B { static int m, prefix[] = new int[100001], l, r; static String in, ins[]; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); in = br.readLine(); for (int i = 1; i < in.length(); i++) { if (i == 1) prefix[i] = (in.charAt(i) == in.charAt(i - 1)) ? 1 : 0; else { prefix[i] = prefix[i - 1]; prefix[i] += (in.charAt(i) == in.charAt(i - 1)) ? 1 : 0; } } m = Integer.parseInt(br.readLine()); StringBuffer sb = new StringBuffer(); for (int i = 0; i < m; i++) { ins = br.readLine().split(" "); l = Integer.parseInt(ins[0]); r = Integer.parseInt(ins[1]); sb.append(prefix[r - 1] - prefix[l - 1]); sb.append("\n"); } bw.write(sb.toString()); bw.flush();bw.close(); } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
953fad5db0fadea3d81b51499c735e56
train_003.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.util.Arrays; import java.util.HashMap; import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String s = scanner.nextLine(); int queries = scanner.nextInt(); scanner.nextLine(); int[] memo = new int[s.length()]; memo[0] = 0; for (int i = 1; i < s.length(); i++) { memo[i] = memo[i - 1]; if (s.charAt(i) == s.charAt(i - 1)) memo[i]++; } for (int i = 0; i < queries; i++) { int x = scanner.nextInt() - 1; int y = scanner.nextInt() - 1; System.out.println(memo[memo.length - 1] - memo[x] - (memo[memo.length - 1] - memo[y])); } } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
e384fe8da596cfd75a9a129f6f36e8da
train_003.jsonl
1369927800
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≀ li &lt; ri ≀ n). The answer to the query li, ri is the number of such integers i (li ≀ i &lt; ri), that si = si + 1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem.
256 megabytes
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class su0{ public static void main(String[]args) { Scanner sc=new Scanner(System.in); String line=sc.next(); sc.nextLine(); int j=0; int arr[]=new int [line.length()+1]; int i; boolean flag =true; //System.out.print(Arrays.toString(Line)); for( i=0;i<line.length();i++) { arr[i+1]=arr[i]; if (i<line.length()-1 &&line.charAt(i)==line.charAt(i+1)) { arr[i+1]++; } } int n=sc.nextInt(); for (i=0;i<n;i++) { int a=sc.nextInt(); int b=sc.nextInt(); int c=-arr[a-1]+arr[b-1]; System.out.println(c); } } }
Java
["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"]
2 seconds
["1\n1\n5\n4", "1\n1\n2\n2\n0"]
null
Java 8
standard input
[ "dp", "implementation" ]
b30e09449309b999473e4be6643d68cd
The first line contains string s of length n (2 ≀ n ≀ 105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1 ≀ m ≀ 105) β€” the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li, ri (1 ≀ li &lt; ri ≀ n).
1,100
Print m integers β€” the answers to the queries in the order in which they are given in the input.
standard output
PASSED
ebee09817c8117e5a17c025cf77a489d
train_003.jsonl
1338737400
Hamming distance between strings a and b of equal length (denoted by h(a, b)) is equal to the number of distinct integers i (1 ≀ i ≀ |a|), such that ai ≠ bi, where ai is the i-th symbol of string a, bi is the i-th symbol of string b. For example, the Hamming distance between strings "aba" and "bba" equals 1, they have different first symbols. For strings "bbba" and "aaab" the Hamming distance equals 4.John Doe had a paper on which four strings of equal length s1, s2, s3 and s4 were written. Each string si consisted only of lowercase letters "a" and "b". John found the Hamming distances between all pairs of strings he had. Then he lost the paper with the strings but he didn't lose the Hamming distances between all pairs.Help John restore the strings; find some four strings s'1, s'2, s'3, s'4 of equal length that consist only of lowercase letters "a" and "b", such that the pairwise Hamming distances between them are the same as between John's strings. More formally, set s'i must satisfy the condition . To make the strings easier to put down on a piece of paper, you should choose among all suitable sets of strings the one that has strings of minimum length.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author pandusonu */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { public void solve(int testNumber, InputReader in, PrintWriter out) { int d12 = in.readInt(); int d13 = in.readInt(); int d14 = in.readInt(); int d23 = in.readInt(); int d24 = in.readInt(); int d34 = in.readInt(); int end = Math.max(Math.max(Math.max(d12, d13), d14), Math.max(Math.max(d23, d24), d34)); int solSize = -1; int[] ans = new int[7]; outer: for (int i = 0; i <= end; i++) { int[] sol = new int[7]; sol[6] = i; sol[5] = (d12 + d13 - d23) / 2 - sol[6]; sol[4] = (d14 + d12 - d24) / 2 - sol[6]; sol[3] = d12 - sol[4] - sol[5] - sol[6]; sol[2] = (-d34 + d14 + d13) / 2 - sol[6]; sol[1] = d23 - sol[2] - sol[3] - sol[4]; sol[0] = d34 - sol[1] - sol[4] - sol[5]; for (int x : sol) { if (x < 0) continue outer; } if (!((sol[3] + sol[4] + sol[5] + sol[6] == d12) && (sol[1] + sol[2] + sol[5] + sol[6] == d13) && (sol[0] + sol[2] + sol[4] + sol[6] == d14) && (sol[1] + sol[2] + sol[3] + sol[4] == d23) && (sol[0] + sol[2] + sol[3] + sol[5] == d24) && (sol[0] + sol[1] + sol[4] + sol[5] == d34))) { continue outer; } /* * 0 - aaab * 1 - aaba * 2 - aabb * 3 - abaa * 4 - abab * 5 - abba * 6 - abbb */ int sum = 0; for (int j = 0; j < 7; j++) { sum += sol[j]; } if (sum < solSize || solSize == -1) { for (int j = 0; j < 7; j++) { ans[j] = sol[j]; } solSize = sum; } } if (solSize == -1) { out.println(-1); return; } String[] a = {"aaaaaaa", "aaabbbb", "abbaabb", "bababab"}; out.println(solSize); for (int i = 0; i < 4; i++) { for (int j = 0; j < 7; j++) { for (int k = 0; k < ans[j]; k++) { out.print(a[i].charAt(j)); } } out.println(); } } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() { try { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) return -1; } } catch (IOException e) { throw new RuntimeException(e); } return buf[curChar++]; } public int readInt() { return (int) readLong(); } public long readLong() { int c = read(); while (isSpaceChar(c)) { c = read(); if (c == -1) throw new RuntimeException(); } boolean negative = false; if (c == '-') { negative = true; 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 negative ? (-res) : (res); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["4 4 4\n4 4\n4"]
2 seconds
["6\naaaabb\naabbaa\nbbaaaa\nbbbbbb"]
null
Java 8
standard input
[ "math" ]
d43786ca0472a5da735b04b9808c62d9
The first line contains space-separated integers h(s1, s2), h(s1, s3), h(s1, s4). The second line contains space-separated integers h(s2, s3) and h(s2, s4). The third line contains the single integer h(s3, s4). All given integers h(si, sj) are non-negative and do not exceed 105. It is guaranteed that at least one number h(si, sj) is positive.
2,400
Print -1 if there's no suitable set of strings. Otherwise print on the first line number len β€” the length of each string. On the i-th of the next four lines print string s'i. If there are multiple sets with the minimum length of the strings, print any of them.
standard output
PASSED
9d186e0a3813ca871fa00846c61b0b29
train_003.jsonl
1338737400
Hamming distance between strings a and b of equal length (denoted by h(a, b)) is equal to the number of distinct integers i (1 ≀ i ≀ |a|), such that ai ≠ bi, where ai is the i-th symbol of string a, bi is the i-th symbol of string b. For example, the Hamming distance between strings "aba" and "bba" equals 1, they have different first symbols. For strings "bbba" and "aaab" the Hamming distance equals 4.John Doe had a paper on which four strings of equal length s1, s2, s3 and s4 were written. Each string si consisted only of lowercase letters "a" and "b". John found the Hamming distances between all pairs of strings he had. Then he lost the paper with the strings but he didn't lose the Hamming distances between all pairs.Help John restore the strings; find some four strings s'1, s'2, s'3, s'4 of equal length that consist only of lowercase letters "a" and "b", such that the pairwise Hamming distances between them are the same as between John's strings. More formally, set s'i must satisfy the condition . To make the strings easier to put down on a piece of paper, you should choose among all suitable sets of strings the one that has strings of minimum length.
256 megabytes
import java.util.Scanner; public class HammingDistance194E { private static String[] combination = { "aaaaaaa", "aaabbbb", "abbaabb", "bababab" }; public static void main(String[] args) { Scanner in = new Scanner(System.in); int[] h = new int[6]; for (int i = 0; i < 6; i++) h[i] = in.nextInt(); int[] a = new int[7]; int[] b = new int[7]; int len = -1; for (int a7 = 0; a7 <= 10000; a7++) { b[0] = h[4] + h[5] - h[1] - h[0] + 2 * a7; b[1] = h[3] + h[5] - h[0] - h[2] + 2 * a7; b[2] = h[1] + h[2] - h[5] - 2 * a7; b[3] = h[3] + h[4] - h[1] - h[2] + 2 * a7; b[4] = h[0] + h[2] - h[4] - 2 * a7; b[5] = h[0] + h[1] - h[3] - 2 * a7; b[6] = 2 * a7; int l = 0; boolean sat = true; for (int i = 0; i < 7; i++) if (b[i] < 0 || b[i] % 2 != 0) { sat = false; break; } else { l += b[i] / 2; } if (!sat) continue; if (len < 0 || l < len) { len = l; for (int i = 0; i < 7; i++) a[i] = b[i] / 2; } } if (len < 0) System.out.println(-1); else { System.out.println(len); for (int s = 0; s < 4; s++) { for (int i = 0; i < 7; i++) { for (int j = 0; j < a[i]; j++) System.out.print(combination[s].charAt(i)); } System.out.println(); } } } }
Java
["4 4 4\n4 4\n4"]
2 seconds
["6\naaaabb\naabbaa\nbbaaaa\nbbbbbb"]
null
Java 6
standard input
[ "math" ]
d43786ca0472a5da735b04b9808c62d9
The first line contains space-separated integers h(s1, s2), h(s1, s3), h(s1, s4). The second line contains space-separated integers h(s2, s3) and h(s2, s4). The third line contains the single integer h(s3, s4). All given integers h(si, sj) are non-negative and do not exceed 105. It is guaranteed that at least one number h(si, sj) is positive.
2,400
Print -1 if there's no suitable set of strings. Otherwise print on the first line number len β€” the length of each string. On the i-th of the next four lines print string s'i. If there are multiple sets with the minimum length of the strings, print any of them.
standard output
PASSED
87a037499ef3ec4a3d91cff185613c51
train_003.jsonl
1338737400
Hamming distance between strings a and b of equal length (denoted by h(a, b)) is equal to the number of distinct integers i (1 ≀ i ≀ |a|), such that ai ≠ bi, where ai is the i-th symbol of string a, bi is the i-th symbol of string b. For example, the Hamming distance between strings "aba" and "bba" equals 1, they have different first symbols. For strings "bbba" and "aaab" the Hamming distance equals 4.John Doe had a paper on which four strings of equal length s1, s2, s3 and s4 were written. Each string si consisted only of lowercase letters "a" and "b". John found the Hamming distances between all pairs of strings he had. Then he lost the paper with the strings but he didn't lose the Hamming distances between all pairs.Help John restore the strings; find some four strings s'1, s'2, s'3, s'4 of equal length that consist only of lowercase letters "a" and "b", such that the pairwise Hamming distances between them are the same as between John's strings. More formally, set s'i must satisfy the condition . To make the strings easier to put down on a piece of paper, you should choose among all suitable sets of strings the one that has strings of minimum length.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Test { static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; static int nextInt() throws IOException { return Integer.parseInt(nextToken()); } static long nextLong() throws IOException { return Long.parseLong(nextToken()); } static double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } static String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } private static void solve() throws IOException { double[][] f= new double[5][5]; f[1][2]=nextInt(); f[1][3]=nextInt(); f[1][4]=nextInt(); f[2][3]=nextInt(); f[2][4]=nextInt(); f[3][4]=nextInt(); double[] N = new double[5]; double[] x = new double[5]; N[1]=(f[1][2]-f[2][3]+f[1][3])/2; N[2]=(f[1][2]+f[2][3]-f[1][3])/2; N[3]=(-f[1][2]+f[2][3]+f[1][3])/2; for(int i=1;i<=3;i++) { if(Math.abs(1.0*((int)N[i])-N[i])>0.0001) { writer.println(-1); return; } if(N[i]<-0.0001) { writer.println(-1); return; } } x[1]=(f[2][4]+f[3][4]-2*N[1]-N[2]-N[3])/(-2); x[2]=(f[1][4]+f[3][4]-N[1]-2*N[2]-N[3])/(-2); x[3]=(f[1][4]+f[2][4]-N[1]-N[2]-2*N[3])/(-2); if(Math.abs(1.0*((int)x[1])-x[1])>0.0001 || Math.abs(1.0*((int)x[2])-x[2])>0.0001 || Math.abs(1.0*((int)x[3])-x[3])>0.0001) { writer.println(-1); return; } N[4]=0.0; if(x[1]<-0.0001 || x[2]<-0.0001 || x[3]<-0.0001) { double ned = Math.min(x[1],Math.min(x[2], x[3])); x[1]-=ned; x[2]-=ned; x[3]-=ned; N[4]-=ned; } x[1]=N[1]-x[1]; if(x[1]>N[1]+0.0001) { writer.println(-1); return; } if(x[2]>N[2]+0.0001) { writer.println(-1); return; } if(x[3]>N[3]+0.0001) { writer.println(-1); return; } int rx[] = new int[5]; int rn[] = new int[5]; for(int i=0;i<5;i++) { rx[i]=(int)x[i]; rn[i]=(int)N[i]; } int n = rn[1]+rn[2]+rn[3]+rn[4]; writer.println(n); for(int i=0;i<n;i++) { writer.print("a"); } writer.println(); for(int i=0;i<rn[1]+rn[2];i++) { writer.print("b"); } for(int i=0;i<rn[3]+rn[4];i++) { writer.print("a"); } writer.println(); for(int i=0;i<rn[2];i++) { writer.print("a"); } for(int i=0;i<rn[1]+rn[3];i++) { writer.print("b"); } for(int i=0;i<rn[4];i++) { writer.print("a"); } writer.println(); for(int i=0;i<rx[2];i++) { writer.print("a"); } for(int i=0;i<rn[2]-rx[2];i++) { writer.print("b"); } for(int i=0;i<rx[1];i++) { writer.print("a"); } for(int i=0;i<rn[1]-rx[1];i++) { writer.print("b"); } for(int i=0;i<rx[3];i++) { writer.print("a"); } for(int i=0;i<rn[3]-rx[3];i++) { writer.print("b"); } for(int i=0;i<rn[4];i++) { writer.print("b"); } writer.println(); } }
Java
["4 4 4\n4 4\n4"]
2 seconds
["6\naaaabb\naabbaa\nbbaaaa\nbbbbbb"]
null
Java 6
standard input
[ "math" ]
d43786ca0472a5da735b04b9808c62d9
The first line contains space-separated integers h(s1, s2), h(s1, s3), h(s1, s4). The second line contains space-separated integers h(s2, s3) and h(s2, s4). The third line contains the single integer h(s3, s4). All given integers h(si, sj) are non-negative and do not exceed 105. It is guaranteed that at least one number h(si, sj) is positive.
2,400
Print -1 if there's no suitable set of strings. Otherwise print on the first line number len β€” the length of each string. On the i-th of the next four lines print string s'i. If there are multiple sets with the minimum length of the strings, print any of them.
standard output
PASSED
8e71ad27cd32ed6aa9a76652e10dc8ce
train_003.jsonl
1338737400
Hamming distance between strings a and b of equal length (denoted by h(a, b)) is equal to the number of distinct integers i (1 ≀ i ≀ |a|), such that ai ≠ bi, where ai is the i-th symbol of string a, bi is the i-th symbol of string b. For example, the Hamming distance between strings "aba" and "bba" equals 1, they have different first symbols. For strings "bbba" and "aaab" the Hamming distance equals 4.John Doe had a paper on which four strings of equal length s1, s2, s3 and s4 were written. Each string si consisted only of lowercase letters "a" and "b". John found the Hamming distances between all pairs of strings he had. Then he lost the paper with the strings but he didn't lose the Hamming distances between all pairs.Help John restore the strings; find some four strings s'1, s'2, s'3, s'4 of equal length that consist only of lowercase letters "a" and "b", such that the pairwise Hamming distances between them are the same as between John's strings. More formally, set s'i must satisfy the condition . To make the strings easier to put down on a piece of paper, you should choose among all suitable sets of strings the one that has strings of minimum length.
256 megabytes
import java.util.Scanner; public class HammingDistance194E { private static String[] combination = { "aaaaaaa", "aaabbbb", "abbaabb", "bababab" }; public static void main(String[] args) { Scanner in = new Scanner(System.in); int[] h = new int[6]; for (int i = 0; i < 6; i++) h[i] = in.nextInt(); int[] a = new int[7]; int[] b = new int[7]; int len = -1; for (int a7 = 0; a7 <= 10000; a7++) { b[0] = h[4] + h[5] - h[1] - h[0] + 2 * a7; b[1] = h[3] + h[5] - h[0] - h[2] + 2 * a7; b[2] = h[1] + h[2] - h[5] - 2 * a7; b[3] = h[3] + h[4] - h[1] - h[2] + 2 * a7; b[4] = h[0] + h[2] - h[4] - 2 * a7; b[5] = h[0] + h[1] - h[3] - 2 * a7; b[6] = 2 * a7; int l = 0; boolean sat = true; for (int i = 0; i < 7; i++) if (b[i] < 0 || b[i] % 2 != 0) { sat = false; break; } else { l += b[i] / 2; } if (!sat) continue; if (len < 0 || l < len) { len = l; for (int i = 0; i < 7; i++) a[i] = b[i] / 2; } } if (len < 0) System.out.println(-1); else { System.out.println(len); for (int s = 0; s < 4; s++) { for (int i = 0; i < 7; i++) { for (int j = 0; j < a[i]; j++) System.out.print(combination[s].charAt(i)); } System.out.println(); } } } }
Java
["4 4 4\n4 4\n4"]
2 seconds
["6\naaaabb\naabbaa\nbbaaaa\nbbbbbb"]
null
Java 6
standard input
[ "math" ]
d43786ca0472a5da735b04b9808c62d9
The first line contains space-separated integers h(s1, s2), h(s1, s3), h(s1, s4). The second line contains space-separated integers h(s2, s3) and h(s2, s4). The third line contains the single integer h(s3, s4). All given integers h(si, sj) are non-negative and do not exceed 105. It is guaranteed that at least one number h(si, sj) is positive.
2,400
Print -1 if there's no suitable set of strings. Otherwise print on the first line number len β€” the length of each string. On the i-th of the next four lines print string s'i. If there are multiple sets with the minimum length of the strings, print any of them.
standard output
PASSED
4e3f2f84987aa077d5c60d91874bed16
train_003.jsonl
1338737400
Hamming distance between strings a and b of equal length (denoted by h(a, b)) is equal to the number of distinct integers i (1 ≀ i ≀ |a|), such that ai ≠ bi, where ai is the i-th symbol of string a, bi is the i-th symbol of string b. For example, the Hamming distance between strings "aba" and "bba" equals 1, they have different first symbols. For strings "bbba" and "aaab" the Hamming distance equals 4.John Doe had a paper on which four strings of equal length s1, s2, s3 and s4 were written. Each string si consisted only of lowercase letters "a" and "b". John found the Hamming distances between all pairs of strings he had. Then he lost the paper with the strings but he didn't lose the Hamming distances between all pairs.Help John restore the strings; find some four strings s'1, s'2, s'3, s'4 of equal length that consist only of lowercase letters "a" and "b", such that the pairwise Hamming distances between them are the same as between John's strings. More formally, set s'i must satisfy the condition . To make the strings easier to put down on a piece of paper, you should choose among all suitable sets of strings the one that has strings of minimum length.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.Map.Entry; public class Main { public static void main(String[] args) throws IOException { (new Main()).solve(); } public void Main() { } void solve() throws IOException { // BufferedReader in = new BufferedReader(new // InputStreamReader(System.in)); // Scanner in = new Scanner(System.in); MyReader in = new MyReader(); PrintWriter out = new PrintWriter(System.out); // Scanner in = new Scanner(new FileReader("input.txt")); // PrintWriter out = new PrintWriter("output.txt"); int h12 = in.nextInt(); int h13 = in.nextInt(); int h14 = in.nextInt(); int h23 = in.nextInt(); int h24 = in.nextInt(); int h34 = in.nextInt(); int n = -1; int d = h12; int c = 0; int c2 = h13 + h23 - h12; if (c2 % 2 == 0) { c2 /= 2; } else { out.println(-1); out.close(); return; } int c1 = 0; int d2 = 0; int d1 = 0; int c22 = 0; int c21 = 0; int d22 = 0; int d11 = 0; int d21 = 0; int d12 = 0; for (int i = 0; i < 1000000; i++) { int L = i; c = L - h12; c1 = c - c2; d2 = h13 - c2; d1 = h23 - c2; c22 = h14 + h24 - h12 - 2 * c1; if (c22 % 2 == 0) { c22 /= 2; } else { continue; } c21 = c2 - c22; d21 = h24 + h34 - h23 - 2 * c1; if (d21 % 2 == 0) { d21 /= 2; } else { continue; } d22 = d2 - d21; d12 = h14 + h34 - h13 - 2 * c1; if (d12 % 2 == 0) { d12 /= 2; } else { continue; } d11 = d1 - d12; if (d >= 0 && c >= 0 && c1 >= 0 && c2 >= 0 && c21 >= 0 && c22 >= 0 && d1 >= 0 && d2 >= 0 && d11 >= 0 && d12 >= 0 && d21 >= 0 && d22 >= 0) { n = i; break; } } out.println(n); if (n > -1) { writeA(n, 'a', out); out.println(); writeA(c, 'a', out); writeA(d, 'b', out); out.println(); writeA(c1, 'a', out); writeA(c2, 'b', out); writeA(d1, 'a', out); writeA(d2, 'b', out); out.println(); writeA(c1, 'b', out); writeA(c21, 'a', out); writeA(c22, 'b', out); writeA(d11, 'a', out); writeA(d12, 'b', out); writeA(d21, 'a', out); writeA(d22, 'b', out); } out.close(); } void writeA(int n, char a, PrintWriter out) { for (int i = 0; i < n; i++) { out.print(a); } } }; class MyReader { private BufferedReader in; String[] parsed; int index = 0; public MyReader() { in = new BufferedReader(new InputStreamReader(System.in)); } public int nextInt() throws NumberFormatException, IOException { if (parsed == null || parsed.length == index) { read(); } return Integer.parseInt(parsed[index++]); } public long nextLong() throws NumberFormatException, IOException { if (parsed == null || parsed.length == index) { read(); } return Long.parseLong(parsed[index++]); } public String nextString() throws IOException { if (parsed == null || parsed.length == index) { read(); } return parsed[index++]; } private void read() throws IOException { parsed = in.readLine().split(" "); index = 0; } public String readLine() throws IOException { return in.readLine(); } };
Java
["4 4 4\n4 4\n4"]
2 seconds
["6\naaaabb\naabbaa\nbbaaaa\nbbbbbb"]
null
Java 6
standard input
[ "math" ]
d43786ca0472a5da735b04b9808c62d9
The first line contains space-separated integers h(s1, s2), h(s1, s3), h(s1, s4). The second line contains space-separated integers h(s2, s3) and h(s2, s4). The third line contains the single integer h(s3, s4). All given integers h(si, sj) are non-negative and do not exceed 105. It is guaranteed that at least one number h(si, sj) is positive.
2,400
Print -1 if there's no suitable set of strings. Otherwise print on the first line number len β€” the length of each string. On the i-th of the next four lines print string s'i. If there are multiple sets with the minimum length of the strings, print any of them.
standard output
PASSED
9470b6397d1dd7d12a5ab7146698ea08
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); String[] in = br.readLine().split("\\s+"); int r = Integer.parseInt(in[0]), c = Integer.parseInt(in[1]), k = Integer.parseInt(in[2]); int[][] grid = new int[r][c]; for(int i = 0 ; i < r ; i++){ String[] row = br.readLine().split("\\s+"); for(int j = 0 ; j < c ; j++) grid[i][j] = Integer.parseInt(row[j]); } int[] rows = new int[r], cols = new int[c]; for(int i = 0 ; i < r ; i++) rows[i] = i; for(int i = 0 ; i < c ; i++) cols[i] = i; for(int i = 0 ; i < k ; i++){ String[] query = br.readLine().split("\\s+"); int q1 = Integer.parseInt(query[1])-1, q2 = Integer.parseInt(query[2])-1; if(query[0].equals("g")) out.println(grid[rows[q1]][cols[q2]]); if(query[0].equals("r")){ int temp = rows[q1]; rows[q1] = rows[q2]; rows[q2] = temp; } if(query[0].equals("c")){ int temp = cols[q1]; cols[q1] = cols[q2]; cols[q2] = temp; } } out.close(); } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
88c5762b6ce85c2bb2086d1b6ecccc4a
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.util.*; import java.io.*; public class Div2B { public static void main(String[] args) throws IOException { new Div2B().run(); } FastScanner in; PrintWriter out; void run() throws IOException { in = new FastScanner(System.in); out = new PrintWriter(System.out, false); solve(); out.close(); } void solve() throws IOException { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int space[] = new int[n * m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) space[i * m + j] = in.nextInt(); int permN[] = new int[n]; int permM[] = new int[m]; for (int i = 0; i < n; i++) permN[i] = i; for (int i = 0; i < m; i++) permM[i] = i; for (int i = 0; i < k; i++) { char type = in.next().charAt(0); int x = in.nextInt() - 1; int y = in.nextInt() - 1; if (type == 'c') { permM[x] ^= permM[y]; permM[y] ^= permM[x]; permM[x] ^= permM[y]; } if (type == 'r') { permN[x] ^= permN[y]; permN[y] ^= permN[x]; permN[x] ^= permN[y]; } if (type == 'g') out.printf("%d\n", space[permN[x] * m + permM[y]]); } } static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { if (st == null || !st.hasMoreTokens()) return br.readLine(); StringBuilder result = new StringBuilder(st.nextToken()); while (st.hasMoreTokens()) { result.append(" "); result.append(st.nextToken()); } return result.toString(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
1204226a584af7a1e8d26d5953a1d233
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
//package com.morazow.cf; import java.io.*; import java.util.*; public class CF222B { public static void main(String[] args) { ArrayBufferScanner scanner = new ArrayBufferScanner(System.in); PrintWriter output = new PrintWriter(new OutputStreamWriter(System.out)); int N = scanner.nextInt(); int M = scanner.nextInt(); int K = scanner.nextInt(); int[][] matrix = new int[N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { matrix[i][j] = scanner.nextInt(); } } int[] rows = new int[N]; for (int i = 0; i < N; i++) { rows[i] = i; } int[] cols = new int[M]; for (int i = 0; i < M; i++) { cols[i] = i; } for (int i = 0; i < K; i++) { char ch = scanner.next().charAt(0); int r = scanner.nextInt() - 1; int c = scanner.nextInt() - 1; if (ch == 'r') { swap(rows, r, c); } else if (ch == 'c') { swap(cols, r, c); } else { output.println(matrix[rows[r]][cols[c]]); } } output.close(); } private static void swap(int[] A, int i, int j) { int t = A[i]; A[i] = A[j]; A[j] = t; } private static class ArrayBufferScanner { private char[] buffer = new char[1 << 4]; private int pos = 1; private BufferedReader reader; public ArrayBufferScanner(InputStream in) { this.reader = new BufferedReader(new InputStreamReader(in)); } public boolean hasNext() { return pos > 0; } public String next() { loadBuffer(); return current(); } public int nextInt() { loadBuffer(); final int radix = 10; int result = 0; int i = buffer[0] == '-' || buffer[0] == '+' ? 1 : 0; for (checkValidNumber(pos > i); i < pos; i++) { int digit = buffer[i] - '0'; checkValidNumber(0 <= digit && digit <= 9); result = result * radix + digit; } return buffer[0] == '-' ? -result : result; } private void checkValidNumber(boolean condition) { if (!condition) { throw new NumberFormatException(current()); } } private void loadBuffer() { pos = 0; try { for (int i; (i = reader.read()) != -1; ) { char c = (char) i; if (c != ' ' && c != '\n' && c != '\t' && c != '\r' && c != '\f') { if (pos == buffer.length) { buffer = Arrays.copyOf(buffer, 2 * pos); } buffer[pos++] = c; } else if (pos != 0) { break; } } } catch (IOException e) { throw new UncheckedIOException(e); } } private String current() { return String.copyValueOf(buffer, 0, pos); } } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
62855b7723ef82cf8fa0f027fee5a3ce
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class CosmicTables { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); String[] in = br.readLine().split("\\s+"); int r = Integer.parseInt(in[0]), c = Integer.parseInt(in[1]), k = Integer.parseInt(in[2]); int[][] grid = new int[r][c]; for(int i = 0 ; i < r ; i++){ String[] row = br.readLine().split("\\s+"); for(int j = 0 ; j < c ; j++) grid[i][j] = Integer.parseInt(row[j]); } int[] rows = new int[r], cols = new int[c]; for(int i = 0 ; i < r ; i++) rows[i] = i; for(int i = 0 ; i < c ; i++) cols[i] = i; for(int i = 0 ; i < k ; i++){ String[] query = br.readLine().split("\\s+"); int q1 = Integer.parseInt(query[1])-1, q2 = Integer.parseInt(query[2])-1; if(query[0].equals("g")) out.println(grid[rows[q1]][cols[q2]]); if(query[0].equals("r")){ int temp = rows[q1]; rows[q1] = rows[q2]; rows[q2] = temp; } if(query[0].equals("c")){ int temp = cols[q1]; cols[q1] = cols[q2]; cols[q2] = temp; } } out.close(); } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
8771bcfba2ff8d72ed28b4dcc38cc54f
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.StringTokenizer; public class q4 { public static void main(String[]args) throws IOException { Scanner sc=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); int n=sc.nextInt(),m=sc.nextInt(),k=sc.nextInt(); int[][]map=new int[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { map[i][j]=sc.nextInt(); } } int[]row=new int[n],col=new int[m]; for(int i=0;i<n;i++)row[i]=i; for(int i=0;i<m;i++)col[i]=i; // for(int i=0;i<n;i++)out.print(row[i]+" "); // ArrayList<Pair>x=new ArrayList(); for(int i=0;i<k;i++) { String s=sc.next(); int x=sc.nextInt()-1,y=sc.nextInt()-1; if(s.equals("g"))out.println(map[row[x]][col[y]]); else if(s.equals("c")) { int temp=col[x]; col[x]=col[y]; col[y]=temp; }else { int temp=row[x]; row[x]=row[y]; row[y]=temp; } } // for(int i=0;i<n;i++)out.print(row[i]+" "); // String s=sc.nextLine(); // for(int i=0;i<n;i++) {}; // out.print(2); // out.println(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready(); } } static class Pair implements Comparable<Pair>{ int x,y; Pair(int x,int y){ this.x=x; this.y=y; } public int compareTo(Pair p) { return p.y-y; } } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
06a0c6d6146f7ecbf42e7ea60d566279
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
// δ½œθ€…οΌšζ¨ζˆη‘žε…ˆη”Ÿ import java.io.*; import java.util.*; public class cf222b { static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e){e.printStackTrace();} } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try {st = new StringTokenizer(br.readLine());} catch (Exception e) {e.printStackTrace();} return st.nextToken(); } public int nextInt() {return Integer.parseInt(next());} public long nextLong() {return Long.parseLong(next());} public double nextDouble() {return Double.parseDouble(next());} public String nextLine() { String line = ""; if(st.hasMoreTokens()) line = st.nextToken(); else try {return br.readLine();}catch(IOException e){e.printStackTrace();} while(st.hasMoreTokens()) line += " "+st.nextToken(); return line; } } public static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(), m = sc.nextInt(), k = sc.nextInt(); int[][] grid = new int[n][m]; int[] row = new int[n]; int[] col = new int[m]; for(int i=0;i<n;i++) row[i] = i; for(int i=0;i<m;i++) col[i] = i; for(int i=0;i<n;i++) { String[] s = sc.nextLine().split(" "); for(int j=0;j<m;j++) { grid[i][j] = Integer.parseInt(s[j]); } } for(int i=0;i<k;i++) { String[] s = sc.nextLine().split(" "); char c = s[0].charAt(0); int a = Integer.parseInt(s[1]) - 1; int b = Integer.parseInt(s[2]) - 1; switch(c) { case 'g': pw.println(grid[row[a]][col[b]]); break; case 'r': int temp = row[a]; row[a] = row[b]; row[b] = temp; break; case 'c': temp = col[a]; col[a] = col[b]; col[b] = temp; break; } } pw.close(); } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
5d293799953ecd27d58c0efa4a69c741
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
//package forces; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; public class P_222B { public static void main(String[] args) throws IOException { try( BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)) ) { String[] ar = in.readLine().split(" "); int r = Integer.parseInt(ar[0]); int c = Integer.parseInt(ar[1]); int q = Integer.parseInt(ar[2]); List<String> ansList = new ArrayList<>(); int[][] table = new int[r][c]; for(int i=0; i<r; i++) { ar = in.readLine().split(" "); for(int j=0; j<c; j++) { table[i][j] = Integer.parseInt(ar[j]); } } int[] row = new int[r]; //row(i) maintains the pointer to ith row in table int[] col = new int[c]; //col(i) maintains pointer to ith col in table for(int i=0; i< r; i++) row[i] = i; for(int i=0; i<c; i++) col[i] = i; for(int i=0; i<q; i++) { ar = in.readLine().split(" "); String op = ar[0]; int m = Integer.parseInt(ar[1])-1; int n = Integer.parseInt(ar[2])-1; if(op.equals("c")) { int tmp = col[m]; col[m] = col[n]; col[n] = tmp; } else if(op.equals("r")) { int tmp = row[m]; row[m] = row[n]; row[n] = tmp; } else { //System.out.println(table[row[m]][col[n]]); ansList.add( Integer.toString(table[row[m]][col[n]])+"\n" ); } } for(String ans: ansList) out.write( ans ); } } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
a06f31d7039e31bfdc0a8d62b666cb1c
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.IOException; import java.util.StringTokenizer; import java.io.InputStreamReader; import java.io.BufferedReader; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.util.ArrayList; import java.util.Collections; import java.util.TreeSet; import java.util.*; public class Main { public static void main(String[]args) { FastReader in=new FastReader(); int r=in.nextInt(); int c=in.nextInt(); int k=in.nextInt(); int[][]x=new int[r][c]; int[]p=new int[c]; for(int i=0;i<r;i++) { for(int y=0;y<c;y++) { x[i][y]=in.nextInt(); } } for(int u=0;u<c;u++) { p[u]=u; } StringBuilder sb=new StringBuilder(); while(k-->0) { String s=in.next(); int a=in.nextInt(); int b=in.nextInt(); if(s.equals("g")) { sb.append(x[a-1][p[b-1]]+"\n"); } else if(s.equals("r")) { int[]m=x[a-1]; x[a-1]=x[b-1]; x[b-1]=m; } else if(s.equals("c")) { int e=p[a-1]; p[a-1]=p[b-1]; p[b-1]=e; } } System.out.print(sb); } } /* longest common subsequence Scanner in=new Scanner(System.in); while(in.hasNextLine()){ String s=in.next(); String x=in.next(); int l1=s.length(); int l2=x.length(); int[][]e=new int[l1+1][l2+1]; for(int i=0;i<l1+1;i++) { for(int y=0;y<l2+1;y++) { if(i==0 || y==0) { e[i][y]=0; } else{ if(s.charAt(i-1)==x.charAt(y-1)) { e[i][y]=e[i-1][y-1]+1; } else { e[i][y]=Math.max(e[i-1][y],e[i][y-1]); } } } } System.out.println(e[l1][l2]); */ //method for prime numbers /*public static boolean sieve(int n) { boolean[]x=new boolean[n+1]; for(int i = 0; i <= n;++i) { x[i] = true; } x[0] = false; x[1] = false; for(int i = 2; i * i <= n; ++i) { if(x[i] == true) { // Mark all the multiples of i as composite numbers for(int j = i * i; j <= n ;j += i) x[j] = false; } } int i=0; int count=0; while(i<x.length) { if(x[i] && n%i==0) count++; i++; } return (count==3)?true:false;*/ /* monk is birthday treat int n=in.nextInt(); int t=in.nextInt(); s=new List[n]; for(int r=0;r<s.length;r++) { s[r]=new ArrayList(); } while(t-->0) { int a=in.nextInt()-1; int b=in.nextInt()-1; s[a].add(b); } long[]p=new long[n]; for(int i=0;i<s.length;i++) { Stack<Integer>e=new Stack(); int[]k=new int[s[i].size()]; int j=0; if(!s[i].isEmpty()){ boolean []x=new boolean[n]; for (Integer h : s[i]) { int count=0; e.add(h); if(!x[h]){ x[h]=true; count++; } while(!e.isEmpty()) { int u=e.pop(); for (Integer v : s[u]) { if(!x[v]) { x[v]=true; count++; e.add(v); } } } k[j]=count; j++; } Arrays.sort(k); int q=0; while(q<k.length) { if(k[q]!=0) { p[i]=k[q]; break; } q++; } } } Arrays.sort(p); int y=0; long count2=0; while(y<p.length) { if(p[y]!=0) { count2=p[y]; break; } y++; } System.out.println(count2); */ /*class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } }*/ 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
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
0f63fdc7994f062125ce7b19ce99d84b
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Main{ public static void main(String[] args) throws Exception{ BufferedReader f=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(System.out); Scanner s=new Scanner(System.in); String split[]=f.readLine().split("\\s+"); int n=Integer.parseInt(split[0]); int m=Integer.parseInt(split[1]); int q=Integer.parseInt(split[2]); int table[][]=new int[n][m]; int row[]=new int[n]; int col[]=new int[m]; int i,j; for(i=0;i<n;i++) row[i]=i; for(i=0;i<m;i++) col[i]=i; for(i=0;i<n;i++){ split=f.readLine().split("\\s+"); for(j=0;j<m;j++){ table[i][j]=Integer.parseInt(split[j]); } } for(int k=0;k<q;k++){ split=f.readLine().split("\\s+"); char command=split[0].charAt(0); int x=Integer.parseInt(split[1])-1; int y=Integer.parseInt(split[2])-1; switch(command){ case 'g': out.println(table[row[x]][col[y]]); break; case 'r': int temp=row[x]; row[x]=row[y]; row[y]=temp; break; case 'c': temp=col[x]; col[x]=col[y]; col[y]=temp; break; } } out.close(); } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
d6e38f73f4edab00ca77f79d23ae5dc8
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.NoSuchElementException; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Alex */ 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out) { int rows = in.readInt(), cols = in.readInt(), k = in.readInt(); int[][] input = IOUtils.readIntTable(in, rows, cols); int[] row = new int[rows], col = new int[cols]; for (int i = 0; i < row.length; i++) row[i] = i; for (int i = 0; i < col.length; i++) col[i] = i; for (int i = 0; i < k; i++) { char s = in.readCharacter(); int x = in.readInt() - 1, y = in.readInt() - 1; if (s == 'c') { int temp = col[x]; col[x] = col[y]; col[y] = temp; } else if (s == 'r') { int temp = row[x]; row[x] = row[y]; row[y] = temp; } else{ out.printLine(input[row[x]][col[y]]); } } } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } public static int[][] readIntTable(InputReader in, int rowCount, int columnCount) { int[][] table = new int[rowCount][]; for (int i = 0; i < rowCount; i++) table[i] = readIntArray(in, columnCount); return table; } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
9f10f4d6a05728a8f4c1da78529e7e3a
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.*; import java.util.*; public class Solution { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { boolean env=System.getProperty("ONLINE_JUDGE") != null; if(!env) { try { br=new BufferedReader(new FileReader("src\\input.txt")); } catch (FileNotFoundException e) { e.printStackTrace(); } } else br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static FastReader sc=new FastReader(); static PrintWriter out=new PrintWriter(System.out); //Main public static void main(String args[]) { int test=1; //test=sc.nextInt(); while(test-->0) { int n=sc.nextInt(),m=sc.nextInt(),k=sc.nextInt(); int x[]=new int[n],y[]=new int[m],a[][]=new int[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { a[i][j]=sc.nextInt(); y[j]=j; } x[i]=i; } for(int i=0;i<k;i++) { char type=sc.next().charAt(0); int r=sc.nextInt()-1,c=sc.nextInt()-1; if(type=='r') { int tmp=x[r]; x[r]=x[c]; x[c]=tmp; } else if(type=='c') { int tmp=y[r]; y[r]=y[c]; y[c]=tmp; } else { out.println(a[x[r]][y[c]]); } } } out.flush(); out.close(); } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
56c832e1af953c7347e0162f05ce1645
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.FileReader; import java.io.InputStreamReader; import java.io.File; import java.io.FileNotFoundException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author zodiacLeo */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, FastScanner in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int q = in.nextInt(); int a[][] = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = in.nextInt(); } } int rows[] = new int[n]; int cols[] = new int[m]; for (int i = 0; i < n; i++) { rows[i] = i; } for (int i = 0; i < m; i++) { cols[i] = i; } while (q-- > 0) { String ch = in.next(); if (ch.equals("g")) { int row = in.nextInt() - 1; int col = in.nextInt() - 1; out.println(a[rows[row]][cols[col]]); } else if (ch.equals("c")) { int col1 = in.nextInt() - 1; int col2 = in.nextInt() - 1; int temp = cols[col1]; cols[col1] = cols[col2]; cols[col2] = temp; } else { int row1 = in.nextInt() - 1; int row2 = in.nextInt() - 1; int temp = rows[row1]; rows[row1] = rows[row2]; rows[row2] = temp; } } } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public String next() { while (st == null || !st.hasMoreElements()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
f98fa4cfec1e3fdd752553341e72e47b
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.util.Scanner; public class Main { FastScanner in; PrintWriter out; static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { if (st == null || !st.hasMoreTokens()) return br.readLine(); StringBuilder result = new StringBuilder(st.nextToken()); while (st.hasMoreTokens()) { result.append(" "); result.append(st.nextToken()); } return result.toString(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } void run() throws IOException { in = new FastScanner(System.in); out = new PrintWriter(System.out, false); solve(); out.close(); } public static void main(String[] args) throws IOException{ new Main().run(); } public void solve() throws IOException{ int n = in.nextInt(), m = in.nextInt(), k = in.nextInt(); int[][] tab = new int[n][m]; List<Integer> nmap = new ArrayList<Integer>(); List<Integer> mmap = new ArrayList<Integer>(); for(int i = 0; i < n; i++){ nmap.add(i); } for(int i = 0; i < m; i++){ mmap.add(i); } for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ tab[i][j] = in.nextInt(); } } for(int q = 0; q < k; q++){ char c = in.next().charAt(0); int a = in.nextInt() - 1; int b = in.nextInt() - 1; if(c == 'r'){ Collections.swap(nmap, a, b); }else if(c == 'c'){ Collections.swap(mmap, a, b); }else if(c == 'g'){ int x = nmap.get(a); int y = mmap.get(b); out.println(tab[x][y]); } } return; } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
eda9a438878887ba3eb1156e19e41ca5
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.util.*; import java.io.*; public class cf222b { public static void main(String[] args) throws Exception { // Scanner in = new Scanner(System.in); FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int m = in.nextInt(); int q = in.nextInt(); int[][] a = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = in.nextInt(); } } int[] r = new int[n]; int[] c = new int[m]; for (int i = 0; i < n; i++) { r[i] = i; } for (int i = 0; i < m; i++) { c[i] = i; } for (int i = 0; i < q; i++) { char qq = in.next().charAt(0); int x = in.nextInt() - 1; int y = in.nextInt() - 1; if (qq == 'r') { int tmp = r[x]; r[x] = r[y]; r[y] = tmp; } else if (qq == 'c') { int tmp = c[x]; c[x] = c[y]; c[y] = tmp; } else { out.println(a[r[x]][c[y]]); } } out.flush(); out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } FastReader(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException x) { System.out.println(x); } } String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } boolean hasNext() throws IOException { String s = br.readLine(); if (s == null) { return false; } st = new StringTokenizer(s); return true; } } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
8b4b433df87e75bc906c4e81de81c14e
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class CosmicTables { static BufferedReader in; static PrintWriter out; static StringTokenizer tok; static void solve() throws Exception { int n = nextInt(), m = nextInt(), k = nextInt(); int[][] b = new int[n][m]; for (int i = 0; i < n; i++) b[i] = nextIntArray(m, 0); int[] r = new int[n]; for (int i = 0; i < n; i++) r[i] = i; int[] c = new int[m]; for (int j = 0; j < m; j++) c[j] = j; for (int i = 0; i < k; i++) { String s = next(); if (s.equals("r")) swap(r, nextInt() - 1, nextInt() - 1); else if (s.equals("c")) swap(c, nextInt() - 1, nextInt() - 1); else { int x = r[nextInt() - 1]; int y = c[nextInt() - 1]; out.println(b[x][y]); } } } static void swap(int[] a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; } public static void main(String args[]) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); in.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(1); } } static int nextInt() throws IOException { return Integer.parseInt(next()); } static int[] nextIntArray(int len, int start) throws IOException { int[] a = new int[len]; for (int i = start; i < len; i++) a[i] = nextInt(); return a; } static long nextLong() throws IOException { return Long.parseLong(next()); } static long[] nextLongArray(int len, int start) throws IOException { long[] a = new long[len]; for (int i = start; i < len; i++) a[i] = nextLong(); return a; } static String next() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
7a9413a09ae2d64679e22a3c83d7fe9a
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter w = new PrintWriter(System.out); String[] ss = br.readLine().trim().split("\\s+"); int t,i,n= Integer.parseInt(ss[0]),m= Integer.parseInt(ss[1]),k= Integer.parseInt(ss[2]); int ar[][]=new int[n+1][m+1]; int r[]=new int[n+1]; int c[]=new int[m+1]; for(t=1;t<=n;t++)r[t]=t; for(t=1;t<=m;t++)c[t]=t; for(t=1;t<=n;t++) { ss = br.readLine().trim().split("\\s"); for (i = 1; i <= m; i++) ar[t][i] = Integer.parseInt(ss[i-1]); } for(t=0;t<k;t++){ ss = br.readLine().trim().split("\\s"); char s=ss[0].charAt(0); int x=Integer.parseInt(ss[1]),y=Integer.parseInt(ss[2]),sw; if(s=='r'){ sw=r[x]; r[x]=r[y]; r[y]=sw; }else if(s=='c'){ sw=c[x]; c[x]=c[y]; c[y]=sw; }else { w.println(ar[r[x]][c[y]]); } } w.close(); } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
0f3095ea0f6d9aac3e5a82f228019f17
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.*; import java.util.*; public class GFG { public static void main (String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); String str[] = br.readLine().split(" "); int n = Integer.valueOf(str[0]);//sc.nextInt(); int m = Integer.valueOf(str[1]);// int arr[][] =new int[n+1][m+1]; int k = Integer.valueOf(str[2]);// int r[] = new int[n+1]; int c[] = new int[m+1]; for(int i=1;i<=n;i++){ r[i]= i; str = br.readLine().split(" "); for(int ii=1;ii<=m;ii++){ c[ii]=ii; arr[i][ii]= Integer.valueOf(str[ii-1]); } } for(int i=0;i<k;i++){ str = br.readLine().split(" "); if(str[0].equals("g")){ bw.write(arr[r[Integer.valueOf(str[1])]][c[Integer.valueOf(str[2])]]+"\n"); } else if(str[0].equals("c")){ int c1 = Integer.valueOf(str[1]); int c2 = Integer.valueOf(str[2]); int cc=c[c1]; c[c1]=c[c2]; c[c2] =cc; } else { int r1 = Integer.valueOf(str[1]); int r2 = Integer.valueOf(str[2]); int y = r[r1]; r[r1]=r[r2]; r[r2]=y; } } bw.flush(); } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
2450d500a728302af1afedc9feab1f83
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jenish */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); BCosmicTables solver = new BCosmicTables(); solver.solve(1, in, out); out.close(); } static class BCosmicTables { int n; int m; int[][] arr; int[] row; int[] col; public void solve(int testNumber, ScanReader in, PrintWriter out) { n = in.scanInt(); m = in.scanInt(); int k = in.scanInt(); arr = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = in.scanInt(); } } row = new int[n]; col = new int[m]; for (int i = 0; i < n; i++) row[i] = i; for (int j = 0; j < m; j++) col[j] = j; while (k-- > 0) { char c = in.scanChar(); int x = in.scanInt() - 1; int y = in.scanInt() - 1; if (c == 'r') { int temp = row[x]; row[x] = row[y]; row[y] = temp; } else if (c == 'c') { int temp = col[x]; col[x] = col[y]; col[y] = temp; } else { out.println(arr[row[x]][col[y]]); } } } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int INDEX; private BufferedInputStream in; private int TOTAL; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (INDEX >= TOTAL) { INDEX = 0; try { TOTAL = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (TOTAL <= 0) return -1; } return buf[INDEX++]; } public char scanChar() { int c = scan(); while (isWhiteSpace(c)) c = scan(); return (char) c; } public int scanInt() { int I = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { I *= 10; I += n - '0'; n = scan(); } } return neg * I; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
013c4fb61747acaf6060d49e08f60953
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.util.HashMap; public class Main { public static void main(String[] args) throws IOException { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader input, PrintWriter out) throws IOException { int n = input.nextInt(), m = input.nextInt(), k = input.nextInt(); String[][] arr = new String[n + 1][m + 1]; for (int i = 1; i <= n; i++) { arr[i] = (" " + input.reader.readLine()).split(" "); } HashMap<Integer, Integer> mapRows = new HashMap<>(); for (int i = 1; i <= n; i++) { mapRows.put(i, i); } HashMap<Integer, Integer> mapCols = new HashMap<>(); for (int i = 1; i <= m; i++) { mapCols.put(i, i); } String query; int x, y, temp; for (int i = 0; i < k; i++) { query = input.next(); x = input.nextInt(); y = input.nextInt(); switch (query) { case "g": x = mapRows.get(x); y = mapCols.get(y); out.println(arr[x][y]); break; case "c": temp = mapCols.get(x); mapCols.put(x, mapCols.get(y)); mapCols.put(y, temp); break; case "r": temp = mapRows.get(x); mapRows.put(x, mapRows.get(y)); mapRows.put(y, temp); break; } } } } 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
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
3b8a75fbf654a97acac691e0173fccc7
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class CosmicTables implements Closeable { private InputReader in = new InputReader(System.in); private PrintWriter out = new PrintWriter(System.out); public void solve() { int n = in.ni(), m = in.ni(), q = in.ni(); int[][] data = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { data[i][j] = in.ni(); } } int[] row = new int[n]; for (int i = 0; i < n; i++) row[i] = i; int[] col = new int[m]; for (int i = 0; i < m; i++) col[i] = i; while (q-- > 0) { char type = in.next().charAt(0); int x = in.ni() - 1, y = in.ni() - 1; if (type == 'c') { int temp = col[x]; col[x] = col[y]; col[y] = temp; } else if (type == 'r') { int temp = row[x]; row[x] = row[y]; row[y] = temp; } else { out.println(data[row[x]][col[y]]); } } } @Override public void close() throws IOException { in.close(); out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int ni() { return Integer.parseInt(next()); } public long nl() { return Long.parseLong(next()); } public void close() throws IOException { reader.close(); } } public static void main(String[] args) throws IOException { try (CosmicTables instance = new CosmicTables()) { instance.solve(); } } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
79b898b21eadb3375947d77440442696
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int[][] nums = new int[n][m]; int[] row = new int[n]; int[] cal = new int[m]; for (int i = 0; i < n; i++) { row[i] = i; for (int j = 0; j < m; j++) { cal[j] = j; nums[i][j] = in.nextInt(); } } while (k-- != 0) { String ch = in.next(); int a = in.nextInt() - 1; int b = in.nextInt() - 1; if (ch.equals("r")) { int temp = row[a]; row[a] = row[b]; row[b] = temp; } else if (ch.equals("c")) { int temp = cal[a]; cal[a] = cal[b]; cal[b] = temp; } else { out.println(nums[row[a]][cal[b]]); } } } } 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
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
304ce0d03385d4a3fad3e918c8a5a227
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.util.Scanner; /** * 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int row = in.nextInt(); int col = in.nextInt(); int lines = in.nextInt(); int[][] s = new int[row][col]; int[] r = new int[row]; int[] c = new int[col]; for (int i = 0; i < row; i++) { r[i] = i; } for (int i = 0; i < col; i++) { c[i] = i; } for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { s[i][j] = in.nextInt(); } } while (lines-- != 0) { String ch = in.next(); int a = in.nextInt() - 1; int b = in.nextInt() - 1; if (ch.equals("r")) { int temp = r[a]; r[a] = r[b]; r[b] = temp; } else if (ch.equals("c")) { int temp = c[a]; c[a] = c[b]; c[b] = temp; } else { out.println(s[r[a]][c[b]]); } } } } 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
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
c478c70a623af88c953659c3bd7bb2b9
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); int n =in.nextInt(),m=in.nextInt(),k=in.nextInt(); int arr[][]=new int[n][m]; int row[]=new int[n]; int col[]=new int[m]; for(int i=0;i<n;i++) for(int j=0;j<m;j++) { arr[i][j]=in.nextInt(); row[i]=i; col[j]=j; } for(int i=0;i<k;i++) { char inp=in.next().charAt(0); int x=in.nextInt()-1,y=in.nextInt()-1; if(inp=='c') { int val1=col[x],val2=col[y]; col[x]=val2; col[y]=val1; } else if(inp=='r') { int val1=row[x],val2=row[y]; row[x]=val2; row[y]=val1; } else out.println(arr[row[x]][col[y]]); } out.close(); } } 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()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
c6e7cd0c3fa433d653272bad101e8194
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.*; import java.util.*; public class B { public static void main(String[] args)throws IOException { FastReader f=new FastReader(); StringBuffer sb = new StringBuffer(); int n=f.nextInt(); int m=f.nextInt(); int k=f.nextInt(); int mat[][]=new int[n][m]; for(int i=0;i<n;i++) { for(int j=0;j<m;j++) mat[i][j]=f.nextInt(); } int r[]=new int[n]; int c[]=new int[m]; for(int i=0;i<n;i++) r[i]=i; for(int i=0;i<m;i++) c[i]=i; while(k-->0) { char ch=f.next().charAt(0); int x=f.nextInt(); int y=f.nextInt(); if(ch=='g') { int xr=r[x-1]; int yr=c[y-1]; int val=mat[xr][yr]; sb.append(val+"\n"); continue; } if(ch=='r') { int t=r[x-1]; r[x-1]=r[y-1]; r[y-1]=t; } if(ch=='c') { int t=c[x-1]; c[x-1]=c[y-1]; c[y-1]=t; } } System.out.println(sb); } 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
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
421815dbf5bc8b574c65085407d399b0
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class ct { public static void main(String[] args) { InputStream inputStream = System.in; InputReader sc = new InputReader(inputStream); int n=sc.nextInt(); int m=sc.nextInt(); int q=sc.nextInt(); int arr[][]=new int[n][m]; int row[]=new int[n]; int col[]=new int[m]; for(int i=0;i<n;i++){ row[i]=i; } for(int i=0;i<m;i++){ col[i]=i; } for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ arr[i][j]=sc.nextInt(); } } StringBuilder sb=new StringBuilder(); while(q-->0){ char c=sc.next().charAt(0); int x=sc.nextInt()-1; int y=sc.nextInt()-1; if(c=='g'){ sb.append(arr[row[x]][col[y]]+"\n"); }else if(c=='r'){ int temp=row[x]; row[x]=row[y]; row[y]=temp; }else{ int temp=col[x]; col[x]=col[y]; col[y]=temp; } } System.out.print(sb.toString()); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
8276396e650041081c0f614ed25a146c
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; public class CosmicTables { public static void main(String args[]) throws IOException { Reader scan = new Reader(); StringBuilder sb = new StringBuilder(); int n = scan.nextInt(); int m = scan.nextInt(); int k = scan.nextInt(); int[][] mat = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { mat[i][j] = scan.nextInt(); } } int r[] = new int[n]; int c[] = new int[m]; for (int i = 0; i < m; i++) { c[i] = i; } for (int i = 0; i < n; i++) { r[i] = i; } while (k-- > 0) { int ch = scan.nextInt(); int f = scan.nextInt() - 1; int l = scan.nextInt() - 1; if (ch == 51) { int temp = c[f]; c[f] = c[l]; c[l] = temp; } else if (ch == 66) { int temp = r[f]; r[f] = r[l]; r[l] = temp; } else { sb.append(mat[r[f]][c[l]]+"\n"); } } System.out.println(sb); } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { break; } buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) { return -ret; } return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) { buffer[0] = -1; } } private byte read() throws IOException { if (bufferPointer == bytesRead) { fillBuffer(); } return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) { return; } din.close(); } } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
546f00bd0e4d5616a517a97535203380
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
//package codeforces; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.StringTokenizer; public class B implements Closeable { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); StringTokenizer stringTokenizer; B() throws IOException { // reader = new BufferedReader(new FileReader("input.txt")); // writer = new PrintWriter(new FileWriter("output.txt")); } String next() throws IOException { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.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()); } final int MOD = 1000 * 1000 * 1000 + 7; int sum(int a, int b) { a += b; return a >= MOD ? a - MOD : a; } int product(int a, int b) { return (int) (1l * a * b % MOD); } int pow(int x, long k) { int result = 1; while (k > 0) { if (k % 2 == 1) { result = product(result, x); } x = product(x, x); k /= 2; } return result; } @SuppressWarnings("unchecked") void solve() throws IOException { int n = nextInt(), m = nextInt(), k = nextInt(); int[][] table = new int[n][m]; for (int[] row : table) { for(int i = 0; i < m; i++) { row[i] = nextInt(); } } int[] rows = new int[n], cols = new int[m]; for(int i = 0; i < n; i++) { rows[i] = i; } for(int i = 0; i < m; i++) { cols[i] = i; } for(int i = 0; i < k; i++) { switch (next().charAt(0)) { case 'r': { int r1 = nextInt() - 1; int r2 = nextInt() - 1; int t = rows[r1]; rows[r1] = rows[r2]; rows[r2] = t; break; } case 'c': { int c1 = nextInt() - 1; int c2 = nextInt() - 1; int t = cols[c1]; cols[c1] = cols[c2]; cols[c2] = t; break; } default: { int r = nextInt() - 1; int c = nextInt() - 1; writer.println(table[rows[r]][cols[c]]); } } } } public static void main(String[] args) throws IOException { try (B b = new B()) { b.solve(); } } @Override public void close() throws IOException { reader.close(); writer.close(); } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
50c2b610d979699c1bc6a261c18af721
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class B222 { static int[][] data; static int[] row; static int[] col; public static void main(String[] args)throws Exception{ FastReader scan = new FastReader(); int n = scan.nextInt(), m = scan.nextInt(), k = scan.nextInt(); row = new int[n+1]; col = new int[m+1]; for(int i=0;i<n;++i)row[i] = i; for(int i=0;i<m;++i)col[i] = i; data = new int[n][m]; for(int i=0;i<n;++i){ for(int j=0;j<m;++j){ data[i][j] = scan.nextInt(); } } PrintWriter out = new PrintWriter(System.out); for(int i=0;i<k;++i){ char t = scan.next().charAt(0); int x = scan.nextInt()-1; int y = scan.nextInt()-1; if(t=='c')swap(col, x, y); else if(t=='r')swap(row, x, y); else { out.println(data[row[x]][col[y]]); } } out.close(); } public static void swap(int[] a, int x, int y){ int temp = a[x]; a[x] = a[y]; a[y] = temp; } 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
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
100923bbac983c0eee3c6aeac3200c27
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws Throwable { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // BufferedReader br = new BufferedReader(new FileReader("out1")); PrintWriter out = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int q = Integer.parseInt(st.nextToken()); int[][] arr = new int[n][m]; int[] col = new int[m],row = new int[n]; for (int i = 0; i < n; i++) { st = new StringTokenizer(br.readLine()); row[i] = i; for (int j = 0; j < m; j++) { arr[i][j] = Integer.parseInt(st.nextToken()); col[j] = j; } } while(q-->0) { st = new StringTokenizer(br.readLine()); char c = st.nextToken().charAt(0); int a = Integer.parseInt(st.nextToken()) -1; int b = Integer.parseInt(st.nextToken()) -1; if(c=='c') { col[a] ^= col[b]; col[b] ^= col[a]; col[a] ^= col[b]; } else { if(c=='r') { row[a] ^= row[b]; row[b] ^= row[a]; row[a] ^= row[b]; } else { out.append(arr[row[a]][col[b]]+"\n"); } } } out.flush(); } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
fc75d476802e434eae22155c8ee549d4
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.*; import java.util.*; 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); Solver solver = new Solver(); solver.solve(in, out); out.close(); } static class Solver { public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); int[][] a = new int[n][m]; int[] row = new int[n]; int[] col = new int[m]; for (int i = 0; i < n; ++i) { row[i] = i; } for (int i = 0; i < m; ++i) { col[i] = i; } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { a[i][j] = in.nextInt(); } } for (int i = 0; i < k; ++i) { char query = in.next().charAt(0); int x = in.nextInt() - 1; int y = in.nextInt() - 1; if (query == 'r') { swap(row, x, y); } else if (query == 'c') { swap(col, x, y); } else { out.println(a[row[x]][col[y]]); } } } public void swap(int[] a, int x, int y) { int temp = a[y]; a[y] = a[x]; a[x] = temp; } } 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.hasMoreElements()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
488bf8381f4ee76c7becd2391f1134c8
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.awt.Point; import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.*; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Double.parseDouble; import static java.lang.String.*; import javafx.scene.paint.Color; public class Main { public static void main(String[] args) throws IOException { // BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //(new FileReader("input.in")); StringBuilder out = new StringBuilder(); // StringTokenizer tk; // tk = new StringTokenizer(in.readLine()); //Scanner Reader = new Scanner(System.in); Reader.init(System.in); int r = Reader.nextInt(), c = Reader.nextInt(), k = Reader.nextInt(), temp = 0; int[][] a = new int[r][c]; for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { a[i][j] = Reader.nextInt(); } } int []ar=new int[r],ac=new int[c]; for (int i = 0; i < r; i++) { ar[i]=i; } for (int i = 0; i < c; i++) { ac[i]=i; } while(k-->0){ String x=Reader.next(); int r1=Reader.nextInt()-1,c1=Reader.nextInt()-1; if(x.equals("g")) out.append(a[ar[r1]][ac[c1]]+"\n"); else if(x.equals("r")) swapR(ar, r1, c1); else swapR(ac, r1, c1); } System.out.println(out); } static void swapR(int []a,int x,int y){ int t=a[x]; a[x]=a[y]; a[y]=t; } } class Reader { static StringTokenizer tokenizer; static BufferedReader reader; public static void init(InputStream input) throws UnsupportedEncodingException { reader = new BufferedReader(new InputStreamReader(input, "UTF-8")); tokenizer = new StringTokenizer(""); } public static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public static String nextLine() throws IOException { return reader.readLine(); } public static int nextInt() throws IOException { return Integer.parseInt(next()); } public static double nextDouble() throws IOException { return Double.parseDouble(next()); } public static long nextLong() throws IOException { return Long.parseLong(next()); } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
34fd7d9604cd764e9d7293da329d9b9e
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; inclass in = new inclass(inputStream); PrintWriter out = new PrintWriter(outputStream); BCosmicTables solver = new BCosmicTables(); solver.solve(1, in, out); out.close(); } static class BCosmicTables { static int n; static int m; public void solve(int testNumber, inclass in, PrintWriter out) { n = in.nextInt(); m = in.nextInt(); int q = in.nextInt(); int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = in.nextInt(); } } int col[] = new int[m]; for (int i = 0; i < col.length; i++) { col[i] = i; } while (q-- > 0) { String str[] = in.readLine().split(" "); String ch = str[0].trim(); int x = Integer.parseInt(str[1]) - 1; int y = Integer.parseInt(str[2]) - 1; if (ch.equals("c")) { int temp = col[x]; col[x] = col[y]; col[y] = temp; } else if (ch.equals("r")) { swaprow(x, y, arr); } else { out.println(get(x, col[y], arr)); } } } void swaprow(int row1, int row2, int[][] arr) { int temp[] = arr[row1]; arr[row1] = arr[row2]; arr[row2] = temp; } int get(int x, int y, int[][] arr) { return arr[x][y]; } } static class inclass { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private inclass.SpaceCharFilter filter; public inclass(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuilder buf = new StringBuilder(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') { buf.appendCodePoint(c); } c = read(); } return buf.toString(); } public String readLine() { String s = readLine0(); while (s.trim().length() == 0) { s = readLine0(); } return s; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
b6f09955937b63f90263fbc44ede3387
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { FScanner in = new FScanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int l = in.nextInt(); int[][] a = new int[1001][1001]; for(int i = 1; i <= n; ++i) { for(int j = 1; j <= m; ++j) { a[i][j] = in.nextInt(); } } int[] q = new int[1001]; int[] w = new int[1001]; for(int i = 1; i <= n; i++) { q[i] = i; } for(int j = 1; j <= m; j++) { w[j] = j; } StringBuilder sv = new StringBuilder(); for(int i = 0; i < l; ++i) { String s = in.next(); int d = in.nextInt(); int b = in.nextInt(); if(s.equals("r")) { int x = q[d]; q[d] = q[b]; q[b] = x; } else if(s.equals("c")) { int x = w[d]; w[d] = w[b]; w[b] = x; } else { sv.append(a[q[d]][w[b]]).append("\n"); } } System.out.println(sv.toString()); } static class FScanner { StringTokenizer st; BufferedReader br; public FScanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
46ed7c45645c760cc8ccdf4cc759dfa8
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
/* package whatever; // 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 Ideone { public static void main (String[] args) throws java.lang.Exception { // your code goes here BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(br.readLine()); StringBuilder sb=new StringBuilder(); int n=Integer.parseInt(st.nextToken()),m=Integer.parseInt(st.nextToken()),k=Integer.parseInt(st.nextToken()); int[][] metor=new int[n][m]; int[] row=new int[n],col=new int[m]; for(int i=0;i<n;i++){ st=new StringTokenizer(br.readLine()); for(int j=0;j<m;j++) { metor[i][j]=Integer.parseInt(st.nextToken()); // System.out.println(metor[i][j]); row[i]=i; col[j]=j; } } for(int i=0;i<k;i++){ st=new StringTokenizer(br.readLine()); String query=st.nextToken(); int x=Integer.parseInt(st.nextToken())-1,y=Integer.parseInt(st.nextToken())-1; //System.out.println(x+" "+y); if(query.charAt(0)=='r'){ int temp=row[x]; row[x]=row[y]; row[y]=temp; } if(query.charAt(0)=='c'){ int temp=col[x]; col[x]=col[y]; col[y]=temp; } if(query.charAt(0)=='g'){ sb.append(metor[row[x]][col[y]]+"\n"); } // System.out.println(Arrays.toString(row)+" "+Arrays.toString(col)); } System.out.println(sb); } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
70a0b47b8e152726a36e3c1484799009
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.util.*; import java.io.*; import java.text.*; import java.util.Arrays; public class Main { public static void main( String [] args ) throws IOException{ Scanner scan = new Scanner(System.in); in.init( System.in ); PrintWriter pw = new PrintWriter(System.out); int matrixRows = in.nextInt(); int matrixColumns = in.nextInt(); int qs = in.nextInt(); int matrix[][] = new int[matrixRows][matrixColumns]; int colSwap[] = new int[matrixColumns]; int rowSwap[] = new int[matrixRows]; for(int i = 0; i<matrixColumns; i++){ colSwap[i] = i; } for(int i = 0; i<matrixRows; i++){ rowSwap[i] = i; } for(int r = 0; r<matrixRows; r++){ for(int c= 0; c<matrixColumns;c++){ int curr = in.nextInt(); matrix[r][c] = curr; } } for(int i=0; i<qs;i++){ String character = in.next(); if( character.equals("c")){ int col1 = in.nextInt(); int col2 = in.nextInt(); int i1 = col1-1; int i2 = col2-1; int temp = colSwap[i1]; colSwap[i1] = colSwap[i2]; colSwap[i2] = temp; }else if(character.equals("r")){ int row1 = in.nextInt(); int row2 = in.nextInt(); int i1 = row1-1; int i2 = row2-1; int temp = rowSwap[i1]; rowSwap[i1] = rowSwap[i2]; rowSwap[i2] = temp; }else{ int row = in.nextInt(); int col = in.nextInt(); int cIndex = colSwap[col-1]; int rIndex = rowSwap[row-1]; pw.println(matrix[rIndex][cIndex]); } } pw.close(); /*for(int i=0; i<qs;i++){ String character = scan.next(); if( character.equals("c")){ int col1 = scan.nextInt(); int col2 = scan.nextInt(); int i1 = col1-1; int i2 = col2-1; int temp = colSwap[i1]; colSwap[i1] = colSwap[i2]; colSwap[i2] = temp; }else if(character.equals("r")){ int row1 = scan.nextInt(); int row2 = scan.nextInt(); swapRows(matrix, row1-1, row2-1); }else{ //g int row = scan.nextInt(); int col = scan.nextInt(); int cIndex = colSwap[col-1]; pw.println(matrix[row-1][cIndex]); } } pw.close();*/ } } /** Class for buffered reading int and double values */ class in { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
e9df2b2ff31c367dea91ba5a0b371a96
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.*; import java.util.*; public class B { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); Scanner s = new Scanner(System.in); String[] split = f.readLine().split("\\s+"); int n = Integer.parseInt(split[0]), m = Integer.parseInt(split[1]), q = Integer.parseInt(split[2]); int[][] table = new int[n][m]; int[] row = new int[n], col = new int[m]; for(int i = 0; i < n; i++) row[i] = i; for(int i = 0; i < m; i++) col[i] = i; for(int i = 0; i < n; i++) { split = f.readLine().split("\\s+"); for(int j = 0; j < m; j++) { table[i][j] = Integer.parseInt(split[j]); } } for(int k = 0; k < q; k++) { split = f.readLine().split("\\s+"); char command = split[0].charAt(0); int x = Integer.parseInt(split[1])-1, y = Integer.parseInt(split[2])-1; switch(command) { case 'g': out.println(table[row[x]][col[y]]); break; case 'r': int temp = row[x]; row[x] = row[y]; row[y] = temp; break; case 'c': temp = col[x]; col[x] = col[y]; col[y] = temp; break; } } out.close(); } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
b7ed44ff0cd39c6a9cc4256e63806f8f
train_003.jsonl
1347291900
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement. UCDHP stores some secret information about meteors as an n × m table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries: The query to swap two table rows; The query to swap two table columns; The query to obtain a secret number in a particular table cell. As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import static java.lang.Integer.parseInt; import java.util.StringTokenizer; public class B_Cosmic_Tables { public static void main(String[] args) throws IOException { InputStreamReader Input = new InputStreamReader(System.in); BufferedReader reader = new BufferedReader(Input); StringTokenizer tok = new StringTokenizer(reader.readLine()); OutputStreamWriter Output = new OutputStreamWriter(System.out); BufferedWriter writer = new BufferedWriter(Output); int n = parseInt(tok.nextToken()), m = parseInt(tok.nextToken()), k = parseInt(tok.nextToken()); int mat[][] = new int[n][m]; int swapRow[] = new int[n]; int swapCol[] = new int[m]; for (int i = 0; i < n; i++) { tok = new StringTokenizer(reader.readLine()); for (int j = 0; j < m; j++) { int num = parseInt(tok.nextToken()); mat[i][j] = num; } } for (int i = 0; i < n; i++) { swapRow[i] = i; } for (int i = 0; i < m; i++) { swapCol[i] = i; } for (int i = 0; i < k; i++) { tok = new StringTokenizer(reader.readLine()); char c = tok.nextToken().charAt(0); int num1 = parseInt(tok.nextToken()) - 1; int num2 = parseInt(tok.nextToken()) - 1; switch (c) { case 'r': swapRow[num1] = swapRow[num1] + swapRow[num2]; swapRow[num2] = swapRow[num1] - swapRow[num2]; swapRow[num1] = swapRow[num1] - swapRow[num2]; break; case 'c': swapCol[num1] = swapCol[num1] + swapCol[num2]; swapCol[num2] = swapCol[num1] - swapCol[num2]; swapCol[num1] = swapCol[num1] - swapCol[num2]; break; default: writer.write(mat[swapRow[num1]][swapCol[num2]] +""); writer.newLine(); } } writer.flush(); } }
Java
["3 3 5\n1 2 3\n4 5 6\n7 8 9\ng 3 2\nr 3 2\nc 2 3\ng 2 2\ng 3 2", "2 3 3\n1 2 4\n3 1 5\nc 2 1\nr 1 2\ng 1 3"]
3 seconds
["8\n9\n6", "5"]
NoteLet's see how the table changes in the second test case.After the first operation is fulfilled, the table looks like that:2 1 41 3 5After the second operation is fulfilled, the table looks like that:1 3 52 1 4So the answer to the third query (the number located in the first row and in the third column) will be 5.
Java 8
standard input
[ "data structures", "implementation" ]
290d9779a6be44ce6a2e62989aee0dbd
The first line contains three space-separated integers n, m and k (1 ≀ n, m ≀ 1000, 1 ≀ k ≀ 500000) β€” the number of table columns and rows and the number of queries, correspondingly. Next n lines contain m space-separated numbers each β€” the initial state of the table. Each number p in the table is an integer and satisfies the inequality 0 ≀ p ≀ 106. Next k lines contain queries in the format "si xi yi", where si is one of the characters "с", "r" or "g", and xi, yi are two integers. If si = "c", then the current query is the query to swap columns with indexes xi and yi (1 ≀ x, y ≀ m, x ≠ y); If si = "r", then the current query is the query to swap rows with indexes xi and yi (1 ≀ x, y ≀ n, x ≠ y); If si = "g", then the current query is the query to obtain the number that located in the xi-th row and in the yi-th column (1 ≀ x ≀ n, 1 ≀ y ≀ m). The table rows are considered to be indexed from top to bottom from 1 to n, and the table columns β€” from left to right from 1 to m.
1,300
For each query to obtain a number (si = "g") print the required number. Print the answers to the queries in the order of the queries in the input.
standard output
PASSED
a78f3f13b2301cfcb2a979d5165ece21
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.io.*; import java.util.*; 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(in, out); out.close(); } } class TaskD { void solve(InputReader in, OutputWriter out) { String queue = in.next(); int delay = 0; int i=0; while(i<queue.length() && queue.charAt(i) == 'F') { i++;} int result = 0; int boys = 0; while(i < queue.length()) { if(queue.charAt(i) == 'M') { boys++; delay = Math.max(0, delay-1); } else { result += (boys - result + delay); delay++; } i++; } out.printLine(result); } } 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 boolean hasNext() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { String line = reader.readLine(); if ( line == null ) { return false; } tokenizer = new StringTokenizer(line); } catch (IOException e) { throw new RuntimeException(e); } } return true; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next());} } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if ( i != 0 ) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
b9e5a7000f8dae548ccc2dc81d4f43d7
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.io.*; import java.util.*; 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(in, out); out.close(); } } class TaskD { private boolean types[]; void solve(InputReader in, OutputWriter out) { String queue = in.next(); int n = queue.length(); types = new boolean[n]; for(int i=0;i<queue.length();i++) { types[i] = (queue.charAt(i) == 'M'); } int delay = 0; int i=0; while(i<n && !types[i]) { i++;} int result = 0; int boys = 0; int prev = 0; while(i < n) { if(types[i]) { boys++; delay = Math.max(0, delay-1); } else { prev = boys - result + delay; result += prev; delay++; } i++; } out.printLine(result); } } 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 boolean hasNext() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { String line = reader.readLine(); if ( line == null ) { return false; } tokenizer = new StringTokenizer(line); } catch (IOException e) { throw new RuntimeException(e); } } return true; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next());} } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if ( i != 0 ) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
62a3d2869e8ea3901e8aa495c9ee380e
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import static java.util.Arrays.fill; import static java.lang.Math.*; import static java.util.Arrays.sort; import static java.util.Collections.sort; public class Queue1 { static int mod = 1000000007; static InputReader in = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { int girls=0; boolean m=false,f=false; char[] a=in.nextLine().toCharArray(); int x=0; int despos1=0; while(x<a.length&&a[x]=='F') { x++; despos1++; f=true; } for(;x<a.length;x++) { if(a[x]=='M') m=true; else { f=true; girls++; } } if(!m||!f||girls==0) { System.out.println(0); return; } int[] t=new int[girls+100]; int ptr=0; for(int i=despos1;i<a.length;i++) { if(a[i]=='F') { if(ptr!=0) t[ptr]=max(t[ptr-1]+1, i-despos1); else t[ptr]=i-despos1; despos1++; ptr++; } } out.println(t[girls-1]); out.close(); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public 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 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; } } private static void tr(Object... o) { if (!(System.getProperty("ONLINE_JUDGE") != null)) System.out.println(Arrays.deepToString(o)); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
3b7cb60cbd7043f5b6bc5b84f0ab1035
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
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() { char[] s = in.next().toCharArray(); int rank = 0, before = 0; for (int i = 0; i < s.length; i++) { if (s[i] == 'F') { int dist = i - rank; if (rank == 0 || dist == 0 || before < dist) { before = dist; } else { before = before + 1; } rank++; } } printf(before); } 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()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
7be321f97944a2152474fde5d77b7edf
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.PrintWriter; public class D353 { static class Scanner { BufferedReader br; StringTokenizer tk=new StringTokenizer(""); public Scanner(InputStream is) { br=new BufferedReader(new InputStreamReader(is)); } public int nextInt() throws IOException { if(tk.hasMoreTokens()) return Integer.parseInt(tk.nextToken()); tk=new StringTokenizer(br.readLine()); return nextInt(); } public long nextLong() throws IOException { if(tk.hasMoreTokens()) return Long.parseLong(tk.nextToken()); tk=new StringTokenizer(br.readLine()); return nextLong(); } public String next() throws IOException { if(tk.hasMoreTokens()) return (tk.nextToken()); tk=new StringTokenizer(br.readLine()); return next(); } public String nextLine() throws IOException { tk=new StringTokenizer(""); return br.readLine(); } public double nextDouble() throws IOException { if(tk.hasMoreTokens()) return Double.parseDouble(tk.nextToken()); tk=new StringTokenizer(br.readLine()); return nextDouble(); } public char nextChar() throws IOException { if(tk.hasMoreTokens()) return (tk.nextToken().charAt(0)); tk=new StringTokenizer(br.readLine()); return nextChar(); } public int[] nextIntArray(int n) throws IOException { int a[]=new int[n]; for(int i=0;i<n;i++) a[i]=nextInt(); return a; } public long[] nextLongArray(int n) throws IOException { long a[]=new long[n]; for(int i=0;i<n;i++) a[i]=nextLong(); return a; } public int[] nextIntArrayOneBased(int n) throws IOException { int a[]=new int[n+1]; for(int i=1;i<=n;i++) a[i]=nextInt(); return a; } public long[] nextLongArrayOneBased(int n) throws IOException { long a[]=new long[n+1]; for(int i=1;i<=n;i++) a[i]=nextLong(); return a; } } public static void main(String args[]) throws IOException { Scanner in=new Scanner(System.in); PrintWriter out=new PrintWriter(System.out); char c[]=(in.next()).toCharArray(); int ans=0; int last=-1; int cnt=0; for(int i=0;i<c.length;i++) { if(c[i]=='M') continue; else { int v=i-cnt; if(v<=last&&v!=0) { v=last+1; } ans=v; last=v; cnt++; } } out.println(ans); out.close(); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
3ec645d832f7e1b81fb80ece3eb878b9
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.io.*; import java.util.*; /* * Heart beats fast * Colors and promises * How to be brave * How can I love when I am afraid to fall... */ //read the question correctly (is y a vowel? what are the exact constraints?) //look out for SPECIAL CASES (n=1?) and overflow (ll vs int?) public class Main { public static void main(String[] args) { String s=ns(); int n=s.length(); int te=0,ans=0; for(int i=0; i<n; i++) if(s.charAt(i)=='M') te++; else if(te>0) ans=Math.max(te,ans+1); pr(ans); System.out.print(output); } /////////////////////////////////////////// /////////////////////////////////////////// ///template from here static interface Combiner { public int combine(int a, int b); } static final int mod=1000000007; static final double eps=1e-8; static final long inf=100000000000000000L; static Reader in=new Reader(); static StringBuilder output=new StringBuilder(); static Random rn=new Random(); public static void sort(int[]a) { int te; for(int i=0; i<a.length; i++) { te=rn.nextInt(a.length); if(i!=te) { a[i]^=a[te]; a[te]^=a[i]; a[i]^=a[te]; } } Arrays.sort(a); } public static void sort(long[]a) { int te; for(int i=0; i<a.length; i++) { te=rn.nextInt(a.length); if(i!=te) { a[i]^=a[te]; a[te]^=a[i]; a[i]^=a[te]; } } Arrays.sort(a); }public static void sort(double[]a) { int te; double te1; for(int i=0; i<a.length; i++) { te=rn.nextInt(a.length); if(i!=te) { te1=a[te]; a[te]=a[i]; a[i]=te1; } } Arrays.sort(a); } public static void sort(int[][]a) { Arrays.sort(a, new Comparator<int[]>() { public int compare(int[]a,int[]b) { if(a[0]>b[0]) return 1; if(b[0]>a[0]) return -1; return 0; } }); } static int lowerbound(int[]a, int key) { /* * returns index of smallest element larger than equal to given element between indices l and r inclusive */ int low=0,high=a.length-1,mid=(low+high)/2; while(low<high) { if(a[mid] >= key) high=mid; else low=mid+1; mid=(low+high)/2; } return mid; } static int upperbound(int[]a, int key) { /* * returns index of largest element smaller than equal to given element */ int low=0,high=a.length-1,mid=(low+high+1)/2; while(low<high) { if(a[mid] <= key) low=mid; else high=mid-1; mid=(low+high+1)/2; } return mid; } static int lowerbound(int[]a, int l, int r, int key) { /* * returns index of smallest element larger than equal to given element between indices l and r inclusive */ int low=l,high=r,mid=(low+high)/2; while(low<high) { if(a[mid] >= key) high=mid; else low=mid+1; mid=(low+high)/2; } return mid; } static int upperbound(int[]a, int l, int r, int key) { /* * returns index of largest element smaller than equal to given element */ int low=l,high=r,mid=(low+high+1)/2; while(low<high) { if(a[mid] <= key) low=mid; else high=mid-1; mid=(low+high+1)/2; } return mid; } static class pair { int a,b; pair() { } pair(int c,int d) { a=c; b=d; } } void sort(pair[]a) { Arrays.sort(a,new Comparator<pair>() { @Override public int compare(pair a,pair b) { if(a.a>b.a) return 1; if(b.a>a.a) return -1; return 0; } }); } static int log2n(long a) { int te=0; while(a>0) { a>>=1; ++te; } return te; } static class iter { vecti a; int zin=0; iter(vecti b) { a=b; } public boolean hasNext() { if(a.size>zin) return true; return false; } public int next() { return a.a[zin++]; } public void previous() { zin--; } } static class vecti { int a[],size; vecti() { a=new int[10]; size=0; } vecti(int n) { a=new int[n]; size=0; } public void add(int b) { if(++size==a.length) a=Arrays.copyOf(a, 2*size); a[size-1]=b; } public void sort() { Arrays.sort(a, 0, size); } public void sort(int l, int r) { Arrays.sort(a, l, r); } public iter iterator() { return new iter(this); } } static class lter { vectl a; int curi=0; lter(vectl b) { a=b; } public boolean hasNext() { if(a.size>curi) return true; return false; } public long next() { return a.a[curi++]; } public long prev() { return a.a[--curi]; } } static class vectl { long a[]; int size; vectl() { a=new long[10]; size=0; } vectl(int n) { a=new long[n]; size=0; } public void add(long b) { if(++size==a.length) a=Arrays.copyOf(a, 2*size); a[size-1]=b; } public void sort() { Arrays.sort(a, 0, size); } public void sort(int l, int r) { Arrays.sort(a, l, r); } public lter iterator() { return new lter(this); } } static class dter { vectd a; int curi=0; dter(vectd b) { a=b; } public boolean hasNext() { if(a.size>curi) return true; return false; } public double next() { return a.a[curi++]; } public double prev() { return a.a[--curi]; } } static class vectd { double a[]; int size; vectd() { a=new double[10]; size=0; } vectd(int n) { a=new double[n]; size=0; } public void add(double b) { if(++size==a.length) a=Arrays.copyOf(a, 2*size); a[size-1]=b; } public void sort() { Arrays.sort(a, 0, size); } public void sort(int l, int r) { Arrays.sort(a, l, r); } public dter iterator() { return new dter(this); } } //output functions//////////////// static void pr(Object a){output.append(a+"\n");} static void pr(){output.append("\n");} static void p(Object a){output.append(a);} static void pra(int[]a){for(int i:a)output.append(i+" ");output.append("\n");} static void pra(long[]a){for(long i:a)output.append(i+" ");output.append("\n");} static void pra(String[]a){for(String i:a)output.append(i+" ");output.append("\n");} static void pra(double[]a){for(double i:a)output.append(i+" ");output.append("\n");} static void sop(Object a){System.out.println(a);} static void flush(){System.out.println(output);output=new StringBuilder();} ////////////////////////////////// //input functions///////////////// static int ni(){return in.nextInt();} static long nl(){return Long.parseLong(in.next());} static String ns(){return in.next();} static double nd(){return Double.parseDouble(in.next());} static int[] nia(int n){int a[]=new int[n];for(int i=0; i<n; i++)a[i]=ni();return a;} static int[] pnia(int n){int a[]=new int[n+1];for(int i=1; i<=n; i++)a[i]=ni();return a;} static long[] nla(int n){long a[]=new long[n];for(int i=0; i<n; i++)a[i]=nl();return a;} static String[] nsa(int n){String a[]=new String[n];for(int i=0; i<n; i++)a[i]=ns();return a;} static double[] nda(int n){double a[]=new double[n];for(int i=0; i<n; i++)a[i]=nd();return a;} static vecti niv(int n) {vecti a=new vecti(n);a.size=n;for(int i=0; i<n; i++)a.a[i]=ni();return a;} static vectl nlv(int n) {vectl a=new vectl(n);a.size=n;for(int i=0; i<n; i++)a.a[i]=nl();return a;} static vectd ndv(int n) {vectd a=new vectd(n);a.size=n;for(int i=0; i<n; i++)a.a[i]=nd();return a;} ////////////////////////////////// //some utility functions static void exit(){System.exit(0);} static void psort(int[][] a) { Arrays.sort(a, new Comparator<int[]>() { @Override public int compare(int[]a,int[]b) { if(a[0]>b[0]) return 1; else if(b[0]>a[0]) return -1; return 0; } }); } static String pr(String a, long b) { String c=""; while(b>0) { if(b%2==1) c=c.concat(a); a=a.concat(a); b>>=1; } return c; } static long powm(long a, long b, long m) { long an=1; long c=a; while(b>0) { if(b%2==1) an=(an*c)%m; c=(c*c)%m; b>>=1; } return an; } static int gcd(int a, int b) { if(b==0) return a; else return gcd(b, a%b); } static class Reader { public BufferedReader reader; public StringTokenizer tokenizer; public Reader() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
0135bdd85d2affa49943b26756ec5f42
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.util.*; import java.io.*; public class Queue { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[1000001]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main(String[] args) throws IOException { Reader in=new Reader();PrintWriter out=new PrintWriter(System.out); String q=in.readLine().trim(); LinkedList<Integer> al=new LinkedList<>(); int c=0;boolean yes=false; for(int i=q.length()-1;i>=0;i--){ if(q.charAt(i)=='F'){++c;yes=true;}else{if(yes)al.add(c);c=0;} } ListIterator it=al.listIterator(); int ans=0,add=0; while(it.hasNext()){ int x=(int)it.next(); int v=Math.max(x+add-1-ans,0); ans+=v+1;add+=x; }out.print(ans); out.flush();out.close(); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
0dc1b76e9d1ddab463c614ca4435a57b
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
/* * Author- Priyam Vora * BTech 2nd Year DAIICT */ import java.io.*; import java.math.*; import java.util.*; import javax.print.attribute.SetOfIntegerSyntax; public class Main{ private static InputStream stream; private static byte[] buf = new byte[1024]; private static int curChar; private static int numChars; private static SpaceCharFilter filter; private static PrintWriter pw; public static void main(String[] args) { InputReader(System.in); pw = new PrintWriter(System.out); new Thread(null ,new Runnable(){ public void run(){ try{ soln(); pw.close(); } catch(Exception e){ e.printStackTrace(); } } },"1",1<<26).start(); } // To Get Input // Some Buffer Methods public static void InputReader(InputStream stream1) { stream = stream1; } private static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private static boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } private static 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++]; } private static 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; } private static 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; } private static String nextToken() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private static 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(); } private static int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } private static int[][] next2dArray(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] = nextInt(); } } return arr; } private static char[][] nextCharArray(int n,int m){ char [][]c=new char[n][m]; for(int i=0;i<n;i++){ String s=nextLine(); for(int j=0;j<s.length();j++){ c[i][j]=s.charAt(j); } } return c; } private static long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private static void pArray(int[] arr) { for (int i = 0; i < arr.length; i++) { pw.print(arr[i] + " "); } pw.println(); return; } private static void pArray(long[] arr) { for (int i = 0; i < arr.length; i++) { pw.print(arr[i] + " "); } pw.println(); return; } private static void pArray(boolean[] arr) { for (int i = 0; i < arr.length; i++) { pw.print(arr[i] + " "); } pw.println(); return; } private static boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } //----------------------------------------My Code------------------------------------------------// static LinkedList<Integer> adj[]; static boolean Visited[]; static int deg[]; static int V; static int subtree_size[]; static int i=0; private static void soln() { String s=nextLine(); long fin=0,curr=0; for(int i=0;i<s.length();i++){ if(s.charAt(i)=='M'){ curr++; }else{ if(curr>0) fin=Math.max(curr, fin+1); } } pw.println(fin); } public static int dfs(String s) { if(s.charAt(i++)=='l') return 1; else return Math.max(dfs(s),dfs(s))+1; } //-----------------------------------------The End--------------------------------------------------------------------------// private static void size(int curr,int par){ Visited[curr]=true; for(int x:adj[curr]){ if(!Visited[x]){ size(x,curr); } } subtree_size[par]+=subtree_size[curr]; } private static boolean isEulerian(){ int odd=0; for(int i=1;i<=V;i++){ if(adj[i].size()%2!=0){ odd++; } } if(odd==0 || odd==2){ return true; } return false; } private static boolean isConnected(){ int flag=1; for(int i=1;i<=V;i++){ if(adj[i].size()>0){ dfs(i); flag=0; break; } } if(flag==1){ return true; } for(int i=1;i<=V;i++){ if(adj[i].size()>0 && Visited[i]==false) return false; } return true; } private static void dfs(int curr){ Visited[curr]=true; for(int x:adj[curr]){ if(!Visited[x]) dfs(x); } } private static void buildGraph(){ adj=new LinkedList[V+1]; Visited=new boolean[V+1]; deg=new int[V+1]; subtree_size=new int[V+1]; Arrays.fill(subtree_size, 1); for(int i=0;i<=V;i++){ adj[i]=new LinkedList<Integer>(); } } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
3b1ffe30db56484ffb7d1f8531132558
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public final class Queue205D { public static void main(String ar[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); char[] cc = br.readLine().toCharArray(); int cnt = 0, delay = 0, max = 0; for (int i = 0; i < cc.length; i++) if (cc[i] == 'M') { cnt++; if (delay > 0) delay--; } else { if (cnt > 0) { max = Math.max(max, cnt + delay); delay++; } } System.out.println(max); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
a8e84066f4a7b8a544a8ab892e7f6cc7
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.*; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Double.parseDouble; import static java.lang.String.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder out = new StringBuilder(); StringTokenizer tk; String s = in.readLine(); int [] fem = new int[s.length()]; int [] ma = new int[s.length()]; int i = 0; if(s.charAt(0)=='F') { for(; i<s.length() && s.charAt(i)=='F'; i++) fem[i] = 0; } else ma[i++] = 1; for(; i<s.length(); i++) { if(s.charAt(i)=='F') { if(s.charAt(i-1)=='F') fem[i] = fem[i-1]+1; else fem[i] = max(ma[i-1],fem[i-1]+1); ma[i] = ma[i-1]; } else { ma[i] = ma[i-1]+1; fem[i] = fem[i-1]; } } for(i=s.length()-1; i>=0; i--) if(s.charAt(i)=='F') { System.out.println(fem[i]); return; } System.out.println("0"); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
480c2213d87f9edc87ac6c84efb8ec52
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Arthur Gazizov - Kazan FU #4.3 [2oo7] */ 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 { private static final char GIRL = 'F'; private static final char BOY = 'M'; private static final int MALE = 0; private static final int FEMALE = 1; private boolean isOnlyBoysOrGirls(String state) { return (state.contains("F") && !state.contains("M")) || (!state.contains("F") && state.contains("M")); } private boolean isGirlAlreadyInTop(String state) { if (state.charAt(0) != GIRL) { return false; } boolean boysStarted = false; for (int i = 1; i < state.length(); i++) { if (state.charAt(i) == BOY) { boysStarted = true; } if (state.charAt(i) == GIRL && boysStarted) { return false; } } return true; } private String make(String state) { return state.substring(state.indexOf(BOY)); } public void solve(int testNumber, InputReader in, OutputWriter out) { String state = in.next(); if (isOnlyBoysOrGirls(state) || isGirlAlreadyInTop(state)) { out.print(0); return; } else { state = make(state); } int[][] dp = new int[2][state.length()]; dp[MALE][0] = 1; int lastGirl = 0; for (int i = 1; i < state.length(); i++) { if (state.charAt(i) == GIRL) { lastGirl = i; if (state.charAt(i - 1) == GIRL) { dp[FEMALE][i] = dp[FEMALE][i - 1] + 1; } else { dp[FEMALE][i] = Math.max(dp[MALE][i - 1], dp[FEMALE][i - 1] + 1); } dp[MALE][i] = dp[MALE][i - 1]; } else { dp[MALE][i] = dp[MALE][i - 1] + 1; dp[FEMALE][i] = dp[FEMALE][i - 1]; } } out.print(dp[FEMALE][lastGirl]); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void print(int i) { writer.print(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { 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 readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
8b90d239b31911870d2d46fe410e27ea
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.io.*; public class CF353D { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); char[] cc = br.readLine().toCharArray(); int cnt = 0, delay = 0, max = 0; for (int i = 0; i < cc.length; i++) if (cc[i] == 'M') { cnt++; if (delay > 0) delay--; } else { if (cnt > 0) { max = Math.max(max, cnt + delay); delay++; } } System.out.println(max); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output