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
a518c8064ce790c2193a4a3480936b64
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.util.InputMismatchException; import java.util.LinkedList; public class EGlobalRound4 { public static void main(String[] args) { FastScanner in = new FastScanner(System.in); String g = in.next(); int N = g.length(); int[] arr = new int[N]; for(int i = 0; i < N; i++) { arr[i] = g.charAt(i) - 'a'; } StringBuilder sb = helper(N, arr, 0, 0); System.out.println(sb); } public static String ans(int N, int[] arr) { return null; } public static StringBuilder helper(int N, int[] arr, int first, int second) { @SuppressWarnings("unchecked") LinkedList<Integer>[] pos = new LinkedList[3]; for(int i = 0; i < 3; i++) pos[i] = new LinkedList<>(); for(int i = 0; i < N; i++) { pos[arr[i]].add(i); } int head = -1; int tail = N; int size = 0; StringBuilder sb = new StringBuilder(); while(head <= tail) { // System.out.println("head,tail = " + head + ", " + tail); if(head == tail && (arr[head] == first || arr[head] == second)) { // sb.append((char) (arr[head] + 'a')); // System.out.println("??????????"); break; } // System.out.println("befpre = " + Arrays.toString(pos)); int[][] next = new int[3][2]; for(int i = 0; i < 3; i++) { if(pos[i].size() > 0) { next[i][0] = pos[i].getFirst(); next[i][1] = pos[i].getLast(); } else { next[i][0] = -1; next[i][1] = -3; } } int index = -1; int max = -1; for(int i = 0; i < 3; i++) { int temp = next[i][1] - next[i][0]; if(temp > max) { max = temp; index = i; } } if(index == -1) { // System.out.println("AHH BREAK"); break; } sb.append((char) (index + 'a')); head = next[index][0]; tail = next[index][1]; // System.out.println("head,tail Result = " + head + ", " + tail); if(head != tail) size++; // System.out.println("index = " + index); pos[index].removeFirst(); if(head != tail) pos[index].removeLast(); for(int i = 0; i < 3; i++) { while(pos[i].size() > 0 && pos[i].getFirst() <= head) { pos[i].removeFirst(); } while(pos[i].size() > 0 && pos[i].getLast() >= tail) { pos[i].removeLast(); } } // System.out.println("afterward: " + Arrays.toString(pos)); // System.out.println(); } String temp = sb.toString(); StringBuilder sb2 = new StringBuilder(); sb2.append(temp); for(int i = size-1; i >= 0; i--) { sb2.append(temp.charAt(i)); } return sb2; } /** * Source: Matt Fontaine */ static class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int chars; public FastScanner(InputStream stream) { this.stream = stream; } int read() { if (chars == -1) throw new InputMismatchException(); if (curChar >= chars) { curChar = 0; try { chars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (chars <= 0) return -1; } return buf[curChar++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String next() { 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 (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } } } /* cacbac outputCopy aba inputCopy abc outputCopy a inputCopy cbacacacbcbababacbcb outputCopy cbaaacbcaaabc */
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
22b4e20a780ba30caa886bd5878a7bab
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
256 megabytes
import java.util.*; import java.math.*; // **** E. Archaeology **** public class E { static char [] in = new char [1000001]; public static void main (String [] arg) throws Throwable { char [] s = next().toCharArray(); int [] freq = new int [256]; for (int i =0;i <s.length;++i) freq[s[i]]++; char pivot = 'a'; if (freq['b'] > freq['a']) pivot = 'b'; if (freq['c'] > freq['b'] && freq['c'] > freq['a']) pivot = 'c'; //System.err.println("Pivot is " + pivot); int L = 0; int R = s.length-1; StringBuilder ans = new StringBuilder(s.length); StringBuilder ansR= new StringBuilder(s.length); while (L <= R) { int pL = L; int pR = R; while (L <s.length && s[L] != pivot) ++L; while (R >= 0 && s[R] != pivot) --R; //System.err.println("AT " + L + " , " +R); int distR = pR - R; int distL = L - pL; while (distR > 0 && distL > 0 && distR + R >= L - distL) { if ( s[distR + R] != s[L - distL]) { if (distR > distL) distR--; else distL--; } if (distR <= 0 || distL <= 0) break; if (distR + R == L - distL) { ans = ans.append(s[L-distL]); break; } ans = ans.append(s[L-distL]); ansR = ansR.append(s[distR + R]); distR--; distL--; } if (R >= L) ans = ans.append(pivot); if (R > L) ansR = ansR.append(pivot); R--; L++; } ans = ans.append(ansR.reverse()); System.out.println((ans.length() < s.length/2) ? "IMPOSSIBLE" : ans); } /************** HELPER CLASSES ***************/ //static class HS extends HashSet<Integer>{public HS(){super();}public HS(int a){super(a);}}; //static class AL extends ArrayList<Integer>{public AL(){super();}public AL(int a){super (a);}}; static class Pair implements Comparable<Pair> { int i,j;long L; public Pair(int xx, int yy, long LL){i=xx;j=yy;L=LL;} public int compareTo(Pair p) { return (this.L < p.L) ? -1 : ((this.L == p.L && this.i < p.i) ? -1 : 1);} } /************** FAST IO CODE FOLLOWS *****************/ public static long nextLong() throws Throwable { long i = System.in.read();boolean neg = false;while (i < 33) i = System.in.read();if (i == 45) {neg=true;i=48;}i = i - 48; int j = System.in.read();while (j > 32) {i*=10;i+=j-48;j = System.in.read();}return (neg) ? -i : i; } public static int nextInt() throws Throwable {return (int)nextLong();} public static String next() throws Throwable { int i = 0; while (i < 33 && i != -1) i = System.in.read(); int cptr = 0; while (i >= 33) { in[cptr++] = (char)i; i = System.in.read();} return new String(in, 0,cptr); } /**** LIBRARIES ****/ public static long gcdL(long a, long b) {while (b != 0) {long tmp = b;b = (a % b);a = tmp;}return a;} public static int gcd(int a, int b) {while (b != 0) {int tmp = b;b = (a % b);a = tmp;}return a;} public static int[] sieve(int LIM) { int i,count = 0; boolean [] b = new boolean [LIM]; for (i = 2;i<LIM; ++i) if (!b[i]) {count++; for (int j = i<<1; j<LIM; j+=i) b[j] = true;} int [] primes = new int[count]; for (i = 2,count=0;i<LIM;++i) if (!b[i]) primes[count++] = i; return primes; } public static int[] numPrimeFactors(int LIM) { int i,count = 0; int [] b = new int [LIM]; for (i = 2;i<LIM; ++i) if (b[i] == 0) {count++; for (int j = i; j<LIM; j+=i) b[j]++;} return b; } public static StringBuilder stringFromArray(int [] a) { StringBuilder b = new StringBuilder(9*a.length); for (int i = 0; i<a.length; ++i) { if (i != 0) b = b.append(' '); b = b.append(a[i]); } return b; } public static long modPow (long a, long n, long MOD) { long S = 1; for (;n > 0; n>>=1, a=(a*a)%MOD) if ((n & 1) != 0) S = (a*S) % MOD; return S;} } /* Full Problem Text: Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it? The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it. A string a is a subsequence of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters. */
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
791ff0e031f2743a39c21e8e5da4c19b
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
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 ilyakor */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { public void solve(int testNumber, InputReader in, OutputWriter out) { char[] s = in.nextToken().toCharArray(); StringBuilder sb = new StringBuilder(); int l = 0, r = s.length - 1; while (l + 1 < r - 1) { char c = '?'; if (s[l] == s[r]) c = s[l]; else if (s[l] == s[r - 1]) c = s[l]; else if (s[l + 1] == s[r]) c = s[l + 1]; else if (s[l + 1] == s[r - 1]) c = s[l + 1]; if (c == '?') throw new RuntimeException(); sb.append(c); l += 2; r -= 2; } String res; if (l < r) { if (r - l > 2) throw new RuntimeException(); res = sb.toString() + s[l] + sb.reverse().toString(); } else { res = sb.toString() + sb.reverse().toString(); } if (res.length() < s.length / 2) throw new RuntimeException(); out.printLine(res); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class InputReader { private InputStream stream; private byte[] buffer = new byte[10000]; private int cur; private int count; public InputReader(InputStream stream) { this.stream = stream; } public static boolean isSpace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int read() { if (count == -1) { throw new InputMismatchException(); } try { if (cur >= count) { cur = 0; count = stream.read(buffer); if (count <= 0) return -1; } } catch (IOException e) { throw new InputMismatchException(); } return buffer[cur++]; } public int readSkipSpace() { int c; do { c = read(); } while (isSpace(c)); return c; } public String nextToken() { int c = readSkipSpace(); StringBuilder sb = new StringBuilder(); while (!isSpace(c)) { sb.append((char) c); c = read(); } return sb.toString(); } } }
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
ec03dea1636c94a8b0cd8ad8ecd3e36f
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Random; import java.util.StringTokenizer; import java.util.TreeMap; public class Solution{ public static void main(String[] args) throws IOException { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int tt = 1; while(tt-->0) { char[] ch = fs.next().toCharArray(); int n =ch.length; int l = 0; int r = n-1; StringBuilder str = new StringBuilder(""); while(r-l>=3) { if(ch[l]==ch[r]) { str.append(ch[l]); ++l; --r; } else if(ch[l]==ch[r-1]) { str.append(ch[l]); ++l; r -= 2; } else { str.append(ch[l+1]); if(ch[l+1]==ch[r]) --r; else if(ch[l+1]==ch[r-1]) r -= 2; l += 2; } } out.print(str.toString()); if(l<=r) out.print(ch[l]); out.print(str.reverse().toString()); } out.close(); } static final Random random=new Random(); static void ruffleSort(int[] a) { int n=a.length;//shuffle, then sort for (int i=0; i<n; i++) { int oi=random.nextInt(n); int temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static class FastScanner{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next(){ while(!st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); } catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt(){ return Integer.parseInt(next()); } public int[] readArray(int n){ int[] a = new int[n]; for(int i=0;i<n;i++) a[i] = nextInt(); return a; } public long nextLong() { return Long.parseLong(next()); } public char nextChar() { return next().toCharArray()[0]; } } }
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
0fad3b889efe40ebb929113ffb277bba
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
256 megabytes
import java.util.*; import java.io.*; public class codeforces{ // Input static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader() { reader = new BufferedReader(new InputStreamReader(System.in)); 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()); } public String nextLine() { String s = null; try { s = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return s; } public String nextParagraph() { String line = null; String ans = ""; try { while ((line = reader.readLine()) != null) { ans += line; } } catch (IOException e) { throw new RuntimeException(e); } return ans; } } //Template static int mod = 998244353; static void printArray(int ar[]){ for(int x:ar) System.out.print(x+" ");} static void printArray(ArrayList<Integer> ar){ for(int x:ar) System.out.print(x+" ");} static int gcd(int a, int b){ if (a == 0) return b; return gcd(b%a, a);} static long power(long x, long y, int p) { long res = 1; x = x % p; while (y > 0) { if((y & 1)==1) res = (res * x) % p; y = y >> 1;x = (x * x) % p; } return res;} static void takeArrayInput(InputReader sc, int ar[]){ for(int i=0;i<ar.length;i++) ar[i]=sc.nextInt(); } static void takeArrayInput(InputReader sc, long ar[]){ for(int i=0;i<ar.length;i++) ar[i]=sc.nextLong(); } static void take2dArrayInput(InputReader sc, int ar[][]){ for(int i=0;i<ar.length;i++) for(int j=0;j<ar[i].length;j++) ar[i][j]=sc.nextInt(); } static void take2dArrayInput(InputReader sc, long ar[][]){ for(int i=0;i<ar.length;i++) for(int j=0;j<ar[i].length;j++) ar[i][j]=sc.nextLong(); } static ArrayList<ArrayList<Integer>> graph(InputReader sc, int n, int m){ ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(); for(int i=0;i<n;i++) list.add(new ArrayList<Integer>()); for(int i=0;i<m;i++){ int u = sc.nextInt(); int v = sc.nextInt(); list.get(u).add(v); list.get(v).add(u); } return list; } // Write Code Here static class Data { int u; int v; public Data(int e, int val) { this.u = e; this.v = val; } } static void sieveOfEratosthenes(int n, ArrayList<Integer> pr) { // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. 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] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p pr.add(p); for (int i = p * p; i <= n; i += p) prime[i] = false; } } } public static void main(String args[]) { InputReader sc = new InputReader(); PrintWriter pw = new PrintWriter(System.out); String s = sc.nextLine(); char c[] = s.toCharArray(); int i=0, j=s.length()-1; StringBuilder p = new StringBuilder(""); while((j - i) >= 3){ if(c[i] == c[j]){ p.append(c[i]); i++;j--; }else if(c[i] == c[j-1]){ p.append(c[i]); i++;j -= 2; }else if(c[i+1] == c[j]){ p.append(c[i+1]); i+=2;j--; }else{ p.append(c[i+1]); i+=2;j-=2; } } StringBuilder sb = new StringBuilder(p.toString()); sb.reverse(); if(j >= i) p.append(c[j]); pw.print(p.append(sb.toString()).toString()); pw.close(); } }
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
79bd3f22944bdaaf0c393d4379fa2004
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
256 megabytes
import java.io.*; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Queue; import java.util.StringTokenizer; public class Archaeology { public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(f.readLine()); char[] str = StringUtils.toCharArray(st.nextToken(), 0); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); String ans = ""; String ansReverse = ""; int low = 0; int high = str.length-1; boolean[] used = new boolean[str.length]; while (high - low >= 3) { boolean flag = false; for (int addLow = 0; addLow <= 1; addLow++) { for (int subtractHigh = 0; subtractHigh <= 1; subtractHigh++) { if (str[low + addLow] == str[high - subtractHigh]) { used[low + addLow] = true; used[high - subtractHigh] = true; flag = true; break; } } if (flag) { break; } } low += 2; high -= 2; } String finalStr = ans.toString() + ansReverse; if (low < high) { used[(low + high)/2] = true; } for (int i = 0; i < str.length; i++) { if (used[i]) { out.print(str[i]); } } out.close(); } static class StringUtils { public static char[] toCharArray(String s, int stIndex) { char[] result = new char[s.length() + stIndex]; for (int i = 0; i < s.length(); i++) { result[i + stIndex] = s.charAt(i); } return result; } } }
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
3a12683fe9efc6a4031f4257440dbdf6
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String s = scanner.nextLine(); String ans1 = oneLetterCenter(s, s.length() / 2); String ans2 = oneLetterCenter(s, s.length() / 2 - 1); if (ans1.length() > ans2.length()) System.out.println(ans1); else System.out.println(ans2); } static String oneLetterCenter(String str, int center) { int l = center, r = center; StringBuilder ans = new StringBuilder(); ans.append(str.charAt(center)); while (1 <= l && r <= str.length() - 2) { char l1 = 'm', l2 = 'n', r1 = 'k', r2 = 'p'; if (l - 2 >= 0) l1 = str.charAt(l - 2); if (l - 1 >= 0) l2 = str.charAt(l - 1); if (r + 1 <= str.length() - 1) r1 = str.charAt(r + 1); if (r + 2 <= str.length() - 1) r2 = str.charAt(r + 2); if (l1 == r1) { l -= 2; r += 1; ans.append(l1); } else if (l1 == r2) { l -= 2; r += 2; ans.append(l1); } else if (l2 == r1) { l -= 1; r += 1; ans.append(l2); } else if (l2 == r2) { l -= 1; r += 2; ans.append(l2); } else { break; } } StringBuilder last = new StringBuilder(ans); last.reverse(); last.deleteCharAt(last.length() - 1); return last.toString() + ans.toString(); } }
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
69b096e8a11049f78d7b491d0b1231e6
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.*; import java.util.concurrent.ThreadLocalRandom; public class Main2 { static long mod = 998244353; static FastScanner scanner; public static void main(String[] args) { scanner = new FastScanner(); String s = scanner.nextToken(); int[][] nextPosForward = nextPos(s); int[][] nextPosBackward = nextPosBack(s); int i = 0; int j = s.length() - 1; StringBuilder builder = new StringBuilder(); char last = 0; while (i < j) { if (s.charAt(i) == s.charAt(j)) { builder.append(s.charAt(i)); i++; j--; last = 0; continue; } last = s.charAt(j); int minD = Integer.MAX_VALUE; int best = -1; for (int k = 0; k < 3; k++) { int nextI = nextPosForward[i][k]; int nextJ = nextPosBackward[j][k]; if (nextI == -1 || nextJ == -1) continue;; int distance = (nextI - i) + (j - nextJ); if (minD > distance) { minD = distance; best = k; } } if (best == -1) { break; } i = nextPosForward[i][best]; j = nextPosBackward[j][best]; } String res; if (last != 0) { res = builder.toString() + last + builder.reverse().toString(); } else { res = builder.toString()+ builder.reverse().toString(); } System.out.println(res); } static int[][] nextPos(String a) { int[][] result = new int[a.length()][3]; for (int i = 0; i < a.length(); i++) for (int j = 0; j < 3; j++) result[i][j] = -1; for (int i = a.length() - 1; i >= 0; i--) { if (i != a.length() - 1) { result[i][0] = result[i + 1][0]; result[i][1] = result[i + 1][1]; result[i][2] = result[i + 1][2]; } result[i][a.charAt(i) - 'a'] = i; } return result; } static int[][] nextPosBack(String a) { int[][] result = new int[a.length()][3]; for (int i = 0; i < a.length(); i++) for (int j = 0; j < 3; j++) result[i][j] = -1; for (int i = 0; i < a.length(); i++) { if (i != 0) { result[i][0] = result[i - 1][0]; result[i][1] = result[i - 1][1]; result[i][2] = result[i - 1][2]; } result[i][a.charAt(i) - 'a'] = i; } return result; } static class WithIdx implements Comparable<WithIdx>{ int val, idx; public WithIdx(int val, int idx) { this.val = val; this.idx = idx; } @Override public int compareTo(WithIdx o) { return Integer.compare(val, o.val); } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } String nextLine() { try { return br.readLine(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(); } } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } int[] nextIntArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) res[i] = nextInt(); return res; } long[] nextLongArray(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) res[i] = nextLong(); return res; } String[] nextStringArray(int n) { String[] res = new String[n]; for (int i = 0; i < n; i++) res[i] = nextToken(); return res; } } static class PrefixSums { long[] sums; public PrefixSums(long[] sums) { this.sums = sums; } public long sum(int fromInclusive, int toExclusive) { if (fromInclusive > toExclusive) throw new IllegalArgumentException("Wrong value"); return sums[toExclusive] - sums[fromInclusive]; } public static PrefixSums of(int[] ar) { long[] sums = new long[ar.length + 1]; for (int i = 1; i <= ar.length; i++) { sums[i] = sums[i - 1] + ar[i - 1]; } return new PrefixSums(sums); } public static PrefixSums of(long[] ar) { long[] sums = new long[ar.length + 1]; for (int i = 1; i <= ar.length; i++) { sums[i] = sums[i - 1] + ar[i - 1]; } return new PrefixSums(sums); } } static class ADUtils { static void sort(int[] ar) { Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } Arrays.sort(ar); } static void reverse(int[] arr) { int last = arr.length / 2; for (int i = 0; i < last; i++) { int tmp = arr[i]; arr[i] = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = tmp; } } static void sort(long[] ar) { Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); // Simple swap long a = ar[index]; ar[index] = ar[i]; ar[i] = a; } Arrays.sort(ar); } } static class MathUtils { static long[] FIRST_PRIMES = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89 , 97 , 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051}; static long[] primes(int to) { long[] all = new long[to + 1]; long[] primes = new long[to + 1]; all[1] = 1; int primesLength = 0; for (int i = 2; i <= to; i ++) { if (all[i] == 0) { primes[primesLength++] = i; all[i] = i; } for (int j = 0; j < primesLength && i * primes[j] <= to && all[i] >= primes[j]; j++) { all[(int) (i * primes[j])] = primes[j]; } } return Arrays.copyOf(primes, primesLength); } static long modpow(long b, long e, long m) { long result = 1; while (e > 0) { if ((e & 1) == 1) { /* multiply in this bit's contribution while using modulus to keep * result small */ result = (result * b) % m; } b = (b * b) % m; e >>= 1; } return result; } static long submod(long x, long y, long m) { return (x - y + m) % m; } } }
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
ab8a56c9361501766b46703b8f103841
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
256 megabytes
import java.util.*; import java.io.*; public class E { public static void main(String[] args) { Scanner f = new Scanner(System.in); String s = f.nextLine(); int n = s.length(); boolean[] out = new boolean[n]; for (int i = 0; i+1 < n-2-i; i+=2) { int[] cnt = new int[3], inds = {n-2-i,n-1-i}; cnt[s.charAt(i) - 97] = i+1; cnt[s.charAt(i+1) - 97]=i+2; for (int ind : inds) { int c = s.charAt(ind) - 97; if (cnt[c] != 0) {out[ind] = true; out[cnt[c]-1] = true; break;} } } if (n % 4 > 0) out[n / 2] = true; StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { if (out[i]) sb.append(s.charAt(i)); } System.out.println(sb.toString()); } }
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
76ce969d4129ad1fe9b92522c55eadb5
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
256 megabytes
import java.io.*; import java.util.*; public class A { BufferedReader in; StringTokenizer st; PrintWriter out; String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } double nextDouble() throws Exception { return Double.parseDouble(next()); } void solve() throws Exception { char s[] = next().toCharArray(); int n = s.length; boolean take[] = new boolean[n]; int l = 0; int r = n-1; while(l!=r) { if(s[l] == s[r]) { take[l] = true; take[r] = true; l++; r--; } else if(s[l+1] == s[r]) take[l++] = false; else take[r--] = false; } if(l==r) take[l] = true; StringBuilder ans = new StringBuilder(); for(int i=0;i<n;i++) if(take[i]) ans.append(s[i]); out.println(ans); } void run() { try { Locale.setDefault(Locale.US); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } public static void main(String[] args) { new A().run(); } }
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
7a2160eaaca0bbf96a47efc169382501
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
256 megabytes
import java.util.*; import java.io.*; public class Solution{ public static Integer INT(String s){ return Integer.parseInt(s); } public static Long LONG(String s){ return Long.parseLong(s); } //==================================================================================================================== public static void main(String args[])throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); Scanner in=new Scanner(System.in); StringBuilder out=new StringBuilder(); char s[]=in.next().toCharArray(); int n=s.length; boolean flag[]=new boolean[n]; int i=0, j=n-1; while(i<j){ if(s[i]==s[j]){ flag[i]=flag[j]=true; i+=1; j-=1; } else if(s[i]==s[j-1]){ flag[i]=flag[j-1]=true; i+=1; j-=2; } else if(s[i+1]==s[j]){ flag[i+1]=flag[j]=true; i+=2; j-=1; } else if(s[i+1]==s[j-1]){ flag[i+1]=flag[j-1]=true; i+=2; j-=2; } } for(int k=0; k<n; k++) if(flag[k]) out.append(s[k]); System.out.println(out); } }
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
a6fbaf4f91f3edbf6f3832367d00a4d9
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.SortedSet; import java.io.IOException; import java.io.InputStreamReader; import java.util.TreeSet; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; public class _1178E { public static void main(String[] args) { InputReader in = new InputReader(); String s = in.nextLine(); StringBuilder ansBuilder = new StringBuilder(); boolean[] seen; char[] chars = new char[4]; int charIndex; for (int i = 0; i < s.length() / 2 - 1; i += 2) { seen = new boolean[3]; chars[0] = s.charAt(i); chars[1] = s.charAt(i+1); chars[2] = s.charAt(s.length() - 1 - i); chars[3] = s.charAt(s.length() - 1 - i - 1); charIndex = -1; for (int j = 0; j < 4; j++) { switch (chars[j]) { case 'a': charIndex = 0; break; case 'b': charIndex = 1; break; case 'c': charIndex = 2; break; } if (seen[charIndex]) { ansBuilder.append(chars[j]); break; } else { seen[charIndex] = true; } } } String ans = ansBuilder.toString(); String revAns = ansBuilder.reverse().toString(); String middle = ""; if (s.length() % 4 != 0) { middle = Character.toString(s.charAt(s.length() / 2)); } System.out.println(ans + middle + revAns); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader() { reader = new BufferedReader(new InputStreamReader(System.in)); 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()); } public String nextLine() { String str = ""; try { str = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
47d2d222339b77e0bd9c945eb55a3c21
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
256 megabytes
import java.io.*; import java.util.LinkedList; import java.util.Stack; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); char[] s = sc.next().toCharArray(); int n = s.length; int min = n / 2; int right = n - 1; Stack<Character> l = new Stack<>(); LinkedList<Character> r = new LinkedList<>(); int cnt = 0; for (int i = 0; i < n && cnt < min; i++) { if (cnt == min - 1) { r.add(s[i]); cnt++; break; } if (s[right] == s[i]) { r.addLast(s[i]); l.add(s[right--]); cnt += 2; continue; } right--; if (s[right] == s[i]) { r.addLast(s[i]); l.add(s[right--]); cnt += 2; continue; } else right++; } if (cnt < min) out.println("IMPOSSIBLE"); else { while (!r.isEmpty()) out.print(r.removeFirst()); while (!l.isEmpty()) out.print(l.pop()); } out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } 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 Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) throws IOException { double[] ans = new double[n]; for (int i = 0; i < n; i++) ans[i] = nextDouble(); return ans; } public short nextShort() throws IOException { return Short.parseShort(next()); } } }
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
3fbce4425182fc98b7e6f81dfba633cc
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; import java.math.*; public class E { public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); // int n = Integer.parseInt(bf.readLine()); // StringTokenizer st = new StringTokenizer(bf.readLine()); // int[] a = new int[n]; for(int i=0; i<n; i++) a[i] = Integer.parseInt(st.nextToken()); // int n = Integer.parseInt(st.nextToken()); String s = bf.readLine(); String t = new StringBuilder(s).reverse().toString(); int n = s.length(); StringBuilder ans = new StringBuilder(); for(int i=0; i<n/4; i++) { int[] a = new int[3]; for(int j=i*2; j<i*2+2; j++) a[s.charAt(j)-'a']++; for(int j=i*2; j<i*2+2; j++) a[t.charAt(j)-'a']++; for(int j=0; j<3; j++) { if(a[j] >= 2) { ans.append((char)('a'+j)); break; } } } String aans = ans.toString(); if(n%4 != 0) ans.append(s.charAt((n/4) * 2)); String aaans = aans + ans.reverse().toString(); out.println(aaans); out.close(); System.exit(0); } }
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
05b60aecbf7d219097e4ba4fdd7df5ff
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
256 megabytes
// Don't place your source in a package import java.util.*; import java.lang.*; import java.io.*; import java.math.*; // Please name your class Main public class Main { //static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); /*static int read() throws IOException { in.nextToken(); return (int) in.nval; } static String readString() throws IOException { in.nextToken(); return in.sval; }*/ static Scanner in = new Scanner(System.in); public static void main (String[] args) throws java.lang.Exception { //InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int T=1; for(int t=0;t<T;t++){ String s=Str(); Solution sol=new Solution(); sol.solution(s); } out.flush(); } public static long Long(){ return in.nextLong(); } public static int Int(){ return in.nextInt(); } public static String Str(){ return in.next(); } } class Solution{ //constant variable final int MAX=Integer.MAX_VALUE; final int MIN=Integer.MIN_VALUE; //Set<Integer>adjecent[]; ////////////////////////////// public void fastprint(PrintWriter out,String s){ out.print(s); } public void fastprintln(PrintWriter out,String s){ out.println(s); } public void solution(String s){ if(s.length()<=3){ msg(s.charAt(0)+"");return; } int n=s.length(); StringBuilder str=new StringBuilder(); boolean check[]=new boolean[n]; int cnt=0; int r=n-1; for(int i=0;i<s.length();i++){ if(cnt+1>=n/2){ check[i]=true; break; } char c=s.charAt(i); char c1=s.charAt(r); char c2=s.charAt(r-1); if(c==c1||c==c2){ if(c==c1){ check[i]=true; check[r]=true; r--; } else{ check[i]=true; check[r-1]=true; r-=2; } cnt+=2; } else{ } } for(int i=0;i<n;i++){ if(check[i]){ str.append(s.charAt(i)+""); } } msg(str.toString()); } /*class LCA{ int p1,p2; boolean visit[]; int res=-1; boolean good=false; public LCA(int p1,int p2){ this.p1=p1;this.p2=p2; visit=new boolean[adjecent.length]; } public boolean dfs(int root){ visit[root]=true; List<Integer>next=adjecent[root]; boolean ans=false; if(root==p1||root==p2){ ans=true; } int cnt=0; for(int c:next){ if(visit[c])continue; boolean v=dfs(c); ans|=v; if(v)cnt++; } if(cnt==2){ if(!good){ good=true; res=root; } } else if(cnt==1){ if(!good&&(root==p1||root==p2)){ good=true; res=root; } } return ans; } }*/ /*public void delete(Dnode node){ Dnode pre=node.pre; Dnode next=node.next; pre.next=next; next.pre=pre; map.remove(node.v); } public void add(int v){ Dnode node=new Dnode(v); Dnode pre=tail.pre; pre.next=node; node.pre=pre; node.next=tail; tail.pre=node; map.put(v,node); } class Dnode{ Dnode next=null; Dnode pre=null; int v; public Dnode(int v){ this.v=v; } }*/ public String tobin(int i){ return Integer.toBinaryString(i); } public void reverse(int A[]){ List<Integer>l=new ArrayList<>(); for(int i:A)l.add(i); Collections.reverse(l); for(int i=0;i<A.length;i++){ A[i]=l.get(i); } } public void sort(int A[]){ Arrays.sort(A); } public void swap(int A[],int l,int r){ int t=A[l]; A[l]=A[r]; A[r]=t; } public long C(long fact[],int i,int j){ // C(20,3)=20!/(17!*3!) // take a/b where a=20! b=17!*3! if(j>i)return 1; if(j<=0)return 1; long mod=998244353; long a=fact[i]; long b=((fact[i-j]%mod)*(fact[j]%mod))%mod; BigInteger B= BigInteger.valueOf(b); long binverse=B.modInverse(BigInteger.valueOf(mod)).longValue(); return ((a)*(binverse%mod))%mod; } public long gcd(long a, long b) { if (a == 0) return b; return gcd(b%a, a); } //map operation public void put(Map<Integer,Integer>map,int i){ if(!map.containsKey(i))map.put(i,0); map.put(i,map.get(i)+1); } public void delete(Map<Integer,Integer>map,int i){ map.put(i,map.get(i)-1); if(map.get(i)==0)map.remove(i); } /*public void tarjan(int p,int r){ if(cut)return; List<Integer>childs=adjecent[r]; dis[r]=low[r]=time; time++; //core for tarjan int son=0; for(int c:childs){ if(ban==c||c==p)continue; if(dis[c]==-1){ son++; tarjan(r,c); low[r]=Math.min(low[r],low[c]); if((r==root&&son>1)||(low[c]>=dis[r]&&r!=root)){ cut=true; return; } }else{ if(c!=p){ low[r]=Math.min(low[r],dis[c]); } } } }*/ //helper function I would use public void remove(Map<Integer,Integer>map,int i){ map.put(i,map.get(i)-1); if(map.get(i)==0)map.remove(i); } public void ascii(String s){ for(char c:s.toCharArray()){ System.out.print((c-'a')+" "); } msg(""); } public int flip(int i){ if(i==0)return 1; else return 0; } public boolean[] primes(int n){ boolean A[]=new boolean[n+1]; for(int i=2;i<=n;i++){ if(A[i]==false){ for(int j=i+i;j<=n;j+=i){ A[j]=true; } } } return A; } public void msg(String s){ System.out.println(s); } public void msg1(String s){ System.out.print(s); } public int[] kmpPre(String p){ int pre[]=new int[p.length()]; int l=0,r=1; while(r<p.length()){ if(p.charAt(l)==p.charAt(r)){ pre[r]=l+1; l++;r++; }else{ if(l==0)r++; else l=pre[l-1]; } } return pre; } public boolean isP(String s){ int l=0,r=s.length()-1; while(l<r){ if(s.charAt(l)!=s.charAt(r))return false; l++;r--; } return true; } public int find(int nums[],int x){//union find => find method if(nums[x]==x)return x; int root=find(nums,nums[x]); nums[x]=root; return root; } public int[] copy1(int A[]){ int a[]=new int[A.length]; for(int i=0;i<a.length;i++)a[i]=A[i]; return a; } public void print1(int A[]){ for(long i:A)System.out.print(i+" "); System.out.println(); } public void print2(int A[][]){ for(int i=0;i<A.length;i++){ for(int j=0;j<A[0].length;j++){ System.out.print(A[i][j]+" "); }System.out.println(); } } public int min(int a,int b){ return Math.min(a,b); } public int[][] matrixdp(int[][] grid) { if(grid.length==0)return new int[][]{}; int res[][]=new int[grid.length][grid[0].length]; for(int i=0;i<grid.length;i++){ for(int j=0;j<grid[0].length;j++){ res[i][j]=grid[i][j]+get(res,i-1,j)+get(res,i,j-1)-get(res,i-1,j-1); } } return res; } public int get(int grid[][],int i,int j){ if(i<0||j<0||i>=grid.length||j>=grid[0].length)return 0; return grid[i][j]; } public int[] suffixArray(String s){ int n=s.length(); Suffix A[]=new Suffix[n]; for(int i=0;i<n;i++){ A[i]=new Suffix(i,s.charAt(i)-'a',0); } for(int i=0;i<n;i++){ if(i==n-1){ A[i].next=-1; }else{ A[i].next=A[i+1].rank; } } Arrays.sort(A); for(int len=4;len<A.length*2;len<<=1){ int in[]=new int[A.length]; int rank=0; int pre=A[0].rank; A[0].rank=rank; in[A[0].index]=0; for(int i=1;i<A.length;i++){//rank for the first two letter if(A[i].rank==pre&&A[i].next==A[i-1].next){ pre=A[i].rank; A[i].rank=rank; }else{ pre=A[i].rank; A[i].rank=++rank; } in[A[i].index]=i; } for(int i=0;i<A.length;i++){ int next=A[i].index+len/2; if(next>=A.length){ A[i].next=-1; }else{ A[i].next=A[in[next]].rank; } } Arrays.sort(A); } int su[]=new int[A.length]; for(int i=0;i<su.length;i++){ su[i]=A[i].index; } return su; } } //suffix array Struct class Suffix implements Comparable<Suffix>{ int index; int rank; int next; public Suffix(int i,int rank,int next){ this.index=i; this.rank=rank; this.next=next; } @Override public int compareTo(Suffix other) { if(this.rank==other.rank){ return this.next-other.next; } return this.rank-other.rank; } public String toString(){ return this.index+" "+this.rank+" "+this.next+" "; } } class Wrapper implements Comparable<Wrapper>{ int spf;int cnt; public Wrapper(int spf,int cnt){ this.spf=spf; this.cnt=cnt; } @Override public int compareTo(Wrapper other) { return this.spf-other.spf; } } class Node{//what the range would be for that particular node boolean state=false; int l=0,r=0; int ll=0,rr=0; public Node(boolean state){ this.state=state; } } class Seg1{ int A[]; public Seg1(int A[]){ this.A=A; } public void update(int left,int right,int val,int s,int e,int id){ if(left<0||right<0||left>right)return; if(left==s&&right==e){ A[id]+=val; return; } int mid=s+(e-s)/2; //[s,mid] [mid+1,e] if(left>=mid+1){ update(left,right,val,mid+1,e,id*2+2); }else if(right<=mid){ update(left,right,val,s,mid,id*2+1); }else{ update(left,mid,val,s,mid,id*2+1); update(mid+1,right,val,mid+1,e,id*2+2); } } public int query(int i,int add,int s,int e,int id){ if(s==e&&i==s){ return A[id]+add; } int mid=s+(e-s)/2; //[s,mid] [mid+1,e] if(i>=mid+1){ return query(i,A[id]+add,mid+1,e,id*2+2); }else{ return query(i,A[id]+add,s,mid,id*2+1); } } } class MaxFlow{ public static List<Edge>[] createGraph(int nodes) { List<Edge>[] graph = new List[nodes]; for (int i = 0; i < nodes; i++) graph[i] = new ArrayList<>(); return graph; } public static void addEdge(List<Edge>[] graph, int s, int t, int cap) { graph[s].add(new Edge(t, graph[t].size(), cap)); graph[t].add(new Edge(s, graph[s].size() - 1, 0)); } static boolean dinicBfs(List<Edge>[] graph, int src, int dest, int[] dist) { Arrays.fill(dist, -1); dist[src] = 0; int[] Q = new int[graph.length]; int sizeQ = 0; Q[sizeQ++] = src; for (int i = 0; i < sizeQ; i++) { int u = Q[i]; for (Edge e : graph[u]) { if (dist[e.t] < 0 && e.f < e.cap) { dist[e.t] = dist[u] + 1; Q[sizeQ++] = e.t; } } } return dist[dest] >= 0; } static int dinicDfs(List<Edge>[] graph, int[] ptr, int[] dist, int dest, int u, int f) { if (u == dest) return f; for (; ptr[u] < graph[u].size(); ++ptr[u]) { Edge e = graph[u].get(ptr[u]); if (dist[e.t] == dist[u] + 1 && e.f < e.cap) { int df = dinicDfs(graph, ptr, dist, dest, e.t, Math.min(f, e.cap - e.f)); if (df > 0) { e.f += df; graph[e.t].get(e.rev).f -= df; return df; } } } return 0; } public static int maxFlow(List<Edge>[] graph, int src, int dest) { int flow = 0; int[] dist = new int[graph.length]; while (dinicBfs(graph, src, dest, dist)) { int[] ptr = new int[graph.length]; while (true) { int df = dinicDfs(graph, ptr, dist, dest, src, Integer.MAX_VALUE); if (df == 0) break; flow += df; } } return flow; } } class Edge { int t, rev, cap, f; public Edge(int t, int rev, int cap) { this.t = t; this.rev = rev; this.cap = cap; } } class Seg{ int l,r; int min=Integer.MAX_VALUE; Seg left=null,right=null; int tree[]; public Seg(int l,int r){ this.l=l; this.r=r; if(l!=r){ int mid=l+(r-l)/2; if(l<=mid)left=new Seg(l,mid); if(r>=mid+1)right=new Seg(mid+1,r); if(left!=null)min=Math.min(left.min,min); if(right!=null)min=Math.min(right.min,min); }else{ min=tree[l]; } } public int query(int s,int e){ if(l==s&&r==e){ return min; } int mid=l+(r-l)/2; //left : to mid-1, if(e<=mid){ return left.query(s,e); } else if(s>=mid+1){ return right.query(s,e); }else{ return Math.min(left.query(s,mid),right.query(mid+1,e)); } } public void update(int index){ if(l==r){ min=tree[l]; return; } int mid=l+(r-l)/2; if(index<=mid){ left.update(index); }else{ right.update(index); } this.min=Math.min(left.min,right.min); } } class Fenwick { int tree[];//1-index based int A[]; int arr[]; public Fenwick(int[] A) { this.A=A; arr=new int[A.length]; tree=new int[A.length+1]; int sum=0; for(int i=0;i<A.length;i++){ update(i,A[i]); } } public void update(int i, int val) { arr[i]+=val; i++; while(i<tree.length){ tree[i]+=val; i+=(i&-i); } } public int sumRange(int i, int j) { return pre(j+1)-pre(i); } public int pre(int i){ int sum=0; while(i>0){ sum+=tree[i]; i-=(i&-i); } return sum; } }
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
312e3dc460d6dca82e6c0a54be0530b2
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
256 megabytes
/* * @author derrick20 */ import java.io.*; import java.util.*; public class archaeology { public static void main(String args[]) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); String s = sc.next(); char[] arr = s.toCharArray(); int goal = s.length() / 2; StringBuilder leftAns = new StringBuilder(); StringBuilder rightAns = new StringBuilder(); int left = 0; int right = s.length() - 1; while (right - left >= 3 && leftAns.length() + rightAns.length() < goal) { char l1 = arr[left]; char l2 = arr[left + 1]; // out.println(leftAns.toString() + rightAns.reverse()); // rightAns.reverse(); char r1 = arr[right]; char r2 = arr[right - 1]; if (l1 == r1) { left++; right--; leftAns.append(l1); rightAns.append(r1); if (l2 == r2) { left++; right--; leftAns.append(l2); rightAns.append(r2); } } else if (l2 == r2) { left += 2; right -= 2; leftAns.append(l2); rightAns.append(r2); } else if (l1 == r2) { left++; right -= 2; leftAns.append(l1); rightAns.append(r2); } else if (l2 == r1) { left += 2; right--; leftAns.append(l2); rightAns.append(r1); } } if (right - left < 3) { leftAns.append(arr[left]); } out.println(leftAns.toString() + rightAns.reverse()); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } Scanner(FileReader s) { br = new BufferedReader(s); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
e57f0e6e63335f9d2da15207b8853910
train_002.jsonl
1563636900
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it?The book contains a single string of characters "a", "b" and "c". It has been pointed out that no two consecutive characters are the same. It has also been conjectured that the string contains an unusually long subsequence that reads the same from both sides. Help Alice verify this by finding such subsequence that contains at least half of the characters of the original string, rounded down. Note that you don't have to maximise the length of it.A string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) characters.
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.StringTokenizer; public class E { static BufferedReader br; static StringTokenizer st; private static ArrayList<Integer>[] graf; static String nextToken() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } static int nextInt() { return Integer.parseInt(nextToken()); } static long nextLong() { return Long.parseLong(nextToken()); } static double nextDouble() { return Double.parseDouble(nextToken()); } static String nextLine() throws IOException { return br.readLine(); } static char nextChar() throws IOException { return (char) br.read(); } static String next() { return nextToken(); } static PrintWriter pw; static final int MOD = 998244353; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(System.out); String s = nextLine(); ArrayList<Character> chs = new ArrayList<>(); int len = s.length(); for (int i = 0; i < len / 2; i += 2) { if (s.charAt(i) == s.charAt(len - i - 1) || s.charAt(i) == s.charAt(len - i - 2)) { chs.add(s.charAt(i)); } else { chs.add(s.charAt(i + 1)); } } for (int i = 0; i < chs.size(); i++) { pw.print(chs.get(i)); } int size = chs.size(); if (size * 2 - 1 >= s.length() / 2) { size--; } for (int i = size - 1; i >= 0; i--) { pw.print(chs.get(i)); } pw.close(); } private static void sep(int start, int end) { graf[start].add(end - 1); for (int i = start; i < end - 1; i++) { graf[i].add(i + 1); } } static class Pair implements Comparable<Pair> { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { if (x == o.x) return Integer.compare(y, o.y); return Integer.compare(x, o.x); } } }
Java
["cacbac", "abc", "cbacacacbcbababacbcb"]
1 second
["aba", "a", "cbaaacbcaaabc"]
NoteIn the first example, other valid answers include "cacac", "caac", "aca" and "ccc".
Java 8
standard input
[ "brute force", "constructive algorithms", "greedy", "strings" ]
3bebb50d1c2ef9f80e78715614f039d7
The input consists of a single string $$$s$$$ ($$$2 \leq |s| \leq 10^6$$$). The string $$$s$$$ consists only of characters "a", "b", "c". It is guaranteed that no two consecutive characters are equal.
1,900
Output a palindrome $$$t$$$ that is a subsequence of $$$s$$$ and $$$|t| \geq \lfloor \frac{|s|}{2} \rfloor$$$. If there are multiple solutions, you may print any of them. You don't have to maximise the length of $$$t$$$. If there are no solutions, output a string "IMPOSSIBLE" (quotes for clarity).
standard output
PASSED
2d5c6b91fe6e3724f95823ded9ffe92d
train_002.jsonl
1286463600
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
256 megabytes
import java.io.*; import java.util.*; import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; 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(); public static void main(String[] args) { new Thread(null, new Main(), "persefone", 1 << 32).start(); } @Override public void run() { solve(); printf(); flush(); } void solve() { char[] s = in.next().toCharArray(); char[] w = in.next().toCharArray(); if (s.length != w.length) { printf(-1); return; } int n = in.nextInt(); int[][] cost = new int[26][26]; int oo = MI / 1000; for (int i = 0; i < 26; i++) Arrays.fill(cost[i], oo); for (int i = 0; i < n; i++) { int from = in.next().charAt(0) - 'a'; int to = in.next().charAt(0) - 'a'; cost[from][to] = Math.min(cost[from][to], in.nextInt()); } for (int i = 0; i < 26; i++) { cost[i][i] = 0; } int[][] minCost = new int[26][26]; for (int i = 0; i < 26; i++) { for (int j = 0; j < 26; j++) { minCost[i][j] = cost[i][j]; } } for (int k = 0; k < 26; k++) { for (int i = 0; i < 26; i++) { for (int j = 0; j < 26; j++) { minCost[i][j] = Math.min(minCost[i][j], minCost[i][k] + minCost[k][j]); } } } long ans = 0; StringBuilder fs = new StringBuilder(); for (int i = 0; i < s.length; i++) { int from = s[i] - 'a'; int to = w[i] - 'a'; int res = oo, cur = 0; for (int j = 0; j < 26; j++) { if (minCost[from][j] + minCost[to][j] < res) { res = minCost[from][j] + minCost[to][j]; cur = j; } } if (res == oo) { printf(-1); return; } ans += res; fs.append((char)(cur + 'a')); } printf(ans); printf(fs); } 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
["uayd\nuxxd\n3\na x 8\nx y 13\nd c 3", "a\nb\n3\na b 2\na b 3\nb a 5", "abc\nab\n6\na b 4\na b 7\nb a 8\nc b 11\nc a 3\na c 0"]
2 seconds
["21\nuxyd", "2\nb", "-1"]
null
Java 8
standard input
[ "shortest paths" ]
88c82ada2e66429900caeac758f7083b
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
1,800
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
standard output
PASSED
78de4ae5e1e87d3700e8d506802ac612
train_002.jsonl
1286463600
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import java.util.stream.*; @SuppressWarnings("unchecked") public class P33B { final static int SUB_ADD = 'a'; final static int SIZE = 'z' - SUB_ADD + 1; final static int MAX = Integer.MAX_VALUE >> 2; public void run() throws Exception { String s = next(), t = next(); if (s.length() != t.length()) { println(-1); return; } int [][] ab = new int [SIZE][SIZE]; for (int [] a : ab) { Arrays.fill(a, MAX); } for (int n = nextInt(); n > 0; n--) { int a = next().charAt(0) - SUB_ADD, b = next().charAt(0) - SUB_ADD, v = nextInt(); if (a != b) { ab[a][b] = Math.min(ab[a][b], v); } } for (boolean done = false; !done;) { done = true; for (int a = 0; a < SIZE; a++) { for (int b = 0; b < SIZE; b++) { if (ab[a][b] < MAX) { for (int c = 0; c < SIZE; c++) { if ((c != a) && (c != b) && ((ab[a][b] + ab[b][c]) < ab[a][c])) { ab[a][c] = ab[a][b] + ab[b][c]; done = false; } } } } } } for (int a = 0; a < SIZE; ab[a][a] = 0, a++); int av = 0; StringBuilder as = new StringBuilder(s.length()); for (int i = 0; i < s.length(); i++) { int a = s.charAt(i) - SUB_ADD, b = t.charAt(i) - SUB_ADD, c = 0, m = MAX; for (int j = 0; j < SIZE; j++) { if ((ab[a][j] + ab[b][j]) < m) { m = ab[a][j] + ab[b][j]; c = j; } } if (m >= MAX) { println(-1); return; } av += m; as.append((char)(c + SUB_ADD)); } println(av + "\n" + as); } public static void main(String... args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedOutputStream(System.out)); new P33B().run(); br.close(); pw.close(); System.err.println("\n[Time : " + (System.currentTimeMillis() - startTime) + " ms]"); } static long startTime = System.currentTimeMillis(); static BufferedReader br; static PrintWriter pw; StringTokenizer stok; String nextToken() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return null; } stok = new StringTokenizer(s); } return stok.nextToken(); } void print(byte b) { print("" + b); } void print(int i) { print("" + i); } void print(long l) { print("" + l); } void print(double d) { print("" + d); } void print(char c) { print("" + c); } void print(Object o) { if (o instanceof int[]) { print(Arrays.toString((int [])o)); } else if (o instanceof long[]) { print(Arrays.toString((long [])o)); } else if (o instanceof char[]) { print(Arrays.toString((char [])o)); } else if (o instanceof byte[]) { print(Arrays.toString((byte [])o)); } else if (o instanceof short[]) { print(Arrays.toString((short [])o)); } else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o)); } else if (o instanceof float[]) { print(Arrays.toString((float [])o)); } else if (o instanceof double[]) { print(Arrays.toString((double [])o)); } else if (o instanceof Object[]) { print(Arrays.toString((Object [])o)); } else { print("" + o); } } void print(String s) { pw.print(s); } void println() { println(""); } void println(byte b) { println("" + b); } void println(int i) { println("" + i); } void println(long l) { println("" + l); } void println(double d) { println("" + d); } void println(char c) { println("" + c); } void println(Object o) { print(o); println(); } void println(String s) { pw.println(s); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } char nextChar() throws IOException { return (char) (br.read()); } String next() throws IOException { return nextToken(); } String nextLine() throws IOException { return br.readLine(); } int [] readInt(int size) throws IOException { int [] array = new int [size]; for (int i = 0; i < size; i++) { array[i] = nextInt(); } return array; } long [] readLong(int size) throws IOException { long [] array = new long [size]; for (int i = 0; i < size; i++) { array[i] = nextLong(); } return array; } double [] readDouble(int size) throws IOException { double [] array = new double [size]; for (int i = 0; i < size; i++) { array[i] = nextDouble(); } return array; } String [] readLines(int size) throws IOException { String [] array = new String [size]; for (int i = 0; i < size; i++) { array[i] = nextLine(); } return array; } int gcd(int a, int b) { if (a == 0) return Math.abs(b); if (b == 0) return Math.abs(a); a = Math.abs(a); b = Math.abs(b); int az = Integer.numberOfTrailingZeros(a), bz = Integer.numberOfTrailingZeros(b); a >>>= az; b >>>= bz; while (a != b) { if (a > b) { a -= b; a >>>= Integer.numberOfTrailingZeros(a); } else { b -= a; b >>>= Integer.numberOfTrailingZeros(b); } } return (a << Math.min(az, bz)); } long gcd(long a, long b) { if (a == 0) return Math.abs(b); if (b == 0) return Math.abs(a); a = Math.abs(a); b = Math.abs(b); int az = Long.numberOfTrailingZeros(a), bz = Long.numberOfTrailingZeros(b); a >>>= az; b >>>= bz; while (a != b) { if (a > b) { a -= b; a >>>= Long.numberOfTrailingZeros(a); } else { b -= a; b >>>= Long.numberOfTrailingZeros(b); } } return (a << Math.min(az, bz)); } }
Java
["uayd\nuxxd\n3\na x 8\nx y 13\nd c 3", "a\nb\n3\na b 2\na b 3\nb a 5", "abc\nab\n6\na b 4\na b 7\nb a 8\nc b 11\nc a 3\na c 0"]
2 seconds
["21\nuxyd", "2\nb", "-1"]
null
Java 8
standard input
[ "shortest paths" ]
88c82ada2e66429900caeac758f7083b
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
1,800
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
standard output
PASSED
5932d87610e8ff9422c7e9204bcd1641
train_002.jsonl
1286463600
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; import java.math.BigInteger; public class Main { public static String line; BigInteger x; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String []my ; int t,n,ca,i,old,tmp; String source,dest; source = br.readLine(); dest = br.readLine(); line = br.readLine(); int m,k; m = Integer.parseInt(line); long ma = 100000006; long w[][] = new long[26][26]; int j; for(i=0;i<26;i++) for(j=0;j<26;j++) w[i][j] = ma; for(i=0;i<26;i++) w[i][i] = 0; for(i=0;i<m;i++) { line = br.readLine(); my = line.split(" "); int x,y,ww; x = my[0].charAt(0)-'a'; y = my[1].charAt(0)-'a'; ww = Integer.parseInt(my[2]); if(ww<w[x][y]) w[x][y] = ww; // System.out.println("from " + x + " to " + y + " the cost is " + w[x][y]); } StringBuffer bf = new StringBuffer(); for(k=0;k<26;k++) for(i=0;i<26;i++) for(j=0;j<26;j++) if(w[i][j] > w[i][k] + w[k][j]) w[i][j] = w[i][k] + w[k][j]; long ans = 0; int l = source.length(); if(l!=dest.length())ans = -1; else { for(i=0;i<l;i++) { int x,y; x = source.charAt(i)-'a'; y = dest.charAt(i) -'a'; long min = ma+5; char ch = '0'; for(char ss = 'a';ss<='z';ss++) { k = ss-'a'; if(w[x][k] + w[y][k] < min){ min = w[x][k] + w[y][k]; ch = ss; } } bf.append(ch); ans+=min; } if(ans>=ma)ans = -1; } System.out.println(ans); if(ans!=-1) System.out.println(bf.toString()); } }
Java
["uayd\nuxxd\n3\na x 8\nx y 13\nd c 3", "a\nb\n3\na b 2\na b 3\nb a 5", "abc\nab\n6\na b 4\na b 7\nb a 8\nc b 11\nc a 3\na c 0"]
2 seconds
["21\nuxyd", "2\nb", "-1"]
null
Java 8
standard input
[ "shortest paths" ]
88c82ada2e66429900caeac758f7083b
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
1,800
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
standard output
PASSED
9720ad950131073a5c02f7734ee4d2ce
train_002.jsonl
1286463600
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class Main { private static final int INF = 10000; static class FastReader { BufferedReader bufferedReader; StringTokenizer stringTokenizer; FastReader() { this.bufferedReader = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (this.stringTokenizer == null || !this.stringTokenizer.hasMoreElements()) { try { this.stringTokenizer = new StringTokenizer(this.bufferedReader.readLine()); } catch (IOException e) { e.printStackTrace(); } } return this.stringTokenizer.nextToken(); } int nextInt() { return Integer.parseInt(this.next()); } char nextChar() { return this.next().charAt(0); } } public static void main(String[] args) { FastReader in = new FastReader(); String s = in.next(), t = in.next(); Graph graph = new Graph(26); int edges = in.nextInt(); for (int i = 0; i < edges; i++) graph.insertEdge(in.nextChar() - 'a', in.nextChar() - 'a', in.nextInt()); int[][] minCosts = graph.shortestPaths(); if (s.length() != t.length()) System.out.println(-1); else { int cost = 0; StringBuilder ans = new StringBuilder(); boolean answerExists = true; for (int i = 0; i < s.length() && answerExists; i++) { int sv = s.charAt(i) - 'a'; int tv = t.charAt(i) - 'a'; int v = -1; for (int j = 0; j < 26; j++) { if (minCosts[sv][j] != INF && minCosts[tv][j] != INF && (v == -1 || minCosts[sv][j] + minCosts[tv][j] < minCosts[sv][v] + minCosts[tv][v])) { v = j; } } if (v == -1) answerExists = false; else { cost += minCosts[sv][v] + minCosts[tv][v]; ans.append((char) (v + 'a')); } } if (!answerExists) System.out.println(-1); else { System.out.println(cost); System.out.println(ans); } } } } class Graph { private static final int INF = 10000; private int[][] g; private int vertices; public Graph(int vertices) { this.g = new int[vertices][vertices]; for (int i = 0; i < vertices; i++) for (int j = 0; j < vertices; j++) this.g[i][j] = INF; this.vertices = vertices; } public void insertEdge(int u, int v, int w) { this.g[u][v] = Math.min(this.g[u][v], w); } public int[][] shortestPaths() { int[][] shortestPaths = new int[this.vertices][this.vertices]; for (int i = 0; i < this.vertices; i++) for (int j = 0; j < this.vertices; j++) { if (i == j) shortestPaths[i][j] = 0; else shortestPaths[i][j] = this.g[i][j]; } for (int k = 0; k < this.vertices; k++) for (int i = 0; i < this.vertices; i++) for (int j = 0; j < this.vertices; j++) if (shortestPaths[i][k] != INF && shortestPaths[k][j] != INF) shortestPaths[i][j] = Math.min(shortestPaths[i][j], shortestPaths[i][k] + shortestPaths[k][j]); return shortestPaths; } }
Java
["uayd\nuxxd\n3\na x 8\nx y 13\nd c 3", "a\nb\n3\na b 2\na b 3\nb a 5", "abc\nab\n6\na b 4\na b 7\nb a 8\nc b 11\nc a 3\na c 0"]
2 seconds
["21\nuxyd", "2\nb", "-1"]
null
Java 8
standard input
[ "shortest paths" ]
88c82ada2e66429900caeac758f7083b
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
1,800
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
standard output
PASSED
701fd85d66844786be13040d4fde8dce
train_002.jsonl
1286463600
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import javafx.util.Pair; import java.util.Vector; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Stack; 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); b33 solver = new b33(); solver.solve(1, in, out); out.close(); } static class b33 { public void solve(int testNumber, InputReader in, PrintWriter out) { String s = in.next(); String t = in.next(); int maxW = 1000000; if (s.length() != t.length()) { out.println(-1); return; } int[][] cost = new int[26][26]; for (int i = 0; i < 26; i++) { for (int j = 0; j < 26; j++) { cost[i][j] = maxW; } } int n = in.nextInt(); for (int i = 0; i < n; i++) { int A = in.next().charAt(0) - 'a'; int B = in.next().charAt(0) - 'a'; int W = in.nextInt(); cost[A][B] = Math.min(cost[A][B], W); } for (int i = 0; i < 26; i++) { boolean[] used = new boolean[26]; Stack<Pair<Integer, Integer>> dfs = new Stack<>(); dfs.add(new Pair<>(i, 0)); used[i] = true; while (!dfs.isEmpty()) { Pair<Integer, Integer> cur = dfs.pop(); cost[i][cur.getKey()] = Math.min(cost[i][cur.getKey()], cur.getValue()); for (int j = 0; j < 26; j++) { if (!used[j] && cost[cur.getKey()][j] < maxW) { used[j] = true; dfs.push(new Pair<>(j, cur.getValue() + cost[cur.getKey()][j])); } } } } for (int mid = 0; mid < 26; mid++) { for (int i = 0; i < 26; i++) { for (int j = 0; j < 26; j++) { cost[i][j] = Math.min(cost[i][j], cost[i][mid] + cost[mid][j]); } } } char[] ans = new char[s.length()]; int ansCost = 0; for (int i = 0; i < s.length(); i++) { char best = '&'; int curCost = maxW; int tChar = t.charAt(i) - 'a'; int sChar = s.charAt(i) - 'a'; for (int curChar = 0; curChar < 26; curChar++) { int sCost = cost[sChar][curChar]; int tCost = cost[tChar][curChar]; if (sCost + tCost < curCost) { curCost = sCost + tCost; best = (char) (curChar + 'a'); } } if (best == '&') { out.println(-1); return; } ans[i] = best; ansCost += curCost; } out.println(ansCost); out.println(ans); } } static class InputReader { private BufferedReader reader; private StringTokenizer stt; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { return null; } } public String next() { while (stt == null || !stt.hasMoreTokens()) { stt = new StringTokenizer(nextLine()); } return stt.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["uayd\nuxxd\n3\na x 8\nx y 13\nd c 3", "a\nb\n3\na b 2\na b 3\nb a 5", "abc\nab\n6\na b 4\na b 7\nb a 8\nc b 11\nc a 3\na c 0"]
2 seconds
["21\nuxyd", "2\nb", "-1"]
null
Java 8
standard input
[ "shortest paths" ]
88c82ada2e66429900caeac758f7083b
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
1,800
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
standard output
PASSED
7233a1f2a8f812dc919c0409fc3f1f43
train_002.jsonl
1286463600
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
256 megabytes
import java.io.*; import java.util.*; public class B33 { public static void main(String[] args) throws IOException { input.init(System.in); PrintWriter out = new PrintWriter(System.out); String s = input.next(), t = input.next(); int[][] cs = new int[26][26]; for(int[] A : cs) Arrays.fill(A, 10000001); for(int i = 0; i<26; i++) cs[i][i] = 0; String res = ""; long cost = 0; int n = s.length(); int m = input.nextInt(); for(int i = 0; i<m; i++) { int a = input.next().charAt(0) - 'a'; int b = input.next().charAt(0) - 'a'; int c = input.nextInt(); cs[a][b] = Math.min(cs[a][b], c); } for(int k = 0; k<26; k++) for(int i = 0;i <26; i++) for(int j = 0; j<26; j++) cs[i][j] = Math.min(cs[i][j], cs[i][k] + cs[k][j]); StringBuilder sb = new StringBuilder(""); for(int i = 0; i<n && s.length() == t.length(); i++) { int best = -1; int a = s.charAt(i) - 'a'; int b = t.charAt(i) - 'a'; for(int j = 0; j<26; j++) { if(cs[a][j] == 10000001 || cs[b][j] == 10000001) continue; if(best == -1 || cs[a][j] + cs[b][j] < cs[a][best] + cs[b][best]) best = j; } if(best == -1) cost = (long)1e16; else { cost += cs[a][best] + cs[b][best]; sb.append((char)('a'+best)); } } if(cost < 1e15 && s.length() == t.length()) { out.println(cost); out.println(sb.toString()); } else out.println(-1);; out.close(); } public static class input { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) { reader = new BufferedReader(new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["uayd\nuxxd\n3\na x 8\nx y 13\nd c 3", "a\nb\n3\na b 2\na b 3\nb a 5", "abc\nab\n6\na b 4\na b 7\nb a 8\nc b 11\nc a 3\na c 0"]
2 seconds
["21\nuxyd", "2\nb", "-1"]
null
Java 8
standard input
[ "shortest paths" ]
88c82ada2e66429900caeac758f7083b
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
1,800
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
standard output
PASSED
275cfebbd23af8b10b3942cabcb081da
train_002.jsonl
1286463600
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class Template implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } } class GraphBuilder { int n, m; int[] x, y; int index; int[] size; GraphBuilder(int n, int m) { this.n = n; this.m = m; x = new int[m]; y = new int[m]; size = new int[n]; } void add(int u, int v) { x[index] = u; y[index] = v; size[u]++; size[v]++; index++; } int[][] build() { int[][] graph = new int[n][]; for (int i = 0; i < n; i++) { graph[i] = new int[size[i]]; } for (int i = m - 1; i >= 0; i--) { graph[x[i]][--size[x[i]]] = y[i]; graph[y[i]][--size[y[i]]] = x[i]; } return graph; } } String readString() throws IOException { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine()); } catch (Exception e) { return null; } } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } int[] readIntArray(int size) throws IOException { int[] res = new int[size]; for (int i = 0; i < size; i++) { res[i] = readInt(); } return res; } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } <T> List<T>[] createGraphList(int size) { List<T>[] list = new List[size]; for (int i = 0; i < size; i++) { list[i] = new ArrayList<>(); } return list; } public static void main(String[] args) { new Template().run(); // new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start(); } long timeBegin, timeEnd; void time() { timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } long memoryTotal, memoryFree; void memory() { memoryFree = Runtime.getRuntime().freeMemory(); System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB"); } public void run() { try { timeBegin = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); if (System.getProperty("ONLINE_JUDGE") == null) { time(); memory(); } } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } void solve() throws IOException { char[] s = readString().toCharArray(); char[] t = readString().toCharArray(); if (s.length != t.length) { out.println(-1); return; } int n = readInt(); int[][] cost = new int[26][26]; for (int[] c : cost) Arrays.fill(c, Integer.MAX_VALUE); for (int i=0;i<n;i++) { int x = readString().charAt(0) - 'a'; int y = readString().charAt(0) - 'a'; int c = readInt(); cost[x][y] = Math.min(cost[x][y], c); } for (int k=0;k<26;k++) { for (int i=0;i<26;i++) { for (int j=0;j<26;j++) { if (cost[i][k] == Integer.MAX_VALUE || cost[k][j] == Integer.MAX_VALUE) continue; cost[i][j] = Math.min(cost[i][j], cost[i][k] + cost[k][j]); } } } char[] result = new char[s.length]; int answer = 0; for (int i=0;i<s.length;i++) { int mincost = Integer.MAX_VALUE; int res = -1; if (s[i] == t[i]) { result[i] = s[i]; continue; } int x = s[i] - 'a'; int y = t[i] - 'a'; for (int target=0;target<26;target++) { long cst = 0; if (target != x) { cst += cost[x][target]; } if (target != y) { cst += cost[y][target]; } if (cst < mincost) { mincost = (int) cst; res = target; } } if (mincost == Integer.MAX_VALUE) { out.println(-1); return; } answer += mincost; result[i] = (char) ('a' + res); } out.println(answer); out.println(new String(result)); } }
Java
["uayd\nuxxd\n3\na x 8\nx y 13\nd c 3", "a\nb\n3\na b 2\na b 3\nb a 5", "abc\nab\n6\na b 4\na b 7\nb a 8\nc b 11\nc a 3\na c 0"]
2 seconds
["21\nuxyd", "2\nb", "-1"]
null
Java 8
standard input
[ "shortest paths" ]
88c82ada2e66429900caeac758f7083b
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
1,800
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
standard output
PASSED
0ffe54e954a30721c3f051cc7d2424d6
train_002.jsonl
1286463600
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
256 megabytes
import java.util.Scanner; public class _33B { final static int N = 26; Scanner scanner = new Scanner(System.in); String source, destination; long m, totalCost=0; long[][] distance = new long[N][N]; public static void main(String[] args) { _33B solution = new _33B(); solution.solve(); } public void solve(){ source = scanner.next(); destination = scanner.next(); m = scanner.nextInt(); initialize(); char src, des; long cost; for(int i=1; i<=m; i++){ src = scanner.next().charAt(0); des = scanner.next().charAt(0); cost = scanner.nextLong(); distance[src-'a'][des-'a'] = Math.min(cost, distance[src-'a'][des-'a']); // distance[des-'a'][src-'a'] = Math.min(cost, distance[des-'a'][src-'a']); } if(source.length() != destination.length()){ System.out.println(-1); }else{ allSourceShortestPath(); StringBuilder builder = new StringBuilder(); int si, di; long minCost; char finalChar; for(int i=0; i<source.length(); i++){ si = source.charAt(i) - 'a'; di = destination.charAt(i) - 'a'; minCost = Integer.MAX_VALUE; finalChar = 'a'; for(int j=0; j<N; j++){ if(minCost > distance[si][j] + distance[di][j]){ minCost = distance[si][j] + distance[di][j]; finalChar = (char)('a' +j); } } builder.append(finalChar); totalCost += minCost; } if(totalCost >= Integer.MAX_VALUE){ System.out.println(-1); } else{ System.out.println(totalCost +"\n"+ builder.toString()); } } } private void initialize(){ for(int i=0; i<N; i++){ for(int j=0; j<N; j++){ if(i==j) distance[i][j] = 0; else distance[i][j] = Integer.MAX_VALUE; } } } private void allSourceShortestPath(){ for(int pk=0; pk<N; pk++){ for(int i=0; i<N; i++){ for(int j=0; j<N; j++){ if(distance[i][j] > distance[i][pk] + distance[pk][j]){ distance[i][j] = distance[i][pk] + distance[pk][j]; // System.out.format("from %c to %c via %c cost: %d\n", (char) (i+'a'), (char) (j+'a'), (char) (pk+ 'a'), distance[i][j]); } } } } } }
Java
["uayd\nuxxd\n3\na x 8\nx y 13\nd c 3", "a\nb\n3\na b 2\na b 3\nb a 5", "abc\nab\n6\na b 4\na b 7\nb a 8\nc b 11\nc a 3\na c 0"]
2 seconds
["21\nuxyd", "2\nb", "-1"]
null
Java 8
standard input
[ "shortest paths" ]
88c82ada2e66429900caeac758f7083b
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
1,800
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
standard output
PASSED
540f63d0623ea94c1a24e69f09fc7b89
train_002.jsonl
1286463600
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
256 megabytes
import java.util.*; import java.io.*; public class CF33B_StringProblem { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); String a = sc.next(); String b = sc.next(); if (a.length() != b.length()) { System.out.println(-1); return; } int n = sc.nextInt(); int[][] dist = new int[26][26]; for (int i = 0; i < dist.length; i++) Arrays.fill(dist[i], (int) 1e9); for (int i = 0; i < 26; i++) dist[i][i] = 0; while (n-- > 0) { int x = sc.next().charAt(0) - 'a'; int y = sc.next().charAt(0) - 'a'; int cost = sc.nextInt(); dist[x][y] = Math.min(dist[x][y], cost); } for (int k = 0; k < 26; k++) for (int i = 0; i < 26; i++) for (int j = 0; j < 26; j++) dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); int ans = 0; StringBuilder sb = new StringBuilder(); for (int i = 0; i < a.length(); i++) { int x = a.charAt(i) - 'a'; int y = b.charAt(i) - 'a'; int car = -1; int min = (int)1e9; for(int j=0;j<26;j++) { if(dist[x][j] + dist[y][j] < min) { min = dist[x][j] + dist[y][j]; car = j; } } if(car == -1) { System.out.println(-1); return; } sb.append((char)(car + 'a')); ans+=min; } System.out.println(ans); System.out.println(sb.toString()); } 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 double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["uayd\nuxxd\n3\na x 8\nx y 13\nd c 3", "a\nb\n3\na b 2\na b 3\nb a 5", "abc\nab\n6\na b 4\na b 7\nb a 8\nc b 11\nc a 3\na c 0"]
2 seconds
["21\nuxyd", "2\nb", "-1"]
null
Java 8
standard input
[ "shortest paths" ]
88c82ada2e66429900caeac758f7083b
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
1,800
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
standard output
PASSED
2f41ff7f8ade294fcf3f6840da13ed91
train_002.jsonl
1286463600
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
256 megabytes
/* / フフ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ム / )\⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ Y (⠀⠀| ( ͡° ͜ʖ ͡°)⠀⌒(⠀ ノ (⠀ ノ⌒ Y ⌒ヽ-く __/ | _⠀。ノ| ノ。 |/ (⠀ー '_人`ー ノ ⠀|\  ̄ _人'彡ノ ⠀ )\⠀⠀ 。⠀⠀ / ⠀⠀(\⠀ #⠀ / ⠀/⠀⠀⠀/ὣ====================D- /⠀⠀⠀/⠀ \ \⠀⠀\ ( (⠀)⠀⠀⠀⠀ ) ).⠀) (⠀⠀)⠀⠀⠀⠀⠀( | / |⠀ /⠀⠀⠀⠀⠀⠀ | / [_] ⠀⠀⠀⠀⠀[___] */ // Main Code at the Bottom import java.util.*; import java.lang.*; import java.io.*; import java.math.BigInteger; public class Main { //Fast IO class 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 long MOD=1000000000+7; //Euclidean Algorithm static long gcd(long A,long B){ return (B==0)?A:gcd(B,A%B); } //Modular Exponentiation static long fastExpo(long x,long n){ if(n==0) return 1; if((n&1)==0) return fastExpo((x*x)%MOD,n/2)%MOD; return ((x%MOD)*fastExpo((x*x)%MOD,(n-1)/2))%MOD; } //Modular Inverse static long inverse(long x) { return fastExpo(x,MOD-2); } //Prime Number Algorithm static boolean isPrime(long n){ if(n<=1) return false; if(n<=3) return true; if(n%2==0 || n%3==0) return false; for(int i=5;i*i<=n;i+=6) if(n%i==0 || n%(i+2)==0) return false; return true; } //Reverse an array static void reverse(int arr[],int l,int r){ while(l<r) { int tmp=arr[l]; arr[l++]=arr[r]; arr[r--]=tmp; } } //Print array static void print1d(int arr[]) { out.println(Arrays.toString(arr)); } static void print2d(int arr[][]) { for(int a[]: arr) out.println(Arrays.toString(a)); } // Pair static class pair{ int x; double y; pair(int a,double b){ this.x=a; this.y=b; } public boolean equals(Object obj) { if(obj == null || obj.getClass()!= this.getClass()) return false; pair p = (pair) obj; return (this.x==p.x && this.y==p.y); } public int hashCode() { return Objects.hash(x,y); } } static FastReader sc=new FastReader(); static PrintWriter out=new PrintWriter(System.out); //Main function(The main code starts from here static int dp[][]=new int[26][26],inf=1000000; public static void main (String[] args) throws java.lang.Exception { int test; test=1; //test=sc.nextInt(); while(test-->0){ char s[]=sc.nextLine().toCharArray(),t[]=sc.nextLine().toCharArray(); if(s.length!=t.length) { out.println(-1); break; } int n=sc.nextInt(),ans=0,N=s.length; for(int i=0;i<26;i++) for(int j=0;j<26;j++) if(i!=j) dp[i][j]=inf; for(int i=0;i<n;i++) { StringTokenizer st=new StringTokenizer(sc.nextLine()); int src=st.nextToken().charAt(0)-'a',dest=st.nextToken().charAt(0)-'a',w=Integer.parseInt(st.nextToken()); dp[src][dest]=Math.min(dp[src][dest], w); } for(int k=0;k<26;k++) for(int i=0;i<26;i++) for(int j=0;j<26;j++) dp[i][j]=Math.min(dp[i][j], dp[i][k]+dp[k][j]); int f=0; for(int i=0;i<N;i++) { int x=s[i]-'a',y=t[i]-'a'; int min=inf; for(int d=0;d<26;d++) { int val=dp[x][d]+dp[y][d]; if(val<min) { min=val; s[i]=(char)(d+'a'); t[i]=(char)(d+'a'); } } if(min==inf) f=1; ans+=min; } if(f==1) out.println(-1); else { out.println(ans); for(char c: s) out.print(c); } } out.flush(); out.close(); } }
Java
["uayd\nuxxd\n3\na x 8\nx y 13\nd c 3", "a\nb\n3\na b 2\na b 3\nb a 5", "abc\nab\n6\na b 4\na b 7\nb a 8\nc b 11\nc a 3\na c 0"]
2 seconds
["21\nuxyd", "2\nb", "-1"]
null
Java 8
standard input
[ "shortest paths" ]
88c82ada2e66429900caeac758f7083b
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
1,800
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
standard output
PASSED
b36f7dda71f33a7a43166ae0f4de9a7f
train_002.jsonl
1286463600
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; /** * Created by Egor on 20/10/14. */ public class Task33B { BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public char nextChar() throws IOException { return nextToken().charAt(0); } public static void main(String[] args) throws IOException { new Task33B().run(); } public void solve() throws IOException { String s = nextToken(); String t = nextToken(); char[] c1 = s.toCharArray(); char[] c2 = t.toCharArray(); int len = c1.length; int len2 = c2.length; if (len != len2) { writer.println(-1); return; } int n = nextInt(); int[][] changes = new int['z' + 1]['z' + 1]; for (int i1 = 0; i1 < changes.length; i1++) { int[] array = changes[i1]; Arrays.fill(array, Integer.MAX_VALUE / 2); array[i1] = 0; } for (int i = 0; i < n; i++) { char ai = nextChar(); char bi = nextChar(); int w = nextInt(); // if (ai == bi) { // continue; // } changes[ai][bi] = Math.min(changes[ai][bi], w); } StringBuilder builder = new StringBuilder(); int price = 0; for (char k = 'a'; k <= 'z'; k++) { for (char i = 'a'; i <= 'z'; i++) { for (char j = 'a'; j <= 'z'; j++) { changes[i][j] = Math.min(changes[i][j], changes[i][k] + changes[k][j]); } } } for (int i = 0; i < len; i++) { int curValue = Integer.MAX_VALUE / 2; char curChar = '#'; for (char j = 'a'; j <= 'z'; j++) { if (changes[c1[i]][j] + changes[c2[i]][j] < curValue) { curValue = changes[c1[i]][j] + changes[c2[i]][j]; curChar = j; } } if (curChar == '#') { writer.print(-1); return; } price += curValue; builder.append(curChar); } writer.println(price + "\n" + builder); } public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); solve(); writer.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } }
Java
["uayd\nuxxd\n3\na x 8\nx y 13\nd c 3", "a\nb\n3\na b 2\na b 3\nb a 5", "abc\nab\n6\na b 4\na b 7\nb a 8\nc b 11\nc a 3\na c 0"]
2 seconds
["21\nuxyd", "2\nb", "-1"]
null
Java 8
standard input
[ "shortest paths" ]
88c82ada2e66429900caeac758f7083b
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
1,800
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
standard output
PASSED
6bfd234b60e91084d9def41d35317c61
train_002.jsonl
1286463600
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
256 megabytes
import java.io.*; import java.util.*; public class Main { static final long INF = (long) 1e18; // don't increase, avoid overflow static class Edge implements Comparable<Edge> { int u; double cost; Edge(int a,double c) { u = a; cost=c; } public int compareTo(Edge e) { return Double.compare(cost, e.cost); } public String toString() { return u+" "+cost; } } static class pair{ int u,v; pair(int a,int b){u=a;v=b;} } static final int inf=(int)1e8; static int[][]arr; static PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) throws IOException, Exception { Scanner sc = new Scanner(System.in); String s1=sc.next(); String s2=sc.next(); if(s1.length()==s2.length()) { int n=sc.nextInt(); int[][]arr=new int[29][29]; for(int i[]:arr)Arrays.fill(i, inf); for(int i=0;i<n;i++) { int a=sc.next().charAt(0)-'a'; int b=sc.next().charAt(0)-'a'; int c=sc.nextInt(); arr[a][b]=Math.min(arr[a][b], c); } int[][]save=new int[29][29]; for(int k=0;k<28;k++) { for(int i=0;i<28;i++) { for(int j=0;j<28;j++) { if(arr[i][j]>arr[i][k]+arr[k][j]){ arr[i][j]=arr[i][k]+arr[k][j];} } } } StringBuilder ans=new StringBuilder(); int res=0; for(int i=0;i<s1.length();i++) { char a=s1.charAt(i); char b=s2.charAt(i); if(a==b) {ans.append(a);continue;} int first=arr[a-'a'][b-'a']; int second=arr[b-'a'][a-'a']; int third=inf; int x=0; for(int j=0;j<28;j++) { if(arr[a-'a'][j]+arr[b-'a'][j]<third) { third=arr[a-'a'][j]+arr[b-'a'][j]; x=j; } } if(first<second) { if(first<third) { ans.append(b); res+=first; } else { ans.append((char)(x+'a')); res+=third; } } else { if(second<third) { ans.append(a); res+=second; } else { ans.append((char)(x+'a')); res+=third; } } if(res>=inf) {res=inf;break;} } if(res==inf)pw.println(-1); else {pw.println(res);pw.println(ans);} } else pw.println(-1); pw.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String file) throws FileNotFoundException { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["uayd\nuxxd\n3\na x 8\nx y 13\nd c 3", "a\nb\n3\na b 2\na b 3\nb a 5", "abc\nab\n6\na b 4\na b 7\nb a 8\nc b 11\nc a 3\na c 0"]
2 seconds
["21\nuxyd", "2\nb", "-1"]
null
Java 8
standard input
[ "shortest paths" ]
88c82ada2e66429900caeac758f7083b
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
1,800
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
standard output
PASSED
f52b4c581cc572d79d2afea9cd152e24
train_002.jsonl
1286463600
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
256 megabytes
/******************************************************************* My love has gone away, quietly after a hundered days. This is what's she has always said she won't stay for more than what she can repay. I can still hear her say there that I'm not hearing tender play The day she let me kiss her was a display, of love to those who she betray. How can I put someone to the test, when I thought I got the best. Untill the taste of bitterness then I regret but still that I won't detest, the love I can't forget, like someone who has left. How can i leave someone for the rest when i'm alone facing the best Untill they take some try to reason i regret But still that i won't detest who i can never forget like someone i once met .. ******************************************************************/ import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.InputMismatchException; public class TaskB_33 { static final int INF = Integer.MAX_VALUE / 2; public static void main(String[] args) { input(); solve(); } static void solve() { if (s1.length != s2.length) { System.out.println(-1); return; } int length = s1.length; int cost = 0; StringBuilder res = new StringBuilder(); // PloydWarshall for (int k = 97; k < 123; k++) { m[k][k] = 0; for (int i = 97; i < 123; i++) { if (m[i][k] == INF) { continue; } for (int j = 97; j < 123; j++) { if (m[k][j] == INF) continue; m[i][j] = Math.min(m[i][k] + m[k][j], m[i][j]); } } } int min; int pos = 0; for (int i = 0; i < length; i++) { if (s1[i] != s2[i]) { min = INF; for (int j = 97; j < 123; j++) { if (m[s1[i]][j] + m[s2[i]][j] < min) { min = m[s1[i]][j] + m[s2[i]][j]; pos = j; } } res.append((char) pos); if (min == INF) { System.out.println(-1); return; } cost += min; } else { res.append(s1[i]); } } System.out.println(cost); System.out.println(res); } /************************************************************************************/ static char[] s1; static char[] s2; static int n; static int[][] m = new int[123][123]; static void input() { s1 = nextString().toCharArray(); s2 = nextString().toCharArray(); n = nextInt(); for (int i = 0; i < 123; i++) { Arrays.fill(m[i], INF); } char a; char b; int w; for (int i = 0; i < n; i++) { a = nextChar(); b = nextChar(); w = nextInt(); m[a][b] = Math.min(m[a][b], w); } } /************************************************************************************/ static InputStream is = System.in; static private byte[] buffer = new byte[1024]; static private int lenbuf = 0, ptrbuf = 0; static private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(buffer); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return buffer[ptrbuf++]; } static private boolean isSpace(int c) { return !(c >= 33 && c <= 126); } static private int read() { int b; while ((b = readByte()) != -1 && isSpace(b)) ; return b; } static private double nextDouble() { return Double.parseDouble(nextString()); } static private char nextChar() { return (char) read(); } static private String nextString() { int b = read(); StringBuilder sb = new StringBuilder(); while (!(isSpace(b))) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } static private char[] nextString(int n) { char[] buf = new char[n]; int b = read(), p = 0; while (p < n && !(isSpace(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } static private 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(); } } private 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(); } } static private int[] nextAi(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } }
Java
["uayd\nuxxd\n3\na x 8\nx y 13\nd c 3", "a\nb\n3\na b 2\na b 3\nb a 5", "abc\nab\n6\na b 4\na b 7\nb a 8\nc b 11\nc a 3\na c 0"]
2 seconds
["21\nuxyd", "2\nb", "-1"]
null
Java 8
standard input
[ "shortest paths" ]
88c82ada2e66429900caeac758f7083b
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
1,800
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
standard output
PASSED
9546daa7873328ce36a51ead5616085d
train_002.jsonl
1286463600
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.BitSet; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; /** * * * 3 2 3 5 * -2 -1 4 -1 2 7 3 * * 10 1 -10617 30886 -7223 -63085 47793 -61665 -14614 60492 16649 -58579 3 8 1 * 10 4 7 1 7 3 7 * * 22862 -34877 * * @author pttrung */ public class D { public static long MOD = 1000000007; static int[] X = {0, 1}; static int[] Y = {1, 0}; static int[][][] dp; public static void main(String[] args) throws FileNotFoundException { // PrintWriter out = new PrintWriter(new FileOutputStream(new File( // "output.txt"))); PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); String s = in.next(); String t = in.next(); if (s.length() != t.length()) { out.println(-1); } else { int n = in.nextInt(); long[][] map = new long[26][26]; for (long[] a : map) { Arrays.fill(a, Integer.MAX_VALUE); } for (int i = 0; i < n; i++) { int x = in.next().charAt(0) - 'a'; int y = in.next().charAt(0) - 'a'; int z = in.nextInt(); map[x][y] = Math.min(map[x][y], z); } for (int k = 0; k < 26; k++) { map[k][k] = 0; for (int i = 0; i < 26; i++) { for (int j = 0; j < 26; j++) { if (map[i][k] != Integer.MAX_VALUE && map[k][j] != Integer.MAX_VALUE) { map[i][j] = Math.min(map[i][j], map[i][k] + map[k][j]); } } } } char[] result = new char[s.length()]; long total = 0; boolean ok = true; for (int i = 0; i < s.length(); i++) { int u = s.charAt(i) - 'a'; int v = t.charAt(i) - 'a'; if (u == v) { result[i] = s.charAt(i); } else { long tmp = Integer.MAX_VALUE; int index = -1; for (int j = 0; j < 26; j++) { if (map[u][j] + map[v][j] < tmp) { tmp = map[u][j] + map[v][j]; index = j; } } if (index == -1) { ok = false; break; } total += tmp; result[i] = (char) ('a' + index); } } if (ok) { out.println(total); out.println(new String(result)); } else { out.println(-1); } } out.close(); } public static int[] KMP(String val) { int i = 0; int j = -1; int[] result = new int[val.length() + 1]; result[0] = -1; while (i < val.length()) { while (j >= 0 && val.charAt(j) != val.charAt(i)) { j = result[j]; } j++; i++; result[i] = j; } return result; } public static boolean nextPer(int[] data) { int i = data.length - 1; while (i > 0 && data[i] < data[i - 1]) { i--; } if (i == 0) { return false; } int j = data.length - 1; while (data[j] < data[i - 1]) { j--; } int temp = data[i - 1]; data[i - 1] = data[j]; data[j] = temp; Arrays.sort(data, i, data.length); return true; } public static int digit(long n) { int result = 0; while (n > 0) { n /= 10; result++; } return result; } public static double dist(long a, long b, long x, long y) { double val = (b - a) * (b - a) + (x - y) * (x - y); val = Math.sqrt(val); double other = x * x + a * a; other = Math.sqrt(other); return val + other; } public static class Point implements Comparable<Point> { int x, y; public Point(int start, int end) { this.x = start; this.y = end; } @Override public int hashCode() { int hash = 5; hash = 47 * hash + this.x; hash = 47 * hash + this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Point other = (Point) obj; if (this.x != other.x) { return false; } if (this.y != other.y) { return false; } return true; } @Override public int compareTo(Point o) { return x - o.x; } } public static class FT { long[] data; FT(int n) { data = new long[n]; } public void update(int index, long value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public long get(int index) { long result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } public static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long pow(long a, long b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return val * val % MOD; } else { return val * (val * a % MOD) % MOD; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["uayd\nuxxd\n3\na x 8\nx y 13\nd c 3", "a\nb\n3\na b 2\na b 3\nb a 5", "abc\nab\n6\na b 4\na b 7\nb a 8\nc b 11\nc a 3\na c 0"]
2 seconds
["21\nuxyd", "2\nb", "-1"]
null
Java 8
standard input
[ "shortest paths" ]
88c82ada2e66429900caeac758f7083b
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
1,800
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
standard output
PASSED
d830250c22e46cf0a5885aa42ed2680a
train_002.jsonl
1286463600
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
256 megabytes
import java.util.HashMap; import java.util.Map; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { FastReader fs = new FastReader(); String line1 = fs.nextLine(); String line2 = fs.nextLine(); int n = fs.nextInt(); int graph[][] = new int[26][26]; // dicionario para mapear cada caracter a uma posicao num array Map<Character, Integer> vertexId = new HashMap<>(); Map<Integer, Character> reversed = new HashMap<>(); char alph[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w' , 'x', 'y', 'z'}; for(int i = 0; i < 26; i++) { vertexId.put(alph[i], i); reversed.put(i, alph[i]); } for(int i = 0; i < 26; i++) { for(int j = 0; j <26; j++) { if(i == j) { graph[i][j] = 0; } else { graph[i][j] = 1000000000; } } } for(int i = 0; i < n; i++) { // contruir matriz de adjacencia String x = fs.next(); String y = fs.next(); int w = fs.nextInt(); char v = x.charAt(0), u = y.charAt(0); /*if(graph[vertexId.get(v)][vertexId.get(u)] == 0 || w < graph[vertexId.get(v)][vertexId.get(u)]) { graph[vertexId.get(v)][vertexId.get(u)] = w; }*/ graph[vertexId.get(v)][vertexId.get(u)] = Math.min(graph[vertexId.get(v)][vertexId.get(u)], w); } int dist[][] = new int[26][26]; int parent[][] = new int[26][26]; dist = graph; for(int a = 0; a < 26; a++) { for(int b = 0; b < 26; b++) { if(a==b) {parent[a][b] = a;} else if(dist[a][b]!=0 && dist[a][b] != 99999) { parent[a][b] = a; } else { parent[a][b] = -1; } } } for(int k = 0; k < 26; k++) { for(int i = 0; i < 26; i++) { for(int j = 0; j < 26; j++) { if(dist[i][k] + dist[k][j] < dist[i][j]) { dist[i][j] = dist[i][k] + dist[k][j]; parent[i][j] = parent[i][k]; } } } } // verificar o menor caminho entre pares de letras de line1 e line2 int totalCost = -1; StringBuilder finalString = new StringBuilder(); boolean pairFound = true; if(line1.length() == line2.length()) { totalCost = 0; pairFound = true; for(int x = 0; x < line1.length(); x++) { if(line1.charAt(x) != line2.charAt(x)) { int source = vertexId.get(line1.charAt(x)); int dest = vertexId.get(line2.charAt(x)); int parentChar = -1; int minDist = 1000000000; for(int y = 0; y < 26; y++) { int result1 = dist[source][y]; int result2 = dist[dest][y]; if(result1 != 1000000000 && result2 != 1000000000 && minDist > result1+result2) { minDist = result1 + result2; parentChar = y; } } if(minDist == 1000000000) { pairFound = false; totalCost = -1; break; } else { totalCost += minDist; finalString.append(reversed.get(parentChar)); } } else { finalString.append(line1.charAt(x)); } } } System.out.println(totalCost); if(pairFound) { System.out.println(finalString); } } } 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
["uayd\nuxxd\n3\na x 8\nx y 13\nd c 3", "a\nb\n3\na b 2\na b 3\nb a 5", "abc\nab\n6\na b 4\na b 7\nb a 8\nc b 11\nc a 3\na c 0"]
2 seconds
["21\nuxyd", "2\nb", "-1"]
null
Java 8
standard input
[ "shortest paths" ]
88c82ada2e66429900caeac758f7083b
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
1,800
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
standard output
PASSED
6ce1b86fcc39ad417ea8f0d8601623a8
train_002.jsonl
1286463600
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
256 megabytes
import java.io.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; public class CodeForces { public static void main(String[] args) { FastIO io = new FastIO(); String first = io.nextLine(); String second = io.nextLine(); if (first.length() != second.length()) { System.out.println("-1"); return; } int numberOfEdges = io.nextInt(); List<Edge> edges = new ArrayList<>(numberOfEdges); for (int edge = 0; edge < numberOfEdges; edge++) { char from = io.nextToken().charAt(0); char to = io.nextToken().charAt(0); int weight = io.nextInt(); edges.add(new Edge(from, to, weight)); } Map<Character, Integer> charToVertex = new HashMap<>(); Map<Integer, Character> vertexToChar = new HashMap<>(); int ci = 0; Set<Character> unique = new HashSet<>(); for (Edge edge : edges) { if (unique.add(edge.from)) { charToVertex.put(edge.from, ci); vertexToChar.put(ci, edge.from); ci++; } if (unique.add(edge.to)) { charToVertex.put(edge.to, ci); vertexToChar.put(ci, edge.to); ci++; } } for (int i = 0; i < first.length(); i++) { if (first.charAt(i) == second.charAt(i)) { continue; } if (!unique.contains(first.charAt(i)) || !unique.contains(second.charAt(i))) { System.out.println("-1"); return; } } int vertices = unique.size(); int[][] dist = new int[vertices][vertices]; for (int[] row : dist) { Arrays.fill(row, Integer.MAX_VALUE); } for (int i = 0; i < vertices; i++) { dist[i][i] = 0; } for (Edge edge : edges) { int cur = dist[charToVertex.get(edge.from)][charToVertex.get(edge.to)]; if (edge.weight < cur) { dist[charToVertex.get(edge.from)][charToVertex.get(edge.to)] = edge.weight; } } for (int k = 0; k < vertices; k++) { for (int i = 0; i < vertices; i++) { for (int j = 0; j < vertices; j++) { if (dist[i][j] > (long) dist[i][k] + dist[k][j]) { dist[i][j] = dist[i][k] + dist[k][j]; } } } } long minTotalPrice = 0; StringBuilder sb = new StringBuilder(); for (int i = 0; i < first.length(); i++) { char fc = first.charAt(i); char sc = second.charAt(i); if (fc == sc) { sb.append(fc); continue; } long m = Integer.MAX_VALUE; int toIndex = -1; for (int j = 0; j < vertices; j++) { long candidateCost = (long) dist[charToVertex.get(fc)][j] + dist[charToVertex.get(sc)][j]; if (candidateCost < m) { m = candidateCost; toIndex = j; } } if (toIndex == -1) { System.out.println("-1"); return; } sb.append(vertexToChar.get(toIndex)); minTotalPrice += m; } System.out.println(minTotalPrice); System.out.println(sb.toString()); io.close(); } static class Edge { char from; char to; int weight; public Edge(char from, char to, int weight) { this.from = from; this.to = to; this.weight = weight; } } static class FastIO extends PrintWriter { BufferedReader br; StringTokenizer st; public FastIO() { super(new BufferedOutputStream(System.out)); 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 nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } String nextLine() { try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } return ""; } } }
Java
["uayd\nuxxd\n3\na x 8\nx y 13\nd c 3", "a\nb\n3\na b 2\na b 3\nb a 5", "abc\nab\n6\na b 4\na b 7\nb a 8\nc b 11\nc a 3\na c 0"]
2 seconds
["21\nuxyd", "2\nb", "-1"]
null
Java 8
standard input
[ "shortest paths" ]
88c82ada2e66429900caeac758f7083b
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
1,800
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
standard output
PASSED
c5ea9cfc6d02b74f1f3e930f22dba723
train_002.jsonl
1286463600
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
256 megabytes
import java.util.*; public class StringProblem { static class Pair implements Comparable<Pair> { char letter; int cost; Pair(char letter, int cost) { this.letter = letter; this.cost = cost; } public int compareTo(Pair other) { return Integer.compare(this.cost, other.cost); } } private final List<Pair>[] adjacencyList; private int totalCost = 0; private String meet; private StringProblem() { adjacencyList = (ArrayList<Pair>[]) new ArrayList[26]; // cost edges coming out of every letter for (int i = 0; i < 26; i++) adjacencyList[i] = new ArrayList<>(); Scanner in = new Scanner(System.in, "UTF-8"); String first = in.next(), second = in.next(); // If the length of the strings are different, they can't be transformed to the same word. if (first.length() != second.length()) return; final int wordLength = first.length(); for (int i = in.nextInt(); i > 0; i--) { char u = in.next().charAt(0), v = in.next().charAt(0); int cost = in.nextInt(); adjacencyList[u - 'a'].add(new Pair(v, cost)); // cost of changing u to v } // Don't calculate the same thing for the second time. Pair[][] reply = new Pair[26][26]; StringBuilder answer = new StringBuilder(); // where the two words meet for (int i = 0; i < wordLength; i++) { int a = first.charAt(i) - 'a', b = second.charAt(i) - 'a'; if (reply[a][b] == null) { Pair aToB = change(a, b); // where a and be meets and for what cost // Impossible. if (aToB == null) return; char meetingLetter = aToB.letter; int costOfChange = aToB.cost; totalCost += costOfChange; answer.append(meetingLetter); reply[a][b] = aToB; } else { totalCost += reply[a][b].cost; answer.append(reply[a][b].letter); } } meet = answer.toString(); } private Pair change(int a, int b) { int[] distToA = shortestPath(a), distToB = shortestPath(b); int cost = Integer.MAX_VALUE, letter = -1; for (int i = 0; i < 26; i++) { if (distToA[i] != Integer.MAX_VALUE && distToB[i] != Integer.MAX_VALUE) { if (distToA[i] + distToB[i] < cost) { cost = distToA[i] + distToB[i]; letter = i; } } } return letter == -1 ? null : new Pair((char) (letter + 'a'), cost); } private int[] shortestPath(int u) { boolean[] marked = new boolean[26]; int[] costTo = new int[26]; // cost of change from u Arrays.fill(costTo, Integer.MAX_VALUE); costTo[u] = 0; PriorityQueue<Pair> distance = new PriorityQueue<>(); distance.offer(new Pair((char) (u + 'a'), costTo[u])); while (!distance.isEmpty()) { int v = distance.poll().letter - 'a'; marked[v] = true; for (Pair change : adjacencyList[v]) { int w = change.letter - 'a', cost = change.cost; if (!marked[w] && costTo[v] + cost < costTo[w]) { costTo[w] = costTo[v] + cost; distance.offer(new Pair((char) (w + 'a'), costTo[w])); } } } return costTo; } private String solve() { return meet == null ? "-1" : totalCost + "\n" + meet; } public static void main(String[] args) { System.out.println(new StringProblem().solve()); } }
Java
["uayd\nuxxd\n3\na x 8\nx y 13\nd c 3", "a\nb\n3\na b 2\na b 3\nb a 5", "abc\nab\n6\na b 4\na b 7\nb a 8\nc b 11\nc a 3\na c 0"]
2 seconds
["21\nuxyd", "2\nb", "-1"]
null
Java 8
standard input
[ "shortest paths" ]
88c82ada2e66429900caeac758f7083b
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
1,800
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
standard output
PASSED
4a31cef2ac548bc05626f8969da1a60d
train_002.jsonl
1286463600
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.StringTokenizer; import static java.lang.Math.min; /** * 33B * * @author artyom */ public class StringProblem implements Runnable { private BufferedReader in; private PrintStream out; private StringTokenizer tok; private final int n = 26; private final int[][] costs = new int[n][n]; private final int[][] bridges = new int[n][n]; private void solve() throws IOException { String s = nextToken(); String t = nextToken(); int[][] paths = initPaths(); for (int i = 0, m = nextInt(); i < m; i++) { int u = nextChar(), v = nextChar(), cost = nextInt(); if (cost < paths[u][v]) { paths[u][v] = cost; } } if (s.length() != t.length()) { out.print(-1); return; } floydWarshall(paths); calcBestRouts(paths); int totalCost = 0; StringBuilder sb = new StringBuilder(); for (int i = 0, m = s.length(); i < m; i++) { int u = s.charAt(i) - 97, v = t.charAt(i) - 97; if (bridges[u][v] != -1) { totalCost += costs[u][v]; sb.append((char) (bridges[u][v] + 97)); } else { out.print(-1); return; } } out.println(totalCost); out.print(sb); } private void calcBestRouts(int[][] paths) { for (int i = 0; i < n; i++) { bridges[i][i] = i; for (int j = i + 1; j < n; j++) { int minCost = Integer.MAX_VALUE / 2, bridge = -1; for (int k = 0; k < n; k++) { int cost = paths[i][k] + paths[j][k]; if (cost < minCost) { minCost = cost; bridge = k; } } costs[i][j] = costs[j][i] = minCost; bridges[i][j] = bridges[j][i] = bridge; } } } private int[][] initPaths() { int[][] path = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i != j) { path[i][j] = Integer.MAX_VALUE / 2; } } } return path; } private void floydWarshall(int[][] paths) { for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { paths[i][j] = min(paths[i][j], paths[i][k] + paths[k][j]); } } } } //-------------------------------------------------------------- public static void main(String[] args) { new StringProblem().run(); } @Override public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = System.out; tok = null; solve(); in.close(); } catch (IOException e) { System.exit(0); } } private String nextToken() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private int nextChar() throws IOException { return (int) nextToken().charAt(0) - 97; } }
Java
["uayd\nuxxd\n3\na x 8\nx y 13\nd c 3", "a\nb\n3\na b 2\na b 3\nb a 5", "abc\nab\n6\na b 4\na b 7\nb a 8\nc b 11\nc a 3\na c 0"]
2 seconds
["21\nuxyd", "2\nb", "-1"]
null
Java 8
standard input
[ "shortest paths" ]
88c82ada2e66429900caeac758f7083b
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
1,800
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
standard output
PASSED
ee7bb7a5b01a795a04442c5b8d653ea1
train_002.jsonl
1286463600
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { static class Reader { private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;} public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];} public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;} public String s(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();} public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;} public int i(){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 double d() throws IOException {return Double.parseDouble(s()) ;} public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public int[] arr(int n){int[] ret = new int[n];for (int i = 0; i < n; i++) {ret[i] = i();}return ret;} } // |----| /\ | | ----- | // | / / \ | | | | // |--/ /----\ |----| | | // | \ / \ | | | | // | \ / \ | | ----- ------- static int n; public static void main(String[] args)throws IOException { PrintWriter out= new PrintWriter(System.out); Reader sc=new Reader(); String s1=sc.s(); String s2=sc.s(); if(s1.length()!=s2.length()) { System.out.println(-1); System.exit(0); } n=sc.i(); int edges[][]=new int[26][26]; for(int i=0;i<26;i++)Arrays.fill(edges[i],1000000000); for(int i=0;i<n;i++) { int a=sc.s().charAt(0)-97; int b=sc.s().charAt(0)-97; int w=sc.i(); edges[a][b]=Math.min(edges[a][b],w); } int shortest[][]=new int[26][26]; for(int i=0;i<26;i++) Arrays.fill(shortest[i],10000000); for(int i=0;i<26;i++) shortest[i][i]=0; for(int i=0;i<26;i++) { Queue<Integer> q=new LinkedList<>(); Queue<Integer> weight=new LinkedList<>(); q.add(i); weight.add(0); while(q.size()!=0) { int a=q.remove(); int w=weight.remove(); for(int j=0;j<26;j++) { if(edges[a][j]<200) { if(shortest[i][j]>w+edges[a][j]) { shortest[i][j]=w+edges[a][j]; q.add(j); weight.add(w+edges[a][j]); } } } } } int count=0; StringBuilder ans=new StringBuilder(""); for(int i=0;i<s1.length();i++) { if(s1.charAt(i)!=s2.charAt(i)) { int min=10000000; char ch='a'; for(int j=0;j<26;j++) { if(shortest[s1.charAt(i)-97][j]+shortest[s2.charAt(i)-97][j]<min) { min=shortest[s1.charAt(i)-97][j]+shortest[s2.charAt(i)-97][j]; ch=(char)(j+97); } } if(min==10000000) { System.out.println(-1); System.exit(0); } ans=ans.append(ch); count+=min; } else ans=ans.append(s1.charAt(i)); } out.println(count); out.println(ans); out.flush(); } }
Java
["uayd\nuxxd\n3\na x 8\nx y 13\nd c 3", "a\nb\n3\na b 2\na b 3\nb a 5", "abc\nab\n6\na b 4\na b 7\nb a 8\nc b 11\nc a 3\na c 0"]
2 seconds
["21\nuxyd", "2\nb", "-1"]
null
Java 8
standard input
[ "shortest paths" ]
88c82ada2e66429900caeac758f7083b
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
1,800
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
standard output
PASSED
9cc9e48025385547f19a539f6f6f66f7
train_002.jsonl
1286463600
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
256 megabytes
import java.util.*; import java.io.*; public class B33 { public static void main(String[] args) throws IOException { PrintWriter w = new PrintWriter(System.out); InputReader in = new InputReader(System.in); String a = in.nextString(); String b = in.nextString(); int n = in.nextInt(); int[][] matrix = new int[26][26]; for (int i=0; i<26; i++) { Arrays.fill(matrix[i], Integer.MAX_VALUE); } for (int i=0; i<n; i++) { String from = in.nextString(); String to = in.nextString(); int cost = in.nextInt(); matrix[from.charAt(0)-97][to.charAt(0)-97] = Math.min(matrix[from.charAt(0)-97][to.charAt(0)-97], cost); } for (int k=0; k<26; k++) { for (int i=0; i<26; i++) { for (int j=0; j<26; j++) { if (matrix[i][k] < Integer.MAX_VALUE && matrix[k][j] < Integer.MAX_VALUE) { matrix[i][j] = Math.min(matrix[i][j], matrix[i][k] + matrix[k][j]); } } } } for (int i=0; i<26; i++) matrix[i][i] = 0; // for (int i=0; i<26; i++) { // for (int j=0; j<26; j++) { // if (matrix[i][j] != Integer.MAX_VALUE) { // w.println(i + " " + j + " " + matrix[i][j]); // } // } // w.println(); // } int cost = 0; if (a.length() != b.length()) { w.println(-1); } else { StringBuilder sb = new StringBuilder(); for (int i=0; i<a.length(); i++) { if (a.charAt(i) != b.charAt(i)) { int cc = Integer.MAX_VALUE; char x = 'p'; for (int j=0; j<26; j++) { if (matrix[a.charAt(i)-97][j] < Integer.MAX_VALUE && matrix[b.charAt(i)-97][j] < Integer.MAX_VALUE && (matrix[a.charAt(i)-97][j] + matrix[b.charAt(i)-97][j] < cc)) { cc = matrix[a.charAt(i)-97][j] + matrix[b.charAt(i)-97][j]; x = (char)(j+97); } } if (cc == Integer.MAX_VALUE) { cost = -1; break; } else { sb.append(x); cost += cc; } } else { sb.append(a.charAt(i)); } } w.println(cost); if (cost != -1) { w.println(sb.toString()); } } w.close(); } 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 static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } 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 long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { 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 interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["uayd\nuxxd\n3\na x 8\nx y 13\nd c 3", "a\nb\n3\na b 2\na b 3\nb a 5", "abc\nab\n6\na b 4\na b 7\nb a 8\nc b 11\nc a 3\na c 0"]
2 seconds
["21\nuxyd", "2\nb", "-1"]
null
Java 8
standard input
[ "shortest paths" ]
88c82ada2e66429900caeac758f7083b
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
1,800
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
standard output
PASSED
9c5e28375cff95dd8090a3a294850610
train_002.jsonl
1286463600
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
256 megabytes
/** * Created by Alex on 10/20/2014. */ import java.io.*; import java.util.*; public class B33 { BufferedReader br; StringTokenizer in; PrintWriter out; public String nextToken() throws IOException { while (in == null || !in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public static void main(String[] args) throws IOException { new B33().run(); } final int INF = Integer.MAX_VALUE / 2; public void solve() throws IOException { char[] s1 = nextToken().toCharArray(); char[] s2 = nextToken().toCharArray(); if (s1.length != s2.length) { out.print(-1); return; } int[][] d = new int[26][26]; for (int i = 0; i < 26; ++i) Arrays.fill(d[i], INF); int n = nextInt(); for (int i = 0; i < n; ++i) { int a = nextToken().charAt(0) - 'a'; int b = nextToken().charAt(0) - 'a'; int w = nextInt(); d[a][b] = Math.min(d[a][b], w); } for (int i = 0; i < 26; ++i) d[i][i] = 0; for (int k = 0; k < 26; ++k) for (int i = 0; i < 26; ++i) for (int j = 0; j < 26; ++j) d[i][j] = Math.min(d[i][j], d[i][k] + d[k][j]); int ans = 0; char[] anss = new char[s1.length]; for (int i = 0; i < s1.length; ++i) { s1[i] -= 'a'; s2[i] -= 'a'; int min = INF; char mini = 0; for (int j = 0; j < 26; ++j) { if (d[s1[i]][j] + d[s2[i]][j] < min) { min = d[s1[i]][j] + d[s2[i]][j]; mini = (char) (j + 'a'); } } if (min < INF) { ans += min; anss[i] = mini; } else { out.print(-1); return; } } out.println(ans); out.println(new String(anss)); } public void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } }
Java
["uayd\nuxxd\n3\na x 8\nx y 13\nd c 3", "a\nb\n3\na b 2\na b 3\nb a 5", "abc\nab\n6\na b 4\na b 7\nb a 8\nc b 11\nc a 3\na c 0"]
2 seconds
["21\nuxyd", "2\nb", "-1"]
null
Java 8
standard input
[ "shortest paths" ]
88c82ada2e66429900caeac758f7083b
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
1,800
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
standard output
PASSED
d1165d5e99829ad1cab51cbe8dd90c46
train_002.jsonl
1286463600
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
256 megabytes
import java.io.*; public class Main { static int value[][] = new int[27][27]; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder s1 = new StringBuilder(br.readLine()); StringBuilder s2 = new StringBuilder(br.readLine()); if(s1.length()!=s2.length()) { System.out.println(-1); return; } int m = Integer.parseInt(br.readLine()); for(int i = 1 ; i <= 26 ; i++) for(int j = 1 ; j <= 26 ; j++) { if(i==j)continue; value[i][j] = Integer.MAX_VALUE/2; } for(int i = 1 ; i <= m ; i++) { String tmp = br.readLine(); int x = tmp.charAt(0) - 'a' + 1 , y = tmp.charAt(2) - 'a' + 1 , z = Integer.parseInt(tmp.substring(4,tmp.length())); value[x][y]=Math.min(z,value[x][y]); } //读取完成 floyd(); // long ans = 0; for(int i = 0 ; i < s1.length() ; i++) { int c1 = s1.charAt(i) - 'a' + 1 , c2 = s2.charAt(i) - 'a' + 1 , minV = Integer.MAX_VALUE; if(c1==c2)continue; for(int j = 1 ; j <= 26 ; j++) { int x1 = value[c1][j] , x2 = value[c2][j]; if(x1!=Integer.MAX_VALUE/2&&x2!=Integer.MAX_VALUE/2&&x1+x2<minV) { minV=x1+x2; s1.setCharAt(i,(char)(j+'a'-1)); s2.setCharAt(i,(char)(j+'a'-1)); } } ans+=minV; } if(!s1.toString().equals(s2.toString())) System.out.println(-1); else { System.out.println(ans); System.out.println(s1.toString()); } } public static void floyd() { for(int k = 1 ; k <= 26 ; k++) for(int i = 1 ; i <= 26 ; i++) for(int j = 1 ; j <= 26 ; j++) value[i][j] = Math.min(value[i][j],value[i][k]+value[k][j]); } }
Java
["uayd\nuxxd\n3\na x 8\nx y 13\nd c 3", "a\nb\n3\na b 2\na b 3\nb a 5", "abc\nab\n6\na b 4\na b 7\nb a 8\nc b 11\nc a 3\na c 0"]
2 seconds
["21\nuxyd", "2\nb", "-1"]
null
Java 8
standard input
[ "shortest paths" ]
88c82ada2e66429900caeac758f7083b
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
1,800
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
standard output
PASSED
eb37be6e85e44e72ea201c21fe4fb200
train_002.jsonl
1286463600
Boy Valera likes strings. And even more he likes them, when they are identical. That's why in his spare time Valera plays the following game. He takes any two strings, consisting of lower case Latin letters, and tries to make them identical. According to the game rules, with each move Valera can change one arbitrary character Ai in one of the strings into arbitrary character Bi, but he has to pay for every move a particular sum of money, equal to Wi. He is allowed to make as many moves as he needs. Since Valera is a very economical boy and never wastes his money, he asked you, an experienced programmer, to help him answer the question: what minimum amount of money should Valera have to get identical strings.
256 megabytes
import java.io.*; import java.util.*; public class B33 { public static void main(String[] args) throws IOException { input.init(System.in); PrintWriter out = new PrintWriter(System.out); String s = input.next(), t = input.next(); int[][] cs = new int[26][26]; for(int[] A : cs) Arrays.fill(A, 10000001); for(int i = 0; i<26; i++) cs[i][i] = 0; String res = ""; long cost = 0; int n = s.length(); int m = input.nextInt(); for(int i = 0; i<m; i++) { int a = input.next().charAt(0) - 'a'; int b = input.next().charAt(0) - 'a'; int c = input.nextInt(); cs[a][b] = Math.min(cs[a][b], c); } for(int k = 0; k<26; k++) for(int i = 0;i <26; i++) for(int j = 0; j<26; j++) cs[i][j] = Math.min(cs[i][j], cs[i][k] + cs[k][j]); StringBuilder sb = new StringBuilder(""); for(int i = 0; i<n && s.length() == t.length(); i++) { int best = -1; int a = s.charAt(i) - 'a'; int b = t.charAt(i) - 'a'; for(int j = 0; j<26; j++) { if(cs[a][j] == 10000001 || cs[b][j] == 10000001) continue; if(best == -1 || cs[a][j] + cs[b][j] < cs[a][best] + cs[b][best]) best = j; } if(best == -1) cost = (long)1e16; else { cost += cs[a][best] + cs[b][best]; sb.append((char)('a'+best)); } } if(cost < 1e15 && s.length() == t.length()) { out.println(cost); out.println(sb.toString()); } else out.println(-1);; out.close(); } public static class input { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) { reader = new BufferedReader(new InputStreamReader(input)); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["uayd\nuxxd\n3\na x 8\nx y 13\nd c 3", "a\nb\n3\na b 2\na b 3\nb a 5", "abc\nab\n6\na b 4\na b 7\nb a 8\nc b 11\nc a 3\na c 0"]
2 seconds
["21\nuxyd", "2\nb", "-1"]
null
Java 8
standard input
[ "shortest paths" ]
88c82ada2e66429900caeac758f7083b
The first input line contains two initial non-empty strings s and t, consisting of lower case Latin letters. The length of each string doesn't exceed 105. The following line contains integer n (0 ≤ n ≤ 500) — amount of possible changings. Then follow n lines, each containing characters Ai and Bi (lower case Latin letters) and integer Wi (0 ≤ Wi ≤ 100), saying that it's allowed to change character Ai into character Bi in any of the strings and spend sum of money Wi.
1,800
If the answer exists, output the answer to the problem, and the resulting string. Otherwise output -1 in the only line. If the answer is not unique, output any.
standard output
PASSED
a04800ee843d9c2afbf74aedde15cfe4
train_002.jsonl
1387893600
You have number a, whose decimal representation quite luckily contains digits 1, 6, 8, 9. Rearrange the digits in its decimal representation so that the resulting number will be divisible by 7.Number a doesn't contain any leading zeroes and contains digits 1, 6, 8, 9 (it also can contain another digits). The resulting number also mustn't contain any leading zeroes.
256 megabytes
import java.util.*; public class maximus { public static void main(String [] args){ Scanner in=new Scanner(System.in); int array[]={1869,1968,1689,6198,1698,1986,1896,1869}; String str=in.next(); int temp[]=new int[10]; temp[1]=temp[6]=temp[8]=temp[9]=-1; for(int i=0;i<str.length();i++)temp[str.charAt(i)-'0']++; int mod=0; StringBuilder sb=new StringBuilder(); boolean flag=false; for(int i=9;i>=1;i--){ for(int j=1;j<=temp[i];j++){ sb.append(i); if(flag) mod=(mod*10 + i)%7; else mod=i%7; flag=true; } } mod=mod*10000%7; if(flag) sb.append(array[7-mod]); else sb.append(array[7]); for(int i=1;i<=temp[0];i++)sb.append(0); System.out.print(sb); } }
Java
["1689", "18906"]
1 second
["1869", "18690"]
null
Java 6
standard input
[ "number theory", "math" ]
3b10e984d7ca6d4071fd4e743394bb60
The first line contains positive integer a in the decimal record. It is guaranteed that the record of number a contains digits: 1, 6, 8, 9. Number a doesn't contain any leading zeroes. The decimal representation of number a contains at least 4 and at most 106 characters.
1,600
Print a number in the decimal notation without leading zeroes — the result of the permutation. If it is impossible to rearrange the digits of the number a in the required manner, print 0.
standard output
PASSED
54b79298c636557e97e8b1adc56b7130
train_002.jsonl
1387893600
You have number a, whose decimal representation quite luckily contains digits 1, 6, 8, 9. Rearrange the digits in its decimal representation so that the resulting number will be divisible by 7.Number a doesn't contain any leading zeroes and contains digits 1, 6, 8, 9 (it also can contain another digits). The resulting number also mustn't contain any leading zeroes.
256 megabytes
import java.io.*; import java.util.*; public class a { public static void main(String[] args) throws IOException { input.init(System.in); PrintWriter out = new PrintWriter(System.out); String s = input.next(); int[] freq = new int[10]; for(int i = 0; i<s.length(); i++) freq[s.charAt(i) - '0']++; int[] mods = new int[10]; mods[1] = 1; mods[6] = 6; mods[8] = 8; mods[9] = 9; for(int i = 0; i<freq[0]; i++) { for(int j = 0; j<10; j++) if(j == 1 || j == 6 || j == 8 || j == 9) mods[j] = (mods[j] * 10)%7; } StringBuilder res = new StringBuilder(""); for(int i = 0; i<10; i++) { if(i == 1 || i == 6 || i == 8 || i == 9) { for(int j = 0; j<freq[i]-1; j++) res.append(i); continue; } if(i==0) continue; for(int j = 0; j<freq[i]; j++) res.append(i); } int mod = 0; int pow = 1; String str = res.toString(); int n = str.length(); for(int i = n-1; i>=0; i--) { mod = (mod + pow * (str.charAt(i) - '0'))%7; pow = (pow*10)%7; } for(int i = 0; i<freq[0]+4; i++) mod = (mod*10)%7; int[] nums = new int[]{1, 6, 8, 9}; //System.out.println(Arrays.toString(mods)); for(int i = 0; i<4; i++) for(int j = 0; j<4; j++) for(int k = 0; k<4; k++) for(int l = 0; l<4; l++) { if(i==j||i==k||i==l||j==k||j==l||k==l) continue; //System.out.println(i+" "+j+" "+k+" "+l+" "+mod); if((mods[nums[i]] + 3*mods[nums[j]] + 2*mods[nums[k]] + 6*mods[nums[l]] + mod)%7 == 0) { out.print(str); out.print(nums[l]+""+nums[k]+""+nums[j]+""+nums[i]); for(int x = 0; x<freq[0]; x++) out.print(0); out.close(); return; } } out.println(0); out.close(); } public static class input { 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() ); } static long nextLong() throws IOException { return Long.parseLong( next() ); } } }
Java
["1689", "18906"]
1 second
["1869", "18690"]
null
Java 6
standard input
[ "number theory", "math" ]
3b10e984d7ca6d4071fd4e743394bb60
The first line contains positive integer a in the decimal record. It is guaranteed that the record of number a contains digits: 1, 6, 8, 9. Number a doesn't contain any leading zeroes. The decimal representation of number a contains at least 4 and at most 106 characters.
1,600
Print a number in the decimal notation without leading zeroes — the result of the permutation. If it is impossible to rearrange the digits of the number a in the required manner, print 0.
standard output
PASSED
5becb03f690fbfbb9ccebc278df25edc
train_002.jsonl
1387893600
You have number a, whose decimal representation quite luckily contains digits 1, 6, 8, 9. Rearrange the digits in its decimal representation so that the resulting number will be divisible by 7.Number a doesn't contain any leading zeroes and contains digits 1, 6, 8, 9 (it also can contain another digits). The resulting number also mustn't contain any leading zeroes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class A { static class Scanner{ BufferedReader br=null; StringTokenizer tk=null; public Scanner(){ br=new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException{ while(tk==null || !tk.hasMoreTokens()) tk=new StringTokenizer(br.readLine()); return tk.nextToken(); } public int nextInt() throws NumberFormatException, IOException{ return Integer.valueOf(next()); } public double nextDouble() throws NumberFormatException, IOException{ return Double.valueOf(next()); } } static int[] period = {1, 3, 2, 6, 4, 5}; static int[] array = {9, 6, 8, 1}; static boolean solve(int idx, int tam, boolean[] used, int[] a, int mod, StringBuilder sb, int limit){ if (idx == tam){ int nmod = 0; for(int i = 0; i < 4; i++) nmod = nmod + (array[a[i]] * period[(limit + i) % period.length]); nmod += mod; nmod %= 7; if (nmod == 0){ for(int i = 0; i < 4; i++) sb.append(array[a[i]]+""); return true; } return false; } for(int i = 0; i < 4; i++){ if (used[i]) continue; used[i] = true; a[idx] = i; if (solve(idx + 1, tam, used, a, mod, sb, limit)) return true; used[i] = false; } return false; } public static void main(String args[]) throws NumberFormatException, IOException{ Scanner sc = new Scanner(); String cad = sc.next(); StringBuilder sb = new StringBuilder(cad); char[] array = sb.reverse().toString().toCharArray(); int mod = 0; StringBuilder ans = new StringBuilder(); boolean[] machete = new boolean[10]; Arrays.fill(machete, false); machete[1] = machete[8] = machete[6] = machete[9] = true; int minus = 0; for(int i = 0; i < array.length; i++){ int current = array[i] - '0'; if (machete[current]){ machete[current] = false; minus++; continue; } mod = (mod + (current * period[(i - minus)% period.length])) % 7; ans.append(array[i] + ""); } boolean[] used = new boolean[4]; int[] tt = new int[4]; Arrays.fill(used, false); if (solve(0, 4, used, tt, mod, ans, array.length - 4)) System.out.println(ans.reverse().toString()); else System.out.println(0); } }
Java
["1689", "18906"]
1 second
["1869", "18690"]
null
Java 6
standard input
[ "number theory", "math" ]
3b10e984d7ca6d4071fd4e743394bb60
The first line contains positive integer a in the decimal record. It is guaranteed that the record of number a contains digits: 1, 6, 8, 9. Number a doesn't contain any leading zeroes. The decimal representation of number a contains at least 4 and at most 106 characters.
1,600
Print a number in the decimal notation without leading zeroes — the result of the permutation. If it is impossible to rearrange the digits of the number a in the required manner, print 0.
standard output
PASSED
27c986ca632a98b9d756a1f8b18c6ef2
train_002.jsonl
1387893600
You have number a, whose decimal representation quite luckily contains digits 1, 6, 8, 9. Rearrange the digits in its decimal representation so that the resulting number will be divisible by 7.Number a doesn't contain any leading zeroes and contains digits 1, 6, 8, 9 (it also can contain another digits). The resulting number also mustn't contain any leading zeroes.
256 megabytes
import java.util.*; import java.io.*; public class A { public static void main(String[] args) { new A().run(); } public void run() { InputReader reader = new InputReader(System.in); PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); String s = reader.next(); StringBuilder t = new StringBuilder(); boolean[] seen = new boolean[10]; Arrays.fill(seen, false); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); // System.out.println(ch + " " + (int)(ch - '0')); if ((ch == '1' || ch == '6' || ch == '8' || ch == '9') && !seen[(int)(ch - '0')]) { seen[(int)(ch - '0')] = true; } else { t.append(ch); } } // System.out.println(t); int x = 1; int y = 0; for (int i = 0; i < t.length(); i++) { x = x * 10 % 7; y = (10 * y + t.charAt(i) - '0') % 7; } int ans = go("", "1689", x, y); if (ans == -1) { writer.println("0"); } else { writer.println(ans + t.toString()); } writer.close(); } public int go(String sofar, String left, int x, int y) { if (left.length() == 0) { int val = Integer.parseInt(sofar); if ((val * x + y) % 7 == 0) { return val; } return -1; } for (int i = 0; i < left.length(); i++) { int val = go(sofar + left.charAt(i), left.substring(0, i) + left.substring(i + 1), x, y); if (val != -1) { return val; } } return -1; } public class InputReader { private static final int HEAP_SIZE = 128; private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(String file) { try { reader = new BufferedReader(new FileReader(file)); tokenizer = null; } catch (FileNotFoundException e) { System.err.println("File not found."); } } public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String nextLine() { tokenizer = null; try { return reader.readLine(); } catch (IOException e) { return null; } } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public boolean hasNext() { if (tokenizer != null && tokenizer.hasMoreTokens()) { return true; } try { reader.mark(HEAP_SIZE); if (reader.readLine() == null) { return false; } reader.reset(); } catch (IOException e) {} return true; } } }
Java
["1689", "18906"]
1 second
["1869", "18690"]
null
Java 6
standard input
[ "number theory", "math" ]
3b10e984d7ca6d4071fd4e743394bb60
The first line contains positive integer a in the decimal record. It is guaranteed that the record of number a contains digits: 1, 6, 8, 9. Number a doesn't contain any leading zeroes. The decimal representation of number a contains at least 4 and at most 106 characters.
1,600
Print a number in the decimal notation without leading zeroes — the result of the permutation. If it is impossible to rearrange the digits of the number a in the required manner, print 0.
standard output
PASSED
613f580f97afaaa0a238681b13422020
train_002.jsonl
1387893600
You have number a, whose decimal representation quite luckily contains digits 1, 6, 8, 9. Rearrange the digits in its decimal representation so that the resulting number will be divisible by 7.Number a doesn't contain any leading zeroes and contains digits 1, 6, 8, 9 (it also can contain another digits). The resulting number also mustn't contain any leading zeroes.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.text.DecimalFormat; 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.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; import java.math.BigDecimal; import java.math.BigInteger; import javax.naming.BinaryRefAddr; public class palin { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(System.out); Scanner scan = new Scanner(System.in); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { String str = in.next(); int c[] = new int[10]; for (int i = 0; i < str.length(); i++) { c[str.charAt(i) - '0']++; } c[1]--; c[6]--; c[8]--; c[9]--; int mod = 0; for (int i = c.length - 1; i > 0; i--) { for (int j = 0; j < c[i]; j++) { mod = (mod * 10 + i) % 7; out.print(i); } } ArrayList<Integer> al = new ArrayList<Integer>(); al.add(1); al.add(6); al.add(8); al.add(9); while (true) { int temp = mod; for (int i = 0; i < 4; i++) { temp = (temp * 10 + al.get(i)) % 7; } if (temp == 0) { for (int i = 0; i < 4; i++) { out.print(al.get(i)); } break; } Collections.shuffle(al); } for (int i = 0; i < c[0]; i++) { out.print(0); } } } class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public float nextFloat() { return Float.parseFloat(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["1689", "18906"]
1 second
["1869", "18690"]
null
Java 6
standard input
[ "number theory", "math" ]
3b10e984d7ca6d4071fd4e743394bb60
The first line contains positive integer a in the decimal record. It is guaranteed that the record of number a contains digits: 1, 6, 8, 9. Number a doesn't contain any leading zeroes. The decimal representation of number a contains at least 4 and at most 106 characters.
1,600
Print a number in the decimal notation without leading zeroes — the result of the permutation. If it is impossible to rearrange the digits of the number a in the required manner, print 0.
standard output
PASSED
31d3fbb995b3de8aa1a15f9739c36719
train_002.jsonl
1387893600
You have number a, whose decimal representation quite luckily contains digits 1, 6, 8, 9. Rearrange the digits in its decimal representation so that the resulting number will be divisible by 7.Number a doesn't contain any leading zeroes and contains digits 1, 6, 8, 9 (it also can contain another digits). The resulting number also mustn't contain any leading zeroes.
256 megabytes
import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Writer; public class DivisibleBySeven { private static final boolean DEBUG = false; private static final boolean TEST = false; public static void main(String[] args) { try { final BufferedReader in; final OutputWriter out; if (DEBUG) { final String fileIn = DivisibleBySeven.class.getSimpleName().toLowerCase() + ".in"; final String fileOut = DivisibleBySeven.class.getSimpleName().toLowerCase() + ".out"; in = new BufferedReader(new FileReader(fileIn)); out = new OutputWriter(new FileWriter(fileOut)); } else { in = new BufferedReader(new InputStreamReader(System.in)); out = new OutputWriter(new OutputStreamWriter(System.out)); } new DivisibleBySeven().solve(in, out); out.close(); } catch (Exception ex) { ex.printStackTrace(); } } private final void solve(final BufferedReader in, final OutputWriter out) throws Exception { if (TEST) { for (int i = 1000; i <= 10000000; ++i) { String s = String.valueOf(i); int okMask = 0; for (char ch : s.toCharArray()) { if (ch == '1') { okMask |= 1; } if (ch == '6') { okMask |= 2; } if (ch == '8') { okMask |= 4; } if (ch == '9') { okMask |= 8; } } if (okMask != 15) { continue; } String result = solveForString(s); boolean isOk = true; String t = ""; if ("0".equals(result)) { isOk = (t = dfs0(0, new boolean[s.length()], new int[s.length()], s)) == null; } else { int[] count = new int[10]; for (char ch : s.toCharArray()) { ++count[ch - '0']; } for (char ch : result.toCharArray()) { --count[ch - '0']; } for (int c : count) { if (c != 0) { isOk = false; break; } } if (isOk) { isOk = Integer.parseInt(result) % 7 == 0; } } if (!isOk) { System.out.println("ERROR for string = " + s + ", got = " + result + ", possible = " + t); System.exit(1); } } } else { String result = solveForString(in.readLine()); out.writeln(result); } } private final String dfs0(final int pos, final boolean[] used, final int[] positions, final String s) { if (pos == used.length) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < used.length; ++i) { sb.append(s.charAt(positions[i])); } if (sb.charAt(0) == '0') { return null; } return Integer.valueOf(sb.toString()) % 7 == 0 ? sb.toString() : null; } String t; for (int i = 0; i < used.length; ++i) { if (used[i]) { continue; } positions[pos] = i; used[i] = true; if ((t = dfs0(pos + 1, used, positions, s)) != null) { return t; } used[i] = false; } return null; } private final String solveForString(final String string) { final char[] s = new StringBuilder(string).reverse().toString().toCharArray(); final int[] nums = new int[s.length]; for (int i = 0; i < s.length; ++i) { nums[i] = s[i] - '0'; } final int[] pos = new int[4]; for (int i = 0; i < nums.length; ++i) { if (nums[i] == 1) { pos[0] = i; } if (nums[i] == 6) { pos[1] = i; } if (nums[i] == 8) { pos[2] = i; } if (nums[i] == 9) { pos[3] = i; } } final int[] target = new int[] { 1, 6, 8, 9 }; for (int i = nums.length - 1, j = 0; j < target.length; ++j, --i) { for (int q = nums.length - 1; q >= 0; --q) { if (nums[q] == target[j]) { int t; t = nums[q]; nums[q] = nums[i]; nums[i] = t; pos[j] = i; break; } } } pow[0] = 1; for (int i = 0; i < nums.length - 4; ++i) { pow[0] = (pow[0] * 10) % 7; } pow[1] = (pow[0] * 10) % 7; pow[2] = (pow[1] * 10) % 7; pow[3] = (pow[2] * 10) % 7; modButLastFour = 0; for (int i = nums.length - 1; i >= 0; --i) { modButLastFour = (modButLastFour * 10 + nums[i]) % 7; } modButLastFour -= nums[nums.length - 4] * pow[0]; modButLastFour -= nums[nums.length - 3] * pow[1]; modButLastFour -= nums[nums.length - 2] * pow[2]; modButLastFour -= nums[nums.length - 1] * pow[3]; modButLastFour = (modButLastFour % 7 + 7) % 7; boolean isOk = dfs(0, pos, new int[4], new boolean[4], nums); StringBuilder result = new StringBuilder(); if (isOk) { for (int i = nums.length - 1; i >= 0; --i) { result.append((char) ('0' + nums[i])); } } else { result.append("0"); } return result.toString(); } int modButLastFour = 0; int powTenModButLastFour = 0; int pow[] = new int[4]; private final boolean dfs(final int pos, final int[] positions, final int[] newPositions, final boolean[] used, final int[] nums) { if (pos == 4) { nums[positions[newPositions[0]]] = 1; nums[positions[newPositions[1]]] = 6; nums[positions[newPositions[2]]] = 8; nums[positions[newPositions[3]]] = 9; if (isOk(nums)) { return true; } nums[positions[0]] = 1; nums[positions[1]] = 6; nums[positions[2]] = 8; nums[positions[3]] = 9; return false; } for (int i = 0; i < positions.length; ++i) { if (used[i]) { continue; } used[i] = true; newPositions[pos] = i; if (dfs(pos + 1, positions, newPositions, used, nums)) { return true; } used[i] = false; } return false; } private final boolean isOk(int[] nums) { int diff = modButLastFour; diff += nums[nums.length - 4] * pow[0]; diff += nums[nums.length - 3] * pow[1]; diff += nums[nums.length - 2] * pow[2]; diff += nums[nums.length - 1] * pow[3]; return diff % 7 == 0; } private static final class InputReader { private static final byte ZERO = '0'; private static final byte NINE = '9'; private static final int BUFFER_SIZE = 1 << 17; private final BufferedInputStream in; private byte[] buffer = new byte[BUFFER_SIZE + 1]; private int offset = buffer.length; private InputReader(final InputStream in) { this.in = (in instanceof BufferedInputStream) ? ((BufferedInputStream) in) : (new BufferedInputStream(in)); } public int nextInt() throws Exception { int result = 0; int position = this.offset; while (position < BUFFER_SIZE && (buffer[position] < ZERO || buffer[position] > NINE)) { ++position; } if (position >= BUFFER_SIZE) { System.arraycopy(buffer, offset, buffer, 0, position - offset); final int bytesRead = in.read(buffer, position - offset, BUFFER_SIZE - position + offset); buffer[position - offset + (bytesRead == -1 ? 0 : bytesRead)] = 0; offset = 0; return nextInt(); } offset = position; while (position < BUFFER_SIZE && buffer[position] >= ZERO && buffer[position] <= NINE) { result = result * 10 + buffer[position] - ZERO; ++position; } if (position >= BUFFER_SIZE) { System.arraycopy(buffer, offset, buffer, 0, position - offset); final int bytesRead = in.read(buffer, position - offset, BUFFER_SIZE - position + offset); buffer[position - offset + (bytesRead == -1 ? 0 : bytesRead)] = 0; offset = 0; return nextInt(); } offset = position; return result; } public long nextLong() throws Exception { long result = 0; int position = this.offset; while (position < BUFFER_SIZE && (buffer[position] < ZERO || buffer[position] > NINE)) { ++position; } if (position >= BUFFER_SIZE) { System.arraycopy(buffer, offset, buffer, 0, position - offset); final int bytesRead = in.read(buffer, position - offset, BUFFER_SIZE - position + offset); buffer[position - offset + (bytesRead == -1 ? 0 : bytesRead)] = 0; offset = 0; return nextLong(); } offset = position; while (position < BUFFER_SIZE && buffer[position] >= ZERO && buffer[position] <= NINE) { result *= 10; result += buffer[position] - ZERO; ++position; } if (position >= BUFFER_SIZE) { System.arraycopy(buffer, offset, buffer, 0, position - offset); final int bytesRead = in.read(buffer, position - offset, BUFFER_SIZE - position + offset); buffer[position - offset + (bytesRead == -1 ? 0 : bytesRead)] = 0; offset = 0; return nextLong(); } offset = position; return result; } public String next() throws Exception { int position = this.offset; while (position < BUFFER_SIZE && Character.isWhitespace(buffer[position])) { ++position; } if (position >= BUFFER_SIZE) { System.arraycopy(buffer, offset, buffer, 0, position - offset); final int bytesRead = in.read(buffer, position - offset, BUFFER_SIZE - position + offset); buffer[position - offset + (bytesRead == -1 ? 0 : bytesRead)] = 0; offset = 0; return next(); } offset = position; while (position < BUFFER_SIZE && !Character.isWhitespace(buffer[position])) { ++position; } if (position >= BUFFER_SIZE) { System.arraycopy(buffer, offset, buffer, 0, position - offset); final int bytesRead = in.read(buffer, position - offset, BUFFER_SIZE - position + offset); buffer[position - offset + (bytesRead == -1 ? 0 : bytesRead)] = 0; offset = 0; return next(); } final String result = new String(buffer, offset, position - offset); offset = position; return result; } } private static final class OutputWriter { private static final String NEW_LINE = String.format("%n"); private final Writer output; private final StringBuilder buffer = new StringBuilder(2 << 20); public OutputWriter(final Writer output) { this.output = output; } public void write(final int i) { buffer.append(i); } public void write(final String s) { buffer.append(s); } public void writeln(final String s) { buffer.append(s); buffer.append(NEW_LINE); } public void writeln(final long l) { buffer.append(l); buffer.append(NEW_LINE); } public void writeln(final int i) { buffer.append(i); buffer.append(NEW_LINE); } public void close() throws Exception { output.write(buffer.toString()); output.flush(); output.close(); } } }
Java
["1689", "18906"]
1 second
["1869", "18690"]
null
Java 6
standard input
[ "number theory", "math" ]
3b10e984d7ca6d4071fd4e743394bb60
The first line contains positive integer a in the decimal record. It is guaranteed that the record of number a contains digits: 1, 6, 8, 9. Number a doesn't contain any leading zeroes. The decimal representation of number a contains at least 4 and at most 106 characters.
1,600
Print a number in the decimal notation without leading zeroes — the result of the permutation. If it is impossible to rearrange the digits of the number a in the required manner, print 0.
standard output
PASSED
909030aee2ee78d266fadee977062320
train_002.jsonl
1387893600
You have number a, whose decimal representation quite luckily contains digits 1, 6, 8, 9. Rearrange the digits in its decimal representation so that the resulting number will be divisible by 7.Number a doesn't contain any leading zeroes and contains digits 1, 6, 8, 9 (it also can contain another digits). The resulting number also mustn't contain any leading zeroes.
256 megabytes
import java.io.*; import java.util.*; public class A { public static void main(String[] args) throws IOException { A solver = new A(); solver.solve(); } private void solve() throws IOException { FastScanner sc = new FastScanner(System.in); // sc = new FastScanner("1689"); // sc = new FastScanner("18906"); char[] line = sc.next().toCharArray(); int[] digits = new int[10]; for (char c : line) { digits[c - '0']++; } int num = 0; num = get(num, 1, digits[1] - 1); num = get(num, 2, digits[2]); num = get(num, 3, digits[3]); num = get(num, 4, digits[4]); num = get(num, 5, digits[5]); num = get(num, 6, digits[6] - 1); num = get(num, 7, digits[7]); num = get(num, 8, digits[8] - 1); num = get(num, 9, digits[9] - 1); int[] p = {1, 6, 8, 9}; do { int X = p[0] + p[1] * 10 + p[2] * 100 + p[3] * 1000 + num * 10000; if (X % 7 == 0) break; } while (nextPermutation(p)); StringBuilder sb = new StringBuilder(); put(sb, 1, digits[1] - 1); put(sb, 2, digits[2]); put(sb, 3, digits[3]); put(sb, 4, digits[4]); put(sb, 5, digits[5]); put(sb, 6, digits[6] - 1); put(sb, 7, digits[7]); put(sb, 8, digits[8] - 1); put(sb, 9, digits[9] - 1); put(sb, p[3], 1); put(sb, p[2], 1); put(sb, p[1], 1); put(sb, p[0], 1); put(sb, 0, digits[0]); System.out.println(sb.toString()); } private void put(StringBuilder sb, int digit, int count) { for (int i = 0; i < count; i++) { sb.append(digit); } } private int get(int num, int digit, int count) { for (int i = 0; i < count; i++) { num *= 10; num += digit; num %= 7; } return num; } private static boolean nextPermutation(int[] a) { int N = a.length; int i = N - 2; for (; i >= 0; i--) { if (a[i] < a[i + 1]) break; } if (i < 0) return false; for (int j = N - 1; j >= i; j--) { if (a[j] > a[i]) { int temp = a[i]; a[i] = a[j]; a[j] = temp; break; } } for (int j = i + 1; j < (N + i + 1) / 2; j++) { int temp = a[j]; a[j] = a[N + i - j]; a[N + i - j] = temp; } return true; } private static class FastScanner { private BufferedReader br; private StringTokenizer st; public FastScanner(InputStream in) throws IOException { br = new BufferedReader(new InputStreamReader(in)); } public FastScanner(File file) throws IOException { br = new BufferedReader(new FileReader(file)); } public FastScanner(String s) { br = new BufferedReader(new StringReader(s)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); return ""; } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["1689", "18906"]
1 second
["1869", "18690"]
null
Java 6
standard input
[ "number theory", "math" ]
3b10e984d7ca6d4071fd4e743394bb60
The first line contains positive integer a in the decimal record. It is guaranteed that the record of number a contains digits: 1, 6, 8, 9. Number a doesn't contain any leading zeroes. The decimal representation of number a contains at least 4 and at most 106 characters.
1,600
Print a number in the decimal notation without leading zeroes — the result of the permutation. If it is impossible to rearrange the digits of the number a in the required manner, print 0.
standard output
PASSED
de9c793e5d9ce0e54041f03a05dfa178
train_002.jsonl
1387893600
You have number a, whose decimal representation quite luckily contains digits 1, 6, 8, 9. Rearrange the digits in its decimal representation so that the resulting number will be divisible by 7.Number a doesn't contain any leading zeroes and contains digits 1, 6, 8, 9 (it also can contain another digits). The resulting number also mustn't contain any leading zeroes.
256 megabytes
import java.util.Scanner; public class main { public static void main(String[] args) { DivisibleBySeven.run(); } } class DivisibleBySeven { private static String[] table; public static void run() { init_table (); String input = get_input(); String output = get_output(input); System.out.println(output); } private static void init_table () { table = new String[7]; table[0] = "1869"; table[1] = "6819"; table[2] = "1689"; table[3] = "6891"; table[4] = "1698"; table[5] = "8916"; table[6] = "1896"; } private static String get_input() { Scanner reader = new Scanner (System.in); String input = reader.nextLine(); reader.close(); return input; } private static String get_output(String input) { String inst_input = instrument_input (input); Divisor divisor = new Divisor (inst_input); int remainder = divisor.get_remainder(); int neg_remainder = (7 - remainder) % 7; int power = (input.length() - 4) % 6; int multiplier = 1; for (int i = 0; i < power; i++) multiplier = multiplier * 3; multiplier = multiplier % 7; int prefix_remainder = neg_remainder; while (multiplier != 1) { multiplier = (multiplier * 3) % 7; prefix_remainder = (prefix_remainder * 3) % 7; } String output = table[prefix_remainder].concat(inst_input.substring(4)); return output; } private static String instrument_input (String input) { int cnt = 0; boolean[] is_achieved = new boolean[10]; char num_char; int num; char[] input_array = input.toCharArray(); for (int i = 0; i < input.length(); i++) { num_char = input_array[i]; if (num_char == '1' || num_char == '6' || num_char == '8' || num_char == '9') { num = Character.getNumericValue(num_char); if (!is_achieved[num]) { input_array[i] = input_array[cnt]; input_array[cnt] = '0'; cnt++; is_achieved[num] = true; } } } return new String(input_array); } } class Divisor { private String input; private int buf[]; private int idx, bufValue; private boolean is_positive; private int len, start, end; private int remainder; public Divisor (String input) { this.input = input; buf = new int[3]; len = input.length(); start = 0; end = len - 1; remainder = 0; is_positive = false; } public int get_remainder () { for (int i = end; i >= start; i--) { idx = (end - i) % 3; if (idx == 0) { flush_buf (); } buf[idx++] = Character.getNumericValue(input.charAt(i)); } flush_buf (); return remainder; } private void flush_buf () { bufValue = buf[2] * 100 + buf[1] * 10 + buf[0]; bufValue = is_positive ? bufValue : (-1) * bufValue; remainder = (remainder + bufValue) % 7; is_positive = !is_positive; buf[0] = buf[1] = buf[2] = 0; } }
Java
["1689", "18906"]
1 second
["1869", "18690"]
null
Java 6
standard input
[ "number theory", "math" ]
3b10e984d7ca6d4071fd4e743394bb60
The first line contains positive integer a in the decimal record. It is guaranteed that the record of number a contains digits: 1, 6, 8, 9. Number a doesn't contain any leading zeroes. The decimal representation of number a contains at least 4 and at most 106 characters.
1,600
Print a number in the decimal notation without leading zeroes — the result of the permutation. If it is impossible to rearrange the digits of the number a in the required manner, print 0.
standard output
PASSED
5c2e7f3b51fd815488af04ec1e140139
train_002.jsonl
1304175600
Fox Ciel safely returned to her castle, but there was something wrong with the security system of the castle: sensors attached in the castle were covering her.Ciel is at point (1, 1) of the castle now, and wants to move to point (n, n), which is the position of her room. By one step, Ciel can move from point (x, y) to either (x + 1, y) (rightward) or (x, y + 1) (upward).In her castle, c2 sensors are set at points (a + i, b + j) (for every integer i and j such that: 0 ≤ i &lt; c, 0 ≤ j &lt; c).Each sensor has a count value and decreases its count value every time Ciel moves. Initially, the count value of each sensor is t. Every time Ciel moves to point (x, y), the count value of a sensor at point (u, v) decreases by (|u - x| + |v - y|). When the count value of some sensor becomes strictly less than 0, the sensor will catch Ciel as a suspicious individual!Determine whether Ciel can move from (1, 1) to (n, n) without being caught by a sensor, and if it is possible, output her steps. Assume that Ciel can move to every point even if there is a censor on the point.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.util.regex.Matcher; public class SafetySystem implements Runnable { int[] a; int[] b; int x; int y; long[] s; long[] t; long[] t2; int n; private void solve() throws IOException { n = nextInt(); long t = nextLong(); a = new int[2]; b = new int[2]; a[0] = nextInt(); b[0] = nextInt(); int c = nextInt(); a[1] = a[0] + c - 1; b[1] = b[0] + c - 1; s = new long[4]; this.t = new long[4]; this.t2 = new long[4]; Arrays.fill(s, t); x = 1; y = 1; if (!valid()) { writer.println("Impossible"); return; } while (x < n || y < n) { if (x < n) { ++x; add(-1); if (valid()) { writer.print("R"); continue; } add(1); --x; } ++y; add(-1); writer.print("U"); } if (!valid()) throw new RuntimeException(); writer.println(); } private boolean valid() { int sx = x; int sy = y; Arrays.fill(t, 0); if (x < a[0]) { addline(1, 0, a[0] - x); } if (y < b[0]) { addline(0, 1, b[0] - y); } if (x < a[1]) { addline(1, 0, a[1] - x); } if (y < b[1]) { addline(0, 1, b[1] - y); } if (x < n) { addline(1, 0, n - x); } if (y < n) { addline(0, 1, n - y); } System.arraycopy(t, 0, t2, 0, 4); Arrays.fill(t, 0); x = sx; y = sy; if (x < a[0]) { addline(1, 0, a[0] - x); } if (y < b[0]) { addline(0, 1, b[0] - y); } if (y < b[1]) { addline(0, 1, b[1] - y); } if (x < a[1]) { addline(1, 0, a[1] - x); } if (x < n) { addline(1, 0, n - x); } if (y < n) { addline(0, 1, n - y); } x = sx; y = sy; if (s[0] < t[0]) return false; if (s[3] < t[3]) return false; long ns1 = Math.min(s[1], Math.max(t[1], t2[1])) - Math.min(t[1], t2[1]); long ns2 = Math.min(s[2], Math.max(t[2], t2[2])) - Math.min(t[2], t2[2]); if (ns1 % 2 != 0) --ns1; if (ns2 % 2 != 0) --ns2; if (ns1 < 0 || ns2 < 0 || ns1 + ns2 < Math.max(t[1], t2[1]) - Math.min(t[1], t2[1])) return false; return true; } private void addline(int dx, int dy, int count) { int nx = x + count * dx; int ny = y + count * dy; int mx = x + dx; int my = y + dy; for (int ai = 0; ai < 2; ++ai) for (int bi = 0; bi < 2; ++bi) { int ma = 1; if (mx + nx >= a[ai] * 2) ma = -1; int mb = 1; if (my + ny >= b[bi] * 2) mb = -1; t[ai * 2 + bi] += (long) ma * ((long) count * a[ai] - (long) (nx + mx) * count / 2) + (long) mb * ((long) count * b[bi] - (long) (ny + my) * count / 2); } x = nx; y = ny; } private void add(int koef) { for (int ai = 0; ai < 2; ++ai) for (int bi = 0; bi < 2; ++bi) { s[ai * 2 + bi] += koef * (Math.abs(a[ai] - x) + Math.abs(b[bi] - y)); } } public static void main(String[] args) { new SafetySystem().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
Java
["5 25 2 4 1", "3 6 1 2 2", "3 5 1 2 2", "20 492 11 4 8"]
1 second
["RRUURURU", "URUR", "Impossible", "RRRRRRRRRRRRRRRRUUUUURUUUUURRUUUUUUUUU"]
NoteThe answers for the first sample and the second sample are shown on the picture: Here, a red point represents a point that contains a sensor.
Java 8
standard input
[ "math" ]
4e388935c4b08101411bd2040040937b
In the first line there are five integers n, t, a, b, c (2 ≤ n ≤ 2·105,  0 ≤ t ≤ 1014,  1 ≤ a ≤ n - c + 1,  1 ≤ b ≤ n - c + 1,  1 ≤ c ≤ n). Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin stream (also you may use the %I64d specificator).
2,900
If Ciel's objective is possible, output in first line 2n - 2 characters that represent her feasible steps, where i-th character is R if i-th step is moving rightward, or U if moving upward. If there are several solution, output lexicographically first one. Character R is lexicographically earlier than the character U. If her objective is impossible, output Impossible.
standard output
PASSED
6766cc187bfe44d0cf8282b50eac081e
train_002.jsonl
1304175600
Fox Ciel safely returned to her castle, but there was something wrong with the security system of the castle: sensors attached in the castle were covering her.Ciel is at point (1, 1) of the castle now, and wants to move to point (n, n), which is the position of her room. By one step, Ciel can move from point (x, y) to either (x + 1, y) (rightward) or (x, y + 1) (upward).In her castle, c2 sensors are set at points (a + i, b + j) (for every integer i and j such that: 0 ≤ i &lt; c, 0 ≤ j &lt; c).Each sensor has a count value and decreases its count value every time Ciel moves. Initially, the count value of each sensor is t. Every time Ciel moves to point (x, y), the count value of a sensor at point (u, v) decreases by (|u - x| + |v - y|). When the count value of some sensor becomes strictly less than 0, the sensor will catch Ciel as a suspicious individual!Determine whether Ciel can move from (1, 1) to (n, n) without being caught by a sensor, and if it is possible, output her steps. Assume that Ciel can move to every point even if there is a censor on the point.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.util.regex.Matcher; public class SafetySystem implements Runnable { int[] a; int[] b; int x; int y; long[] s; long[] t; long[] t2; int n; private void solve() throws IOException { n = nextInt(); long t = nextLong(); a = new int[2]; b = new int[2]; a[0] = nextInt(); b[0] = nextInt(); int c = nextInt(); a[1] = a[0] + c - 1; b[1] = b[0] + c - 1; s = new long[4]; this.t = new long[4]; this.t2 = new long[4]; Arrays.fill(s, t); x = 1; y = 1; if (!valid()) { writer.println("Impossible"); return; } while (x < n || y < n) { if (x < n) { ++x; add(-1); if (valid()) { writer.print("R"); continue; } add(1); --x; } ++y; add(-1); writer.print("U"); } if (!valid()) throw new RuntimeException(); writer.println(); } private boolean valid() { int sx = x; int sy = y; Arrays.fill(t, 0); if (x < a[0]) { addline(1, 0, a[0] - x); } if (y < b[0]) { addline(0, 1, b[0] - y); } if (x < a[1]) { addline(1, 0, a[1] - x); } if (y < b[1]) { addline(0, 1, b[1] - y); } if (x < n) { addline(1, 0, n - x); } if (y < n) { addline(0, 1, n - y); } System.arraycopy(t, 0, t2, 0, 4); Arrays.fill(t, 0); x = sx; y = sy; if (x < a[0]) { addline(1, 0, a[0] - x); } if (y < b[0]) { addline(0, 1, b[0] - y); } if (y < b[1]) { addline(0, 1, b[1] - y); } if (x < a[1]) { addline(1, 0, a[1] - x); } if (x < n) { addline(1, 0, n - x); } if (y < n) { addline(0, 1, n - y); } x = sx; y = sy; if (s[0] < t[0]) return false; if (s[3] < t[3]) return false; long ns1 = Math.min(s[1], Math.max(t[1], t2[1])) - Math.min(t[1], t2[1]); long ns2 = Math.min(s[2], Math.max(t[2], t2[2])) - Math.min(t[2], t2[2]); if (ns1 % 2 != 0) --ns1; if (ns2 % 2 != 0) --ns2; if (ns1 < 0 || ns2 < 0 || ns1 + ns2 < Math.max(t[1], t2[1]) - Math.min(t[1], t2[1])) return false; return true; } private void addline(int dx, int dy, int count) { int nx = x + count * dx; int ny = y + count * dy; int mx = x + dx; int my = y + dy; for (int ai = 0; ai < 2; ++ai) for (int bi = 0; bi < 2; ++bi) { int ma = 1; if (mx + nx >= a[ai] * 2) ma = -1; int mb = 1; if (my + ny >= b[bi] * 2) mb = -1; t[ai * 2 + bi] += (long) ma * ((long) count * a[ai] - (long) (nx + mx) * count / 2) + (long) mb * ((long) count * b[bi] - (long) (ny + my) * count / 2); } x = nx; y = ny; } private void add(int koef) { for (int ai = 0; ai < 2; ++ai) for (int bi = 0; bi < 2; ++bi) { s[ai * 2 + bi] += koef * (Math.abs(a[ai] - x) + Math.abs(b[bi] - y)); } } public static void main(String[] args) { new SafetySystem().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
Java
["5 25 2 4 1", "3 6 1 2 2", "3 5 1 2 2", "20 492 11 4 8"]
1 second
["RRUURURU", "URUR", "Impossible", "RRRRRRRRRRRRRRRRUUUUURUUUUURRUUUUUUUUU"]
NoteThe answers for the first sample and the second sample are shown on the picture: Here, a red point represents a point that contains a sensor.
Java 6
standard input
[ "math" ]
4e388935c4b08101411bd2040040937b
In the first line there are five integers n, t, a, b, c (2 ≤ n ≤ 2·105,  0 ≤ t ≤ 1014,  1 ≤ a ≤ n - c + 1,  1 ≤ b ≤ n - c + 1,  1 ≤ c ≤ n). Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin stream (also you may use the %I64d specificator).
2,900
If Ciel's objective is possible, output in first line 2n - 2 characters that represent her feasible steps, where i-th character is R if i-th step is moving rightward, or U if moving upward. If there are several solution, output lexicographically first one. Character R is lexicographically earlier than the character U. If her objective is impossible, output Impossible.
standard output
PASSED
b5d25e24c57a15cd98a0559f4ae0766b
train_002.jsonl
1304175600
Fox Ciel safely returned to her castle, but there was something wrong with the security system of the castle: sensors attached in the castle were covering her.Ciel is at point (1, 1) of the castle now, and wants to move to point (n, n), which is the position of her room. By one step, Ciel can move from point (x, y) to either (x + 1, y) (rightward) or (x, y + 1) (upward).In her castle, c2 sensors are set at points (a + i, b + j) (for every integer i and j such that: 0 ≤ i &lt; c, 0 ≤ j &lt; c).Each sensor has a count value and decreases its count value every time Ciel moves. Initially, the count value of each sensor is t. Every time Ciel moves to point (x, y), the count value of a sensor at point (u, v) decreases by (|u - x| + |v - y|). When the count value of some sensor becomes strictly less than 0, the sensor will catch Ciel as a suspicious individual!Determine whether Ciel can move from (1, 1) to (n, n) without being caught by a sensor, and if it is possible, output her steps. Assume that Ciel can move to every point even if there is a censor on the point.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.util.regex.Matcher; public class SafetySystem implements Runnable { int[] a; int[] b; int x; int y; long[] s; long[] t; long[] t2; int n; private void solve() throws IOException { n = nextInt(); long t = nextLong(); a = new int[2]; b = new int[2]; a[0] = nextInt(); b[0] = nextInt(); int c = nextInt(); a[1] = a[0] + c - 1; b[1] = b[0] + c - 1; s = new long[4]; this.t = new long[4]; this.t2 = new long[4]; Arrays.fill(s, t); x = 1; y = 1; if (!valid()) { writer.println("Impossible"); return; } while (x < n || y < n) { if (x < n) { ++x; add(-1); if (valid()) { writer.print("R"); continue; } add(1); --x; } ++y; add(-1); writer.print("U"); } if (!valid()) throw new RuntimeException(); writer.println(); } private boolean valid() { int sx = x; int sy = y; Arrays.fill(t, 0); if (x < a[0]) { addline(1, 0, a[0] - x); } if (y < b[0]) { addline(0, 1, b[0] - y); } if (x < a[1]) { addline(1, 0, a[1] - x); } if (y < b[1]) { addline(0, 1, b[1] - y); } if (x < n) { addline(1, 0, n - x); } if (y < n) { addline(0, 1, n - y); } System.arraycopy(t, 0, t2, 0, 4); Arrays.fill(t, 0); x = sx; y = sy; if (x < a[0]) { addline(1, 0, a[0] - x); } if (y < b[0]) { addline(0, 1, b[0] - y); } if (y < b[1]) { addline(0, 1, b[1] - y); } if (x < a[1]) { addline(1, 0, a[1] - x); } if (x < n) { addline(1, 0, n - x); } if (y < n) { addline(0, 1, n - y); } x = sx; y = sy; if (s[0] < t[0]) return false; if (s[3] < t[3]) return false; long ns1 = Math.min(s[1], Math.max(t[1], t2[1])) - Math.min(t[1], t2[1]); long ns2 = Math.min(s[2], Math.max(t[2], t2[2])) - Math.min(t[2], t2[2]); if (ns1 % 2 != 0) --ns1; if (ns2 % 2 != 0) --ns2; if (ns1 < 0 || ns2 < 0 || ns1 + ns2 < Math.max(t[1], t2[1]) - Math.min(t[1], t2[1])) return false; return true; } private void addline(int dx, int dy, int count) { int nx = x + count * dx; int ny = y + count * dy; int mx = x + dx; int my = y + dy; for (int ai = 0; ai < 2; ++ai) for (int bi = 0; bi < 2; ++bi) { int ma = 1; if (mx + nx >= a[ai] * 2) ma = -1; int mb = 1; if (my + ny >= b[bi] * 2) mb = -1; t[ai * 2 + bi] += (long) ma * ((long) count * a[ai] - (long) (nx + mx) * count / 2) + (long) mb * ((long) count * b[bi] - (long) (ny + my) * count / 2); } x = nx; y = ny; } private void add(int koef) { for (int ai = 0; ai < 2; ++ai) for (int bi = 0; bi < 2; ++bi) { s[ai * 2 + bi] += koef * (Math.abs(a[ai] - x) + Math.abs(b[bi] - y)); } } public static void main(String[] args) { new SafetySystem().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
Java
["5 25 2 4 1", "3 6 1 2 2", "3 5 1 2 2", "20 492 11 4 8"]
1 second
["RRUURURU", "URUR", "Impossible", "RRRRRRRRRRRRRRRRUUUUURUUUUURRUUUUUUUUU"]
NoteThe answers for the first sample and the second sample are shown on the picture: Here, a red point represents a point that contains a sensor.
Java 6
standard input
[ "math" ]
4e388935c4b08101411bd2040040937b
In the first line there are five integers n, t, a, b, c (2 ≤ n ≤ 2·105,  0 ≤ t ≤ 1014,  1 ≤ a ≤ n - c + 1,  1 ≤ b ≤ n - c + 1,  1 ≤ c ≤ n). Please do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin stream (also you may use the %I64d specificator).
2,900
If Ciel's objective is possible, output in first line 2n - 2 characters that represent her feasible steps, where i-th character is R if i-th step is moving rightward, or U if moving upward. If there are several solution, output lexicographically first one. Character R is lexicographically earlier than the character U. If her objective is impossible, output Impossible.
standard output
PASSED
d96d6e362d28eb4434bd75cca10903fc
train_002.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.*; import javax.swing.text.InternationalFormatter; import java.math.*; import org.omg.CORBA.Any; public class template { static long time = 0, mp = Integer.MAX_VALUE, k = 0, cnt = 0;; static int[] bp; static int[] low; static int[] des; static boolean bipar = true; static ArrayList<Integer>[] a ; static String sb = ""; public static void main(String[] args) throws IOException { Reader scn = new Reader(); int n = scn.nextInt(); int []p=new int[n+1]; a=new ArrayList[n+1]; for(int i=1; i<a.length; i++) a[i]=new ArrayList<Integer>(); for(int i=1; i<p.length; i++){ p[i]=scn.nextInt(); if(p[i] != -1){ a[i].add(p[i]); a[p[i]].add(i); } } int ans=0; for(int i=1; i<p.length; i++){ if(p[i]==-1){ dfs(i, new HashSet<Integer>(),1); } } System.out.println(cnt); } private static void dfs(int v, HashSet<Integer> visited, int depth) { cnt=Math.max(cnt, depth); visited.add(v); for(int nbr:a[v]){ if(!visited.contains(nbr)) dfs(nbr, visited, depth+1); } } // _________________________TEMPLATE_____________________________________________________________ static class pair implements Comparable<pair> { int u; int v; // int cnt; pair(int b, int a) { u = b; v = a; // cnt = x; } @Override public int compareTo(pair o) { return -this.u + o.v; } } // -----------PrintWriter for faster output--------------------------------- public static PrintWriter out; public 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[100000 + 1]; // 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 int[] nextIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public int[][] nextInt2DArray(int m, int n) throws IOException { int[][] arr = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) arr[i][j] = nextInt(); } return arr; } } // private static void rem(HashMap<Integer, Integer> hm) { // // Iterator<Map.Entry<Integer, Integer>> itr = hm.entrySet().iterator(); // ArrayList<Integer> p=new ArrayList<>(); // // // while(itr.hasNext()){ // Map.Entry<Integer, Integer> entry = itr.next(); // p.add(entry.getKey()); // // } // // // for(int i:p){ // // if(hm.get(i)>1) // hm.put(i, hm.get(i)-1); // else // hm.remove(i); // } // } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 8
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
52f904e94a9f3303f9077a3af45172ed
train_002.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.*; public class Main { public static void main(String args[]) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int ans = 0; Set<Integer> visited = new HashSet<Integer>(); HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); HashMap<Integer,HashSet<Integer>> hash = new HashMap<Integer,HashSet<Integer>>(); for(int i=1;i<=n;i++) { int temp = scan.nextInt(); if(temp!=-1) map.put(i, temp); } for(int i=1;i<=n;i++) { hash.put(i,new HashSet<Integer>()); int curr = i; while(map.get(curr)!=null) { hash.get(i).add(map.get(curr)); curr = map.get(curr); } ans = Math.max(ans,hash.get(i).size()); } ans = ans + 1; System.out.println(ans); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 8
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
3ac550e45ae857511140b8280cb5a499
train_002.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
/* Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. But if it had to perish twice, I think I know enough of hate To say that for destruction ice Is also great And would suffice. */ import java.io.*; import java.util.*; public final class Main{ static class DSU{ int[] parent; int[] size; DSU(int n){ parent = new int[n + 1]; size = new int[n + 1]; for(int i = 0; i <= n; i++){ parent[i] = i; size[i] = 1; } } int getRoot(int i){ while(i != parent[i]){ parent[i] = parent[parent[i]]; i = parent[i]; } return i; } boolean find(int i, int j){ return (getRoot(i) == getRoot(j)) ? true : false; } void union(int i, int j){ if(find(i, j)) return; int rooti = getRoot(i); int rootj = getRoot(j); if(size[rooti] > size[rootj]){ parent[rootj] = rooti; size[rooti] += size[rootj]; } else{ parent[rooti] = rootj; size[rootj] += size[rooti]; } } } public static final long MOD = 1000000007; public static final int limit = 1000005; public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); //int t = in.nextInt(); int t=1; while (t-- > 0) { int i; int n = in.nextInt(); int[] p = new int[n]; for( i = 0; i < n ; i++ ){ p[i] = in.nextInt(); } int ans = 0; for( i = 0; i < n; i++ ){ int d = 1, j = i; while(p[j] != -1){ j = p[j] - 1; //p[j] = -1; d++; } if(d > ans) ans = d; } w.println(ans); //w.println(n); } w.close(); } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 8
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
964b16faab617ba50812c40143dc4101
train_002.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.*; public class Main{ public static void main(String [] args) { Scanner scan = new Scanner(System.in); int n= scan.nextInt(); int a[] = new int[n+1]; for(int i=1;i<=n;i++) { a[i]=scan.nextInt(); } int max =0; for(int i=1;i<=n;i++) { int x = a[i]; int count=1; while(x!=-1) { x=a[x]; count++; } max = Math.max ( max , count); } System.out.println(max); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 8
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
9da32ec197ef96e63f6918c650fa3df9
train_002.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.*; public class Party { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] managers = new int[n]; for(int i = 0; i < n; i++) { managers[i] = scanner.nextInt(); } int maxCount = 0; for(int i = 0; i < n; i++) { int currentCount = 1; int current = managers[i]; while(current != -1) { current = managers[current-1]; currentCount++; } maxCount = currentCount > maxCount ? currentCount : maxCount; } System.out.println(maxCount); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 8
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
b92e6ad06e857f81bea2a16d0820ed81
train_002.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
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.Vector; import java.util.Scanner; import java.util.Stack; import java.util.ArrayList; /** * Built using CHelper plug-in * Actual solution is at the top * * @author AEroui */ 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); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); ArrayList<Integer>[] adjList = new ArrayList[n + 1]; boolean[] isParent = new boolean[n + 1]; for (int i = 1; i <= n; ++i) adjList[i] = new ArrayList<>(); for (int i = 1; i <= n; ++i) { int parent = in.nextInt(); if (parent == -1) { isParent[i] = true; continue; } adjList[parent].add(i); } int ans = 1; boolean[] vis = new boolean[n + 1]; int[] level = new int[n + 1]; Arrays.fill(level, Integer.MAX_VALUE); for (int i = 1; i <= n; ++i) if (!vis[i] && isParent[i]) { Stack<Integer> stk = new Stack<>(); stk.push(i); level[i] = 1; while (!stk.isEmpty()) { int u = stk.pop(); if (vis[u]) continue; vis[u] = true; for (Integer v : adjList[u]) { if (!vis[v]) { stk.push(v); level[v] = Math.min(level[v], level[u] + 1); } } } } for (int i = 1; i <= n; ++i) if (level[i] < Integer.MAX_VALUE) { ans = Math.max(ans, level[i]); } out.println(ans); } } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 8
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
e0e02400286110a8d5161b462c68d467
train_002.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static int level(int [] p,int i) { int l = 1; int manager = p[i]; while(manager != -1) { manager = p[manager-1]; l++; } return l; } public static void main(String [] args) throws IOException { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); StringBuilder output = new StringBuilder(); String line = input.readLine(); //String arr [] = line.split(" "); int n = Integer.parseInt(line); int p [] = new int [n]; for(int i=0;i<n;i++) { p[i] = Integer.parseInt(input.readLine()); } int max = level(p, 0); for(int i=1;i<n;i++) { max = Math.max(max, level(p, i)); } System.out.print(max); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 8
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
0c34e754d09bcbb7f72b7456734b3267
train_002.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.*; public class CF116C { static int level(int[] kk, int[] pp, int i) { if (kk[i] > 0) return kk[i]; return kk[i] = 1 + (pp[i] < 0 ? 0 : level(kk, pp, pp[i])); } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int[] kk = new int[n]; int[] pp = new int[n]; for (int i = 0; i < n; i++) pp[i] = Integer.parseInt(br.readLine()) - 1; int max = 0; for (int i = 0; i < n; i++) { int k = level(kk, pp, i); if (max < k) max = k; } System.out.println(max); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 8
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
8ee4781b1646ca3e7db1b3313882a1c4
train_002.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Scanner; import java.math.*; import java.util.StringTokenizer; /** * * @author T4reQ */ public class Codeforces { static int[] parent; static boolean[] seen; static int depth = -1; public static void main(String[] args) throws Exception { FastScanner in = new FastScanner(); int n = in.nextInt(); parent = new int[n]; seen = new boolean[n]; for (int i = 0; i < n; i++) { int x = in.nextInt(); if (x != -1) { parent[i] = x - 1; } else { parent[i] = -1; } } for (int i = 0; i < n; i++) { Arrays.fill(seen, false); dfs(i, 1); } System.out.println(depth); } static void dfs(int node, int len) { if (seen[node] || parent[node] == -1) { depth = Math.max(depth, len); return; } seen[node] = true; dfs(parent[node], len + 1); } static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { 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()); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 8
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
5cfdafa50551aa5f7eb5db19aa755c5e
train_002.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
// Nailed it :) import java.io.*; import java.util.*; import java.awt.*; public class C { StringTokenizer st; BufferedReader in; PrintWriter ob; boolean visited[]; int val; public static void main(String args[])throws IOException { new C().run(); } void run()throws IOException { in=new BufferedReader(new InputStreamReader(System.in)); ob=new PrintWriter(System.out); solve(); ob.flush(); } void solve()throws IOException { read(); int n=ni(); int a[]=new int[n]; ArrayList<Set<Integer>> list=new ArrayList<Set<Integer>>(n); for(int i=0;i<n;i++) list.add(new HashSet<Integer>()); int start[]=new int[n]; Arrays.fill(start, -1); int k=-1; for(int i=0;i<n;i++) { read(); int x=ni(); if(x!=-1){ list.get(i).add(x-1); list.get(x-1).add(i); } else{ k+=1; start[k]=i; } } visited=new boolean[n]; int ans=0; for(int i=0;i<=k;i++) { val=-1; dfs(list,start[i],1); ans=Math.max(ans, val); } ob.println(ans); } void dfs(ArrayList<Set<Integer>> list,int i,int d){ visited[i]=true; val=Math.max(val,d); for(int u : list.get(i)){ if(visited[u]==false){ dfs(list,u,d+1); } } } void read()throws IOException { st=new StringTokenizer(in.readLine()); } int ni(){ return Integer.parseInt(st.nextToken()); } long nl(){ return Long.parseLong(st.nextToken()); } double nd(){ return Double.parseDouble(st.nextToken()); } String ns(){ return st.nextToken(); } char nc(){ return st.nextToken().charAt(0); } int[] nia(int n)throws IOException { int a[]=new int[n]; read(); for(int i=0;i<n;i++){ a[i]=Integer.parseInt(st.nextToken()); } return a; } long[] nla(int n)throws IOException { long a[]=new long[n]; read(); for(int i=0;i<n;i++){ a[i]=Long.parseLong(st.nextToken()); } return a; } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 8
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
fe3f2cdd66c05bae718fd747155f1215
train_002.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.util.HashMap; import java.util.Map; import java.util.Scanner; /** * * @author gilad */ public class Party { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); Map<Integer, Integer> map = new HashMap<>(); //employee mapped to parent for (int i = 1; i <= t; i++) { map.put(i, in.nextInt()); } int max = 0; for (Integer num : map.keySet()) { int dfs = dfs(map, num); if (dfs > max) max = dfs; } System.out.println(max); } public static int dfs(Map<Integer, Integer> map, int num) { if (map.get(num) == -1) return 1; return 1 + dfs(map, map.get(num)); } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 8
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
14010ffd1aa9197e501848aeea5186bc
train_002.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class Main { final static long mod = 1000000007; public static void main(String[] args) throws Exception { STDIN scan = new STDIN(); PrintWriter pw = new PrintWriter(System.out); int n = scan.nextInt(); Node[] node = new Node[n]; for(int i = 0; i < n; i++) node[i] = new Node(); for(int i = 0; i < n; i++) { int par = scan.nextInt()-1; if(par < 0) node[i].depth = 1; else node[i].parent = node[par]; } int max = Integer.MIN_VALUE; for(int i = 0; i < n; i++) max = Math.max(max, calcDepth(node[i])); pw.println(max); pw.flush(); } static int calcDepth(Node node) { if(node.depth > 0) return node.depth; node.depth = 1 + calcDepth(node.parent); return node.depth; } static class Node{ Node parent = null; int depth = -1; } static class STDIN { BufferedReader br; StringTokenizer st; public STDIN() { br = new BufferedReader(new InputStreamReader(System.in)); st = null; } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } double nextDouble() throws Exception { return Double.parseDouble(next()); } String next() throws Exception { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws Exception { return br.readLine(); } } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 8
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
afdd64121ca0e9f20977c24128e112b1
train_002.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; public class CF116C { static ArrayList<Integer>[] adjList; static boolean[] visited; public static void main(String[] args) throws IOException { FastScanner sc = new FastScanner(System.in); int n = sc.nextInt(); adjList = new ArrayList[n]; visited = new boolean[n]; for (int i = 0; i < n; i++) { adjList[i] = new ArrayList<>(); } for (int i = 0; i < n; i++) { int parent = sc.nextInt(); if(parent != -1) adjList[parent-1].add(i); } int max = 0; for (int i = 0; i < n; i++) { if(!visited[i]) max = Math.max(max, dfs(i)); } System.out.println(max); } static int dfs(int i) { visited[i] = true; if(adjList[i].size() == 0) return 1; int max = 0; for (int j = 0; j < adjList[i].size(); j++) { // System.out.println(adjList[i].get(j)); max = Math.max(max, dfs(adjList[i].get(j)) + 1); } return max; } static class FastScanner { StringTokenizer st; BufferedReader br; public FastScanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public FastScanner(String s) throws FileNotFoundException{br = new BufferedReader(new FileReader(new File(s)));} public String next() throws IOException { 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
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 8
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
45d5d96161940dd22e8f22b436a15236
train_002.jsonl
1316098800
A company has n employees numbered from 1 to n. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee A is said to be the superior of another employee B if at least one of the following is true: Employee A is the immediate manager of employee B Employee B has an immediate manager employee C such that employee A is the superior of employee C. The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.Today the company is going to arrange a party. This involves dividing all n employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees A and B such that A is the superior of B.What is the minimum number of groups that must be formed?
256 megabytes
import java.util.*; import java.io.*; public class party { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int numpeople=sc.nextInt(); GraphAdjacencyList adjlist=new GraphAdjacencyList(numpeople); for(int i=1;i<=numpeople;i++) { int temp=sc.nextInt(); if(temp==-1) { } else { adjlist.setEdge(i, temp); } } int max=0; for(int i=1;i<=numpeople;i++) { //System.out.println(adjlist.getEdge(i)); //System.out.println(adjlist.) } for(int i=1;i<=numpeople;i++) { if(adjlist.countmax(i)>max) { max=adjlist.countmax(i); } } System.out.println(max); } } class GraphAdjacencyList { /* Makes use of Map collection to store the adjacency list for each vertex.*/ private Map<Integer, List<Integer>> Adjacency_List; /* * Initializes the map to with size equal to number of vertices in a graph * Maps each vertex to a given List Object */ public GraphAdjacencyList(int number_of_vertices) { Adjacency_List = new HashMap<Integer, List<Integer>>(); for (int i = 1 ; i <= number_of_vertices ; i++) { Adjacency_List.put(i, new LinkedList<Integer>()); } } public List<Integer> getEdge(int source) { if (source > Adjacency_List.size()) { System.out.println("the vertex entered is not present"); return null; } return Adjacency_List.get(source); } /* Adds nodes in the Adjacency list for the corresponding vertex */ public void setEdge(int source , int destination) { if (source > Adjacency_List.size() || destination > Adjacency_List.size()) { System.out.println("the vertex entered in not present "); return; } List<Integer> slist = Adjacency_List.get(source); slist.add(destination); // List<Integer> dlist = Adjacency_List.get(destination); // dlist.add(source); } public int countmax(int source) { int count=1; while(Adjacency_List.get(source).size()>0) { count+=Adjacency_List.get(source).size(); source=Adjacency_List.get(source).get(Adjacency_List.get(source).size()-1); //System.out.println("current count "+count + " Source: "+source); } //System.out.println("count "+count); return count; } }
Java
["5\n-1\n1\n2\n1\n-1"]
3 seconds
["3"]
NoteFor the first example, three groups are sufficient, for example: Employee 1 Employees 2 and 4 Employees 3 and 5
Java 8
standard input
[ "dfs and similar", "trees", "graphs" ]
8d911f79dde31f2c6f62e73b925e6996
The first line contains integer n (1 ≤ n ≤ 2000) — the number of employees. The next n lines contain the integers pi (1 ≤ pi ≤ n or pi = -1). Every pi denotes the immediate manager for the i-th employee. If pi is -1, that means that the i-th employee does not have an immediate manager. It is guaranteed, that no employee will be the immediate manager of him/herself (pi ≠ i). Also, there will be no managerial cycles.
900
Print a single integer denoting the minimum number of groups that will be formed in the party.
standard output
PASSED
36832fa7e56173693f13d17c7c25e3f0
train_002.jsonl
1594565100
Let $$$a$$$ and $$$b$$$ be some non-negative integers. Let's define strange addition of $$$a$$$ and $$$b$$$ as following: write down the numbers one under another and align them by their least significant digit; add them up digit by digit and concatenate the respective sums together. Assume that both numbers have an infinite number of leading zeros.For example, let's take a look at a strange addition of numbers $$$3248$$$ and $$$908$$$: You are given a string $$$c$$$, consisting of $$$n$$$ digits from $$$0$$$ to $$$9$$$. You are also given $$$m$$$ updates of form: $$$x~d$$$ — replace the digit at the $$$x$$$-th position of $$$c$$$ with a digit $$$d$$$. Note that string $$$c$$$ might have leading zeros at any point of time.After each update print the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$.Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; 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.HashMap; import java.util.HashSet; import java.util.StringTokenizer; import java.util.TreeMap; public class COVID { static ArrayList<Integer>[] adjList; static int mod; static int INF=(int)1e6; static long[] dp,dplr,dpl,dpr; static int []arr; static int n; public static void build() { dp=new long[n<<2]; dplr=new long[n<<2]; dpl=new long[n<<2]; dpr=new long[n<<2]; build(1,1,n); } public static int calc(int d) { return d+1; } public static int calc(int ten,int ones) { int num=ten*10+ones; if(num<10)return 0; return Math.max(0, 19-num); } public static void build(int v, int b, int e) { if(e==b) { dp[v]=arr[e]+1; dpl[v]=dpr[v]=dplr[v]=1; }else { int mid=e+b>>1; build(v<<1,b,mid); build(v<<1|1,mid+1,e); combine(mid, v,b,e); } } public static void combine(int mid, int v, int b, int e) { // mid of two dig all included long dig2mid=mul(mul(calc(arr[mid],arr[mid+1]),dpr[v<<1]),dpl[v<<1|1]); // mid of 1 dig long dig1mid=mul(dp[v<<1],dp[v<<1|1]); dp[v]= add(dig1mid,dig2mid); // for left,right exclusive dig2mid=mul(dplr[v<<1],mul(dplr[v<<1|1],calc(arr[mid],arr[mid+1]))); if(mid-b+1==1||e-mid==1)dig2mid=0; dig1mid=mul(dpl[v<<1],dpr[v<<1|1]); dplr[v]=add(dig2mid,dig1mid); // for left exclusive dig2mid=mul(calc(arr[mid],arr[mid+1]),mul(dplr[v<<1],dpl[v<<1|1])); if(mid-b+1<=1)dig2mid=0; dig1mid=mul(dpl[v<<1],dp[v<<1|1]); dpl[v]=add(dig1mid,dig2mid); //for right exclusive dig2mid= mul(calc(arr[mid],arr[mid+1]),mul(dpr[v<<1],dplr[v<<1|1])); if(e-mid<=1)dig2mid=0; dig1mid=mul(dp[v<<1],dpr[v<<1|1]); dpr[v]=add(dig1mid, dig2mid); } public static long update(int i,int val) { update(1,1,n,i,val); return dp[1]; } public static void update(int v, int b, int e,int idx, int val) { if(b==e&&e==idx) { arr[e]=val; dp[v]=arr[e]+1; dpl[v]=dpr[v]=dplr[v]=1; }else { int mid=b+e>>1; if(idx<=mid) { update(v<<1, b,mid,idx,val); }else { update(v<<1|1, mid+1,e,idx,val); } combine(mid, v,b,e); } } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter pw= new PrintWriter(System.out); mod=998244353; n=sc.nextInt(); int m=sc.nextInt(); arr=new int[1+n]; int idx=1; for(char c:sc.next().toCharArray()) { arr[idx++]=c-'0'; } build(); // System.out.println(Arrays.toString(dp)); // System.out.println(Arrays.toString(dpl)); // System.out.println(Arrays.toString(dpr)); // System.out.println(Arrays.toString(dplr)); // m=0; while(m-->0) { pw.println(update(sc.nextInt(),sc.nextInt())); // System.out.println(" ************ "); // System.out.println(Arrays.toString(dp)); // System.out.println(Arrays.toString(dpl)); // System.out.println(Arrays.toString(dpr)); // System.out.println(Arrays.toString(dplr)); } pw.close(); } static long gcd(long a, long b) { return (b==0)?a:gcd(b,a%b); } static long lcm(long a, long b) { return a/gcd(a,b)*b; } public static int log(int n , int base) { int ans=0; while(n+1>base) { ans++; n/=base; } return ans; } static int pow(int b,long e) { int ans=1; while(e>0) { if((e&1)==1) ans=(int)((ans*1l*b)); e>>=1;{ } b=(int)((b*1l*b)); } return ans; } static long powmod(long b,long e, int mod) { long ans=1; b%=mod; while(e>0) { if((e&1)==1) ans=(int)((ans*1l*b)%mod); e>>=1; b=(int)((b*1l*b)%mod); } return ans; } public static long add(long a, long b) { return (a+b)%mod; } public static long mul(long a, long b) { return ((a%mod)*(b%mod))%mod; } static class Pair implements Comparable<Pair>{ int x;int y; public Pair(int a,int b) { this.x=a;y=b; } public int compareTo(Pair o) { return (x==o.x)?((y>o.y)?1:(y==o.y)?0:-1):((x>o.x)?1:-1); // return y-o.y; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + x; result = prime * result + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Pair other = (Pair) obj; if (x != other.x) return false; if (y != other.y) return false; return true; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String s) throws FileNotFoundException{ br = new BufferedReader(new FileReader(s));} public long[] nextLongArr(int n) throws IOException { long[] arr=new long[n]; for(int i=0;i<n;i++) arr[i]=nextLong(); return arr; } public int[] nextIntArr(int n) throws IOException { int[] arr=new int[n]; for(int i=0;i<n;i++) arr[i]=nextInt(); return arr; } 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; } if (sb.length() == 18) { res += Long.parseLong(sb.toString()) / f; sb = new StringBuilder("0"); } } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } public static void shuffle(int[] a) { int n = a.length; for (int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } }
Java
["2 3\n14\n2 4\n2 1\n1 0"]
5 seconds
["15\n12\n2"]
NoteAfter the first update $$$c$$$ is equal to $$$14$$$. The pairs that sum up to $$$14$$$ are: $$$(0, 14)$$$, $$$(1, 13)$$$, $$$(2, 12)$$$, $$$(3, 11)$$$, $$$(4, 10)$$$, $$$(5, 9)$$$, $$$(6, 8)$$$, $$$(7, 7)$$$, $$$(8, 6)$$$, $$$(9, 5)$$$, $$$(10, 4)$$$, $$$(11, 3)$$$, $$$(12, 2)$$$, $$$(13, 1)$$$, $$$(14, 0)$$$.After the second update $$$c$$$ is equal to $$$11$$$.After the third update $$$c$$$ is equal to $$$01$$$.
Java 8
standard input
[ "dp", "data structures", "matrices" ]
d3baf23c53ba50a03f5ef63d58d177cb
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^5$$$) — the length of the number $$$c$$$ and the number of updates. The second line contains a string $$$c$$$, consisting of exactly $$$n$$$ digits from $$$0$$$ to $$$9$$$. Each of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$d$$$ ($$$1 \le x \le n$$$, $$$0 \le d \le 9$$$) — the descriptions of updates.
2,600
Print $$$m$$$ integers — the $$$i$$$-th value should be equal to the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$ after $$$i$$$ updates are applied. Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
standard output
PASSED
67c29266bee773fe28491c6092c3d0d9
train_002.jsonl
1594565100
Let $$$a$$$ and $$$b$$$ be some non-negative integers. Let's define strange addition of $$$a$$$ and $$$b$$$ as following: write down the numbers one under another and align them by their least significant digit; add them up digit by digit and concatenate the respective sums together. Assume that both numbers have an infinite number of leading zeros.For example, let's take a look at a strange addition of numbers $$$3248$$$ and $$$908$$$: You are given a string $$$c$$$, consisting of $$$n$$$ digits from $$$0$$$ to $$$9$$$. You are also given $$$m$$$ updates of form: $$$x~d$$$ — replace the digit at the $$$x$$$-th position of $$$c$$$ with a digit $$$d$$$. Note that string $$$c$$$ might have leading zeros at any point of time.After each update print the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$.Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
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.ArrayList; /** * 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); StrangeAddition solver = new StrangeAddition(); solver.solve(1, in, out); out.close(); } static class StrangeAddition { int[] str; long[][][][] matrices = new long[10][10][][]; long MOD = 998244353; public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(); // int N = 500000; int M = in.nextInt(); // int M = 500000; if (N == 1) { int a = in.nextInt(); while (M-- > 0) { in.nextInt(); out.println(in.nextInt() + 1); } } else { int id = 0; str = new int[N]; for (char a : in.next().toCharArray()) { str[id++] = Character.getNumericValue(a); } // str = new int[N]; // for (int i = 0; i < N; i++) { // str[i] = (int)(Math.random() * 10); // } SegmentTree seg = new SegmentTree(N - 1); for (int first = 0; first <= 9; first++) { for (int second = 0; second <= 9; second++) { matrices[first][second] = new long[2][2]; if (first == 0) { matrices[first][second][0][0] = 1; } else { matrices[first][second][0][0] = first + 1; if (first == 1) { if (second <= 8) { matrices[first][second][0][1] = 10 - second - 1; } } } matrices[first][second][1][0] = 1; } } seg.build(1, 0, N - 2); for (int i = 0; i < M; i++) { int index = in.nextInt() - 1; // int index = (int)(Math.random() * N); int a = in.nextInt(); // int a = (int)(Math.random() * 10); str[index] = a; if (index == 0) { seg.change(0); } else if (index != N - 1) { seg.change(index); seg.change(index - 1); } else { seg.change(N - 2); } out.println(seg.ans()); } } } class SegmentTree { long[][][] matrix; ArrayList<Integer>[] paths; ArrayList<Integer> cur = new ArrayList<>(); int N; SegmentTree(int N) { this.N = N; paths = new ArrayList[N]; for (int i = 0; i < N; i++) { paths[i] = new ArrayList<>(); } matrix = new long[4 * N][][]; } void build(int n, int tl, int tr) { cur.add(n); if (tl == tr) { matrix[n] = matrices[str[tl]][str[tl + 1]]; paths[tl] = new ArrayList<>(cur); cur.remove(cur.size() - 1); return; } int tm = (tl + tr) / 2; build(2 * n, tl, tm); build(2 * n + 1, tm + 1, tr); matrix[n] = new long[2][2]; multiply(matrix[2 * n], matrix[2 * n + 1], matrix[n]); cur.remove(cur.size() - 1); } long ans() { return (matrix[1][0][0] * (str[N] + 1) + matrix[1][0][1]) % MOD; } void change(int i) { int n = paths[i].get(paths[i].size() - 1); matrix[n] = matrices[str[i]][str[i + 1]]; for (int j = paths[i].size() - 2; j >= 0; j--) { n = paths[i].get(j); multiply(matrix[2 * n], matrix[2 * n + 1], matrix[n]); } } void multiply(long[][] a, long[][] b, long[][] res) { for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { res[i][j] = 0; for (int c = 0; c < 2; c++) { res[i][j] += a[i][c] * b[c][j]; } res[i][j] %= MOD; } } } } } 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
["2 3\n14\n2 4\n2 1\n1 0"]
5 seconds
["15\n12\n2"]
NoteAfter the first update $$$c$$$ is equal to $$$14$$$. The pairs that sum up to $$$14$$$ are: $$$(0, 14)$$$, $$$(1, 13)$$$, $$$(2, 12)$$$, $$$(3, 11)$$$, $$$(4, 10)$$$, $$$(5, 9)$$$, $$$(6, 8)$$$, $$$(7, 7)$$$, $$$(8, 6)$$$, $$$(9, 5)$$$, $$$(10, 4)$$$, $$$(11, 3)$$$, $$$(12, 2)$$$, $$$(13, 1)$$$, $$$(14, 0)$$$.After the second update $$$c$$$ is equal to $$$11$$$.After the third update $$$c$$$ is equal to $$$01$$$.
Java 8
standard input
[ "dp", "data structures", "matrices" ]
d3baf23c53ba50a03f5ef63d58d177cb
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^5$$$) — the length of the number $$$c$$$ and the number of updates. The second line contains a string $$$c$$$, consisting of exactly $$$n$$$ digits from $$$0$$$ to $$$9$$$. Each of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$d$$$ ($$$1 \le x \le n$$$, $$$0 \le d \le 9$$$) — the descriptions of updates.
2,600
Print $$$m$$$ integers — the $$$i$$$-th value should be equal to the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$ after $$$i$$$ updates are applied. Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
standard output
PASSED
988aaad7403eeae20b82f4de5972a553
train_002.jsonl
1594565100
Let $$$a$$$ and $$$b$$$ be some non-negative integers. Let's define strange addition of $$$a$$$ and $$$b$$$ as following: write down the numbers one under another and align them by their least significant digit; add them up digit by digit and concatenate the respective sums together. Assume that both numbers have an infinite number of leading zeros.For example, let's take a look at a strange addition of numbers $$$3248$$$ and $$$908$$$: You are given a string $$$c$$$, consisting of $$$n$$$ digits from $$$0$$$ to $$$9$$$. You are also given $$$m$$$ updates of form: $$$x~d$$$ — replace the digit at the $$$x$$$-th position of $$$c$$$ with a digit $$$d$$$. Note that string $$$c$$$ might have leading zeros at any point of time.After each update print the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$.Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main{ static int mod=998244353; static int pairs(int d) { return d+1; } static int pairs(int d1,int d2) { if(d1==0)return 0; int x=d1*10+d2; int lower=x-9; return Math.max(0, 9-lower+1); } static class segmentTree{ long[]dpLR,dpLr,dplR,dplr;//capital letter means included , small letter means not included int[]arr; int N; public segmentTree(int[]in) { N=in.length-1; arr=in; dpLR=new long[N<<2]; dpLr=new long[N<<2]; dplR=new long[N<<2]; dplr=new long[N<<2]; build(1,1,N); } void build(int node,int left,int right) { if(left==right) { dpLr[node]=dplR[node]=dplr[node]=1; dpLR[node]=pairs(arr[left]); return; } int mid=(left+right)>>1; int leftChild=node<<1,rightChild=node<<1|1; build(leftChild, left, mid); build(rightChild, mid+1, right); long merge=pairs(arr[mid], arr[mid+1]); int lenLeft=mid-left+1,lenRight=right-mid; // if(node==1) { // System.out.println(node); // System.out.println(dpLR[leftChild]+" "+dplR[leftChild]+" "+dpLr[leftChild]+" "+dplr[leftChild]); // System.out.println(dpLR[rightChild]+" "+dplR[rightChild]+" "+dpLr[rightChild]+" "+dplr[rightChild]); // System.out.println(); // } dpLR[node]=((dpLR[leftChild]*dpLR[rightChild])%mod + (merge*dpLr[leftChild]*dplR[rightChild])%mod)%mod; dplR[node]=((dplR[leftChild]*dpLR[rightChild])%mod + (lenLeft==1?0:(merge*dplr[leftChild]*dplR[rightChild]))%mod)%mod; dpLr[node]=((dpLR[leftChild]*dpLr[rightChild])%mod + (lenRight==1?0:(merge*dpLr[leftChild]*dplr[rightChild]))%mod)%mod; dplr[node]=((dplR[leftChild]*dpLr[rightChild])%mod + ((lenLeft==1 || lenRight==1)?0:(merge*dplr[leftChild]*dplr[rightChild]))%mod)%mod; } void updatePoint(int idx,int val) { updatePoint(1, 1, N, idx, val); } void updatePoint(int node,int curLeft,int curRight,int idx,int val) { if(curLeft==curRight) { arr[idx]=val; dpLr[node]=dplR[node]=dplr[node]=1; dpLR[node]=pairs(arr[idx]); return; } int mid=(curLeft+curRight)>>1; int leftChild=node<<1,rightChild=node<<1|1; if(idx<=mid) { updatePoint(leftChild, curLeft, mid, idx, val); } else { updatePoint(rightChild, mid+1, curRight, idx, val); } long merge=pairs(arr[mid], arr[mid+1]); int lenLeft=mid-curLeft+1,lenRight=curRight-mid; dpLR[node]=((dpLR[leftChild]*dpLR[rightChild])%mod + (merge*dpLr[leftChild]*dplR[rightChild])%mod)%mod; dplR[node]=((dplR[leftChild]*dpLR[rightChild])%mod + (lenLeft==1?0:(merge*dplr[leftChild]*dplR[rightChild]))%mod)%mod; dpLr[node]=((dpLR[leftChild]*dpLr[rightChild])%mod + (lenRight==1?0:(merge*dpLr[leftChild]*dplr[rightChild]))%mod)%mod; dplr[node]=((dplR[leftChild]*dpLr[rightChild])%mod + ((lenLeft==1 || lenRight==1)?0:(merge*dplr[leftChild]*dplr[rightChild]))%mod)%mod; } } static void main() throws Exception{ int n=sc.nextInt(),m=sc.nextInt(); int[]in=new int[n+1]; String s=sc.nextLine(); for(int i=1;i<=n;i++)in[i]=(s.charAt(i-1)-'0'); segmentTree st=new segmentTree(in); // pw.println(st.dpLR[1]); while(m-->0) { st.updatePoint(sc.nextInt(), sc.nextInt()); pw.println(st.dpLR[1]); } } public static void main(String[] args) throws Exception{ sc=new MScanner(System.in); pw = new PrintWriter(System.out); int tc=1; // tc=sc.nextInt(); while(tc-->0) main(); pw.flush(); } static PrintWriter pw; static MScanner sc; static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] intArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public long[] longArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public int[] intSortedArr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); shuffle(in); Arrays.sort(in); return in; } public long[] longSortedArr(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); shuffle(in); Arrays.sort(in); return in; } public Integer[] IntegerArr(int n) throws IOException { Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=Integer.valueOf(nextInt()); return in; } public Long[] LongArr(int n) throws IOException { Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=Long.valueOf(nextLong()); return in; } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } static void shuffle(int[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); int tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } static void shuffle(long[]in) { for(int i=0;i<in.length;i++) { int idx=(int)(Math.random()*in.length); long tmp=in[i]; in[i]=in[idx]; in[idx]=tmp; } } }
Java
["2 3\n14\n2 4\n2 1\n1 0"]
5 seconds
["15\n12\n2"]
NoteAfter the first update $$$c$$$ is equal to $$$14$$$. The pairs that sum up to $$$14$$$ are: $$$(0, 14)$$$, $$$(1, 13)$$$, $$$(2, 12)$$$, $$$(3, 11)$$$, $$$(4, 10)$$$, $$$(5, 9)$$$, $$$(6, 8)$$$, $$$(7, 7)$$$, $$$(8, 6)$$$, $$$(9, 5)$$$, $$$(10, 4)$$$, $$$(11, 3)$$$, $$$(12, 2)$$$, $$$(13, 1)$$$, $$$(14, 0)$$$.After the second update $$$c$$$ is equal to $$$11$$$.After the third update $$$c$$$ is equal to $$$01$$$.
Java 8
standard input
[ "dp", "data structures", "matrices" ]
d3baf23c53ba50a03f5ef63d58d177cb
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^5$$$) — the length of the number $$$c$$$ and the number of updates. The second line contains a string $$$c$$$, consisting of exactly $$$n$$$ digits from $$$0$$$ to $$$9$$$. Each of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$d$$$ ($$$1 \le x \le n$$$, $$$0 \le d \le 9$$$) — the descriptions of updates.
2,600
Print $$$m$$$ integers — the $$$i$$$-th value should be equal to the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$ after $$$i$$$ updates are applied. Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
standard output
PASSED
ebf576fae8b6aa8f3137d1b4f91c1562
train_002.jsonl
1594565100
Let $$$a$$$ and $$$b$$$ be some non-negative integers. Let's define strange addition of $$$a$$$ and $$$b$$$ as following: write down the numbers one under another and align them by their least significant digit; add them up digit by digit and concatenate the respective sums together. Assume that both numbers have an infinite number of leading zeros.For example, let's take a look at a strange addition of numbers $$$3248$$$ and $$$908$$$: You are given a string $$$c$$$, consisting of $$$n$$$ digits from $$$0$$$ to $$$9$$$. You are also given $$$m$$$ updates of form: $$$x~d$$$ — replace the digit at the $$$x$$$-th position of $$$c$$$ with a digit $$$d$$$. Note that string $$$c$$$ might have leading zeros at any point of time.After each update print the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$.Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
256 megabytes
import java.io.*; import java.util.*; public class Main extends PrintWriter { void pre() { dp = new long[Math.max(n, 2)+1][10]; for(int d = 0; d < 10; d++) { dp[1][d] = (d+1); dp[2][d] = (d+1)*2L + (10-(d+1))*1L; } for(int i = 3; i <= n; i++) { for(int d = 0; d < 10; d++) { dp[i][d] = ((9-d) * dp[i-2][1] + (d+1) * dp[i-1][1]) % M; } } } long M = 998244353L; long[][] dp; private void solve() { n = sc.nextInt(); int m = sc.nextInt(); pre(); String c_ = sc.nextString(); c = new int[n]; for(int i = 0; i < n; i++) c[i] = c_.charAt(i)-'0'; intervals = new TreeSet<>(Comparator.comparing(arr -> arr[0])); ans = 1L; for(int i = 0; i < n;) { int j = i; while(j < n && c[j] == 1) { j++; } if(j == n) j--; long cur = dp[j-i+1][c[j]]; ans = (ans * cur) % M; intervals.add(new long[] {i, j++, cur}); i = j; } for(int q = 0; q < m; q++) { int x = sc.nextInt()-1; int d = sc.nextInt(); c[x] = d; if(d != 1) { long[] interval = intervals.floor(new long[] {x}); remove(interval); int l = (int)interval[0]; int r = (int)interval[1]; if(x == r) { interval[2] = dp[r-l+1][d]; insert(interval); } else if(x < r){ insert(new long[] {l, x, dp[x-l+1][d]}); insert(new long[] {x+1, r, dp[r-x][c[r]]}); } } else { long[] interval = intervals.floor(new long[] {x}); remove(interval); if(x == interval[1]) { long[] next = intervals.higher(new long[] {x}); if(next != null) { interval[1] = next[1]; remove(next); } int l = (int)interval[0]; int r = (int)interval[1]; int len = r-l+1; interval[2] = dp[len][c[r]]; insert(interval); } else { insert(interval); } } println(ans); } } TreeSet<long[]> intervals; long ans; void insert(long[] interval) { ans = (ans * interval[2]) % M ; intervals.add(interval); } void remove(long[] interval) { ans = (ans * inv(interval[2])) % M ; intervals.remove(interval); } int n; int[] c; long inv(long a) { long i = M, v = 0, d = 1; while (a>0) { long t = i/a, x = a; a = i % x; i = x; x = d; d = v - t*x; v = x; } v %= M; if (v<0) v += M; return v; } private void test() { int cnt = 0; for(int a = 0; a < 10000; a++) { for(int b = 0; b < 10000; b++) { String x = add(String.valueOf(a), String.valueOf(b)); if(x.equals("1114")) { cnt++; } } } println(cnt); } String add(String a, String b) { StringBuilder c = new StringBuilder(); a = new StringBuilder(a).reverse().toString(); b = new StringBuilder(b).reverse().toString(); int i = 0; while(true) { int res = (i<a.length()?a.charAt(i)-'0':0) + (i<b.length()?b.charAt(i)-'0':0); if(i >= a.length() && i >= b.length()) break; c.append(new StringBuilder(String.valueOf(res)).reverse()); i++; } return c.reverse().toString(); } // Solution() throws FileNotFoundException { super(new File("output.txt")); } // InputReader sc = new InputReader(new FileInputStream("test_input.txt")); Main() { super(System.out); } InputReader sc = new InputReader(System.in); static class InputReader { InputReader(InputStream in) { this.in = in; } InputStream in; private byte[] buf = new byte[16384]; private int curChar; private int numChars; public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } public static void main(String[] $) { new Thread(null, new Runnable() { public void run() { long start = System.nanoTime(); try {Main solution = new Main(); solution.solve(); solution.close();} catch (Exception e) {e.printStackTrace(); System.exit(1);} System.err.println((System.nanoTime()-start)/1E9); } }, "1", 1 << 27).start(); } }
Java
["2 3\n14\n2 4\n2 1\n1 0"]
5 seconds
["15\n12\n2"]
NoteAfter the first update $$$c$$$ is equal to $$$14$$$. The pairs that sum up to $$$14$$$ are: $$$(0, 14)$$$, $$$(1, 13)$$$, $$$(2, 12)$$$, $$$(3, 11)$$$, $$$(4, 10)$$$, $$$(5, 9)$$$, $$$(6, 8)$$$, $$$(7, 7)$$$, $$$(8, 6)$$$, $$$(9, 5)$$$, $$$(10, 4)$$$, $$$(11, 3)$$$, $$$(12, 2)$$$, $$$(13, 1)$$$, $$$(14, 0)$$$.After the second update $$$c$$$ is equal to $$$11$$$.After the third update $$$c$$$ is equal to $$$01$$$.
Java 8
standard input
[ "dp", "data structures", "matrices" ]
d3baf23c53ba50a03f5ef63d58d177cb
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^5$$$) — the length of the number $$$c$$$ and the number of updates. The second line contains a string $$$c$$$, consisting of exactly $$$n$$$ digits from $$$0$$$ to $$$9$$$. Each of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$d$$$ ($$$1 \le x \le n$$$, $$$0 \le d \le 9$$$) — the descriptions of updates.
2,600
Print $$$m$$$ integers — the $$$i$$$-th value should be equal to the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$ after $$$i$$$ updates are applied. Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
standard output
PASSED
e3dadbd3e720b73d7819d7e972f4643c
train_002.jsonl
1594565100
Let $$$a$$$ and $$$b$$$ be some non-negative integers. Let's define strange addition of $$$a$$$ and $$$b$$$ as following: write down the numbers one under another and align them by their least significant digit; add them up digit by digit and concatenate the respective sums together. Assume that both numbers have an infinite number of leading zeros.For example, let's take a look at a strange addition of numbers $$$3248$$$ and $$$908$$$: You are given a string $$$c$$$, consisting of $$$n$$$ digits from $$$0$$$ to $$$9$$$. You are also given $$$m$$$ updates of form: $$$x~d$$$ — replace the digit at the $$$x$$$-th position of $$$c$$$ with a digit $$$d$$$. Note that string $$$c$$$ might have leading zeros at any point of time.After each update print the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$.Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
256 megabytes
import java.util.*; import java.io.*; public class F { public static long MOD = 998244353; public static long[] inv; public static void main(String[] args) throws IOException{ BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); StringTokenizer st = new StringTokenizer(f.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); inv = new long[201]; for(long i = 1; i < 201; i++) inv[(int)i] = pow(i, MOD-2, MOD); SegmentTree segtree = new SegmentTree(0, n-1); String str = f.readLine(); for(int i = 0; i < n; i++){ segtree.update(i, (int)(str.charAt(i)-'0')); } for(int i = 0; i < m; i++){ st = new StringTokenizer(f.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); segtree.update(a-1, b); out.println(segtree.val[1]); } out.close(); } public static long pow(long a, long b, long p){ long res = 1L; a%=p; while(b > 0){ if((b & 1) == 1){ res = (res*a) % p; } b/=2; a = (a*a)%p; } return res; } static class SegmentTree { //range query, non lazy final long[] val; final long[] valRemFirst; final long[] valRemLast; final long[] valRemFirstAndLast; final int[] digits; final int treeFrom; final int length; final int n; public SegmentTree(int treeFrom, int treeTo) { this.treeFrom = treeFrom; int length = treeTo - treeFrom + 1; this.n=length; int l; digits = new int[length]; for (l = 0; (1 << l) < length; l++); val = new long[1 << (l + 1)]; Arrays.fill(val, 1); valRemFirst = new long[1 << (l + 1)]; Arrays.fill(valRemFirst, 1); valRemLast = new long[1 << (l + 1)]; Arrays.fill(valRemLast, 1); valRemFirstAndLast = new long[1 << (l + 1)]; Arrays.fill(valRemFirstAndLast, 1); this.length = 1 << l; } public void update(int index, int digit) { digits[index] = digit; recur(index, 1, 0, n-1, digit); } public void recur(int i, int idx, int l, int r, int digit){ if(l == r){ val[idx] = digit+1; valRemFirstAndLast[idx] = 1; valRemFirst[idx] = 1; valRemLast[idx] = 1; return; } int mid = (r+l)/2; int left = 2*idx; int right = 2*idx+1; if(i <= mid){ recur(i, left, l, mid, digit); }else{ recur(i, right, mid+1, r, digit); } //custom segment trees are cancer cancer cancer cancer //fill this in with the combine operation later val[idx] = (val[left]*val[right])%MOD; valRemLast[idx] = (val[left]*valRemLast[right])%MOD; valRemFirst[idx] = (valRemFirst[left]*val[right])%MOD; valRemFirstAndLast[idx] = (valRemFirst[left]*valRemLast[right])%MOD; if(digits[mid] == 1){ val[idx] += (((valRemLast[left]*valRemFirst[right])%MOD)*(9-digits[mid+1]))%MOD; val[idx]%=MOD; if(r != mid+1){ valRemLast[idx] += (((valRemLast[left]*valRemFirstAndLast[right])%MOD)*(9-digits[mid+1]))%MOD; valRemLast[idx]%=MOD; } if(l != mid){ valRemFirst[idx] += (((valRemFirstAndLast[left]*valRemFirst[right])%MOD)*(9-digits[mid+1]))%MOD; valRemFirst[idx]%=MOD; } if(r != mid+1 && l != mid){ valRemFirstAndLast[idx] += (((valRemFirstAndLast[left]*valRemFirstAndLast[right])%MOD)*(9-digits[mid+1]))%MOD; valRemFirstAndLast[idx]%=MOD; } } } } }
Java
["2 3\n14\n2 4\n2 1\n1 0"]
5 seconds
["15\n12\n2"]
NoteAfter the first update $$$c$$$ is equal to $$$14$$$. The pairs that sum up to $$$14$$$ are: $$$(0, 14)$$$, $$$(1, 13)$$$, $$$(2, 12)$$$, $$$(3, 11)$$$, $$$(4, 10)$$$, $$$(5, 9)$$$, $$$(6, 8)$$$, $$$(7, 7)$$$, $$$(8, 6)$$$, $$$(9, 5)$$$, $$$(10, 4)$$$, $$$(11, 3)$$$, $$$(12, 2)$$$, $$$(13, 1)$$$, $$$(14, 0)$$$.After the second update $$$c$$$ is equal to $$$11$$$.After the third update $$$c$$$ is equal to $$$01$$$.
Java 8
standard input
[ "dp", "data structures", "matrices" ]
d3baf23c53ba50a03f5ef63d58d177cb
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^5$$$) — the length of the number $$$c$$$ and the number of updates. The second line contains a string $$$c$$$, consisting of exactly $$$n$$$ digits from $$$0$$$ to $$$9$$$. Each of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$d$$$ ($$$1 \le x \le n$$$, $$$0 \le d \le 9$$$) — the descriptions of updates.
2,600
Print $$$m$$$ integers — the $$$i$$$-th value should be equal to the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$ after $$$i$$$ updates are applied. Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
standard output
PASSED
c9190736b5cb6915fe1a3f8b5f2e04e6
train_002.jsonl
1594565100
Let $$$a$$$ and $$$b$$$ be some non-negative integers. Let's define strange addition of $$$a$$$ and $$$b$$$ as following: write down the numbers one under another and align them by their least significant digit; add them up digit by digit and concatenate the respective sums together. Assume that both numbers have an infinite number of leading zeros.For example, let's take a look at a strange addition of numbers $$$3248$$$ and $$$908$$$: You are given a string $$$c$$$, consisting of $$$n$$$ digits from $$$0$$$ to $$$9$$$. You are also given $$$m$$$ updates of form: $$$x~d$$$ — replace the digit at the $$$x$$$-th position of $$$c$$$ with a digit $$$d$$$. Note that string $$$c$$$ might have leading zeros at any point of time.After each update print the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$.Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.util.TreeSet; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author AnandOza */ 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); FStrangeAddition solver = new FStrangeAddition(); solver.solve(1, in, out); out.close(); } static class FStrangeAddition { private static final NumberTheory.Mod998 mod = new NumberTheory.Mod998(); long[] ones; int[] s; private long computeForBlock(Pii block) { int i = block.first, j = block.second; int count = j - i - 1; long r = mod.mult(ones[count], s[j - 1] + 1); if (count > 0) r = mod.add(r, mod.mult(9 - s[j - 1], ones[count - 1])); return r; } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(), m = in.nextInt(); char[] input = in.next().toCharArray(); s = new int[n]; for (int i = 0; i < n; i++) { s[i] = input[i] - '0'; } ones = new long[n + 1]; ones[0] = 1; ones[1] = 2; for (int i = 2; i <= n; i++) { ones[i] = mod.add(mod.mult(8, ones[i - 2]), mod.mult(2, ones[i - 1])); } TreeSet<Pii> blocks = new TreeSet<>(); long answer = 1; for (int i = 0, l = 0; i < n; i++) { if (s[i] != 1 || i + 1 == n) { Pii block = Pii.of(l, i + 1); blocks.add(block); answer = mod.mult(answer, computeForBlock(block)); l = i + 1; } } for (int query = 0; query < m; query++) { int x = in.nextInt() - 1, d = in.nextInt(); Pii key = Pii.of(x, n); if (d != 1) { Pii block = blocks.floor(key); answer = mod.div(answer, computeForBlock(block)); s[x] = d; if (block.second == x + 1) { answer = mod.mult(answer, computeForBlock(block)); } else { Pii left = Pii.of(block.first, x + 1); Pii right = Pii.of(x + 1, block.second); blocks.remove(block); blocks.add(left); blocks.add(right); answer = mod.mult(answer, computeForBlock(left)); answer = mod.mult(answer, computeForBlock(right)); } } else { Pii block = blocks.floor(key); if (block.second == x + 1) { Pii next = blocks.higher(block); if (next != null) { Pii merged = Pii.of(block.first, next.second); blocks.remove(block); blocks.remove(next); blocks.add(merged); answer = mod.div(answer, computeForBlock(block)); answer = mod.div(answer, computeForBlock(next)); answer = mod.mult(answer, computeForBlock(merged)); } else { answer = mod.div(answer, computeForBlock(block)); s[x] = d; answer = mod.mult(answer, computeForBlock(block)); } } s[x] = d; } out.println(answer); } } } static class Pii implements Comparable<Pii> { public final int first; public final int second; public Pii(int first, int second) { this.first = first; this.second = second; } public static Pii of(int first, int second) { return new Pii(first, second); } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pii pair = (Pii) o; return first == pair.first && second == pair.second; } public int hashCode() { return Arrays.hashCode(new int[]{first, second}); } public String toString() { return "(" + first + ", " + second + ')'; } public int compareTo(Pii o) { if (first != o.first) return Integer.compare(first, o.first); return Integer.compare(second, o.second); } } static class InputReader { public final 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()); } } static class NumberTheory { private static void ASSERT(boolean assertion) { if (!assertion) throw new AssertionError(); } public abstract static class Modulus<M extends NumberTheory.Modulus<M>> { final ArrayList<Long> factorial = new ArrayList<>(); final ArrayList<Long> invFactorial = new ArrayList<>(); public abstract long modulus(); public Modulus() { super(); factorial.add(1L); invFactorial.add(1L); } public long normalize(long x) { x %= modulus(); if (x < 0) x += modulus(); return x; } public long add(long a, long b) { long v = a + b; return v < modulus() ? v : v - modulus(); } public long mult(long a, long b) { return (a * b) % modulus(); } public long div(long a, long b) { return mult(a, inv(b)); } public long inv(long value) { long g = modulus(), x = 0, y = 1; for (long r = value; r != 0; ) { long q = g / r; g %= r; long temp = g; g = r; r = temp; x -= q * y; temp = x; x = y; y = temp; } ASSERT(g == 1); ASSERT(y == modulus() || y == -modulus()); return normalize(x); } } public static class Mod998 extends NumberTheory.Modulus<NumberTheory.Mod998> { public long modulus() { return 998_244_353L; } } } }
Java
["2 3\n14\n2 4\n2 1\n1 0"]
5 seconds
["15\n12\n2"]
NoteAfter the first update $$$c$$$ is equal to $$$14$$$. The pairs that sum up to $$$14$$$ are: $$$(0, 14)$$$, $$$(1, 13)$$$, $$$(2, 12)$$$, $$$(3, 11)$$$, $$$(4, 10)$$$, $$$(5, 9)$$$, $$$(6, 8)$$$, $$$(7, 7)$$$, $$$(8, 6)$$$, $$$(9, 5)$$$, $$$(10, 4)$$$, $$$(11, 3)$$$, $$$(12, 2)$$$, $$$(13, 1)$$$, $$$(14, 0)$$$.After the second update $$$c$$$ is equal to $$$11$$$.After the third update $$$c$$$ is equal to $$$01$$$.
Java 8
standard input
[ "dp", "data structures", "matrices" ]
d3baf23c53ba50a03f5ef63d58d177cb
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^5$$$) — the length of the number $$$c$$$ and the number of updates. The second line contains a string $$$c$$$, consisting of exactly $$$n$$$ digits from $$$0$$$ to $$$9$$$. Each of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$d$$$ ($$$1 \le x \le n$$$, $$$0 \le d \le 9$$$) — the descriptions of updates.
2,600
Print $$$m$$$ integers — the $$$i$$$-th value should be equal to the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$ after $$$i$$$ updates are applied. Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
standard output
PASSED
61077b259b45c61dd0539f5df2d0aaf7
train_002.jsonl
1594565100
Let $$$a$$$ and $$$b$$$ be some non-negative integers. Let's define strange addition of $$$a$$$ and $$$b$$$ as following: write down the numbers one under another and align them by their least significant digit; add them up digit by digit and concatenate the respective sums together. Assume that both numbers have an infinite number of leading zeros.For example, let's take a look at a strange addition of numbers $$$3248$$$ and $$$908$$$: You are given a string $$$c$$$, consisting of $$$n$$$ digits from $$$0$$$ to $$$9$$$. You are also given $$$m$$$ updates of form: $$$x~d$$$ — replace the digit at the $$$x$$$-th position of $$$c$$$ with a digit $$$d$$$. Note that string $$$c$$$ might have leading zeros at any point of time.After each update print the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$.Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.util.TreeSet; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.function.ToLongFunction; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author AnandOza */ 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); FStrangeAddition solver = new FStrangeAddition(); solver.solve(1, in, out); out.close(); } static class FStrangeAddition { private static final NumberTheory.Mod998 mod = new NumberTheory.Mod998(); public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(), m = in.nextInt(); char[] input = in.next().toCharArray(); int[] s = new int[n]; for (int i = 0; i < n; i++) { s[i] = input[i] - '0'; } long[] ones = new long[n + 1]; ones[0] = 1; ones[1] = 2; for (int i = 2; i <= n; i++) { ones[i] = mod.add(mod.mult(8, ones[i - 2]), mod.mult(2, ones[i - 1])); } ToLongFunction<Pii> computeForBlock = (Pii block) -> { int i = block.first, j = block.second; int count = j - i - 1; long r = mod.mult(ones[count], s[j - 1] + 1); if (count > 0) r = mod.add(r, mod.mult(9 - s[j - 1], ones[count - 1])); return r; }; TreeSet<Pii> blocks = new TreeSet<>(); long answer = 1; for (int i = 0, l = 0; i < n; i++) { if (s[i] != 1 || i + 1 == n) { Pii block = Pii.of(l, i + 1); blocks.add(block); answer = mod.mult(answer, computeForBlock.applyAsLong(block)); l = i + 1; } } for (int query = 0; query < m; query++) { int x = in.nextInt() - 1, d = in.nextInt(); Pii key = Pii.of(x, n); if (d != 1) { Pii block = blocks.floor(key); answer = mod.div(answer, computeForBlock.applyAsLong(block)); s[x] = d; if (block.second == x + 1) { answer = mod.mult(answer, computeForBlock.applyAsLong(block)); } else { Pii left = Pii.of(block.first, x + 1); Pii right = Pii.of(x + 1, block.second); blocks.remove(block); blocks.add(left); blocks.add(right); answer = mod.mult(answer, computeForBlock.applyAsLong(left)); answer = mod.mult(answer, computeForBlock.applyAsLong(right)); } } else { Pii block = blocks.floor(key); if (block.second == x + 1) { Pii next = blocks.higher(block); if (next != null) { Pii merged = Pii.of(block.first, next.second); blocks.remove(block); blocks.remove(next); blocks.add(merged); answer = mod.div(answer, computeForBlock.applyAsLong(block)); answer = mod.div(answer, computeForBlock.applyAsLong(next)); answer = mod.mult(answer, computeForBlock.applyAsLong(merged)); } else { answer = mod.div(answer, computeForBlock.applyAsLong(block)); s[x] = d; answer = mod.mult(answer, computeForBlock.applyAsLong(block)); } } s[x] = d; } out.println(answer); } } } static class Pii implements Comparable<Pii> { public final int first; public final int second; public Pii(int first, int second) { this.first = first; this.second = second; } public static Pii of(int first, int second) { return new Pii(first, second); } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pii pair = (Pii) o; return first == pair.first && second == pair.second; } public int hashCode() { return Arrays.hashCode(new int[]{first, second}); } public String toString() { return "(" + first + ", " + second + ')'; } public int compareTo(Pii o) { if (first != o.first) return Integer.compare(first, o.first); return Integer.compare(second, o.second); } } static class InputReader { public final 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()); } } static class NumberTheory { private static void ASSERT(boolean assertion) { if (!assertion) throw new AssertionError(); } public abstract static class Modulus<M extends NumberTheory.Modulus<M>> { final ArrayList<Long> factorial = new ArrayList<>(); final ArrayList<Long> invFactorial = new ArrayList<>(); public abstract long modulus(); public Modulus() { super(); factorial.add(1L); invFactorial.add(1L); } public long normalize(long x) { x %= modulus(); if (x < 0) x += modulus(); return x; } public long add(long a, long b) { long v = a + b; return v < modulus() ? v : v - modulus(); } public long mult(long a, long b) { return (a * b) % modulus(); } public long div(long a, long b) { return mult(a, inv(b)); } public long inv(long value) { long g = modulus(), x = 0, y = 1; for (long r = value; r != 0; ) { long q = g / r; g %= r; long temp = g; g = r; r = temp; x -= q * y; temp = x; x = y; y = temp; } ASSERT(g == 1); ASSERT(y == modulus() || y == -modulus()); return normalize(x); } } public static class Mod998 extends NumberTheory.Modulus<NumberTheory.Mod998> { public long modulus() { return 998_244_353L; } } } }
Java
["2 3\n14\n2 4\n2 1\n1 0"]
5 seconds
["15\n12\n2"]
NoteAfter the first update $$$c$$$ is equal to $$$14$$$. The pairs that sum up to $$$14$$$ are: $$$(0, 14)$$$, $$$(1, 13)$$$, $$$(2, 12)$$$, $$$(3, 11)$$$, $$$(4, 10)$$$, $$$(5, 9)$$$, $$$(6, 8)$$$, $$$(7, 7)$$$, $$$(8, 6)$$$, $$$(9, 5)$$$, $$$(10, 4)$$$, $$$(11, 3)$$$, $$$(12, 2)$$$, $$$(13, 1)$$$, $$$(14, 0)$$$.After the second update $$$c$$$ is equal to $$$11$$$.After the third update $$$c$$$ is equal to $$$01$$$.
Java 8
standard input
[ "dp", "data structures", "matrices" ]
d3baf23c53ba50a03f5ef63d58d177cb
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^5$$$) — the length of the number $$$c$$$ and the number of updates. The second line contains a string $$$c$$$, consisting of exactly $$$n$$$ digits from $$$0$$$ to $$$9$$$. Each of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$d$$$ ($$$1 \le x \le n$$$, $$$0 \le d \le 9$$$) — the descriptions of updates.
2,600
Print $$$m$$$ integers — the $$$i$$$-th value should be equal to the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$ after $$$i$$$ updates are applied. Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
standard output
PASSED
18483eca85a713cdb897abfb3bf76295
train_002.jsonl
1594565100
Let $$$a$$$ and $$$b$$$ be some non-negative integers. Let's define strange addition of $$$a$$$ and $$$b$$$ as following: write down the numbers one under another and align them by their least significant digit; add them up digit by digit and concatenate the respective sums together. Assume that both numbers have an infinite number of leading zeros.For example, let's take a look at a strange addition of numbers $$$3248$$$ and $$$908$$$: You are given a string $$$c$$$, consisting of $$$n$$$ digits from $$$0$$$ to $$$9$$$. You are also given $$$m$$$ updates of form: $$$x~d$$$ — replace the digit at the $$$x$$$-th position of $$$c$$$ with a digit $$$d$$$. Note that string $$$c$$$ might have leading zeros at any point of time.After each update print the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$.Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
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.function.IntBinaryOperator; import java.io.IOException; import java.io.InputStreamReader; import java.util.TreeSet; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author AnandOza */ 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); FStrangeAddition solver = new FStrangeAddition(); solver.solve(1, in, out); out.close(); } static class FStrangeAddition { private static final NumberTheory.Mod998 mod = new NumberTheory.Mod998(); public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(), m = in.nextInt(); char[] input = in.next().toCharArray(); int[] s = new int[n]; for (int i = 0; i < n; i++) { s[i] = input[i] - '0'; } long[] ones = new long[n + 1]; ones[0] = 1; ones[1] = 2; for (int i = 2; i <= n; i++) { ones[i] = mod.add(mod.mult(8, ones[i - 2]), mod.mult(2, ones[i - 1])); } IntBinaryOperator computeForBlock = (i, j) -> { int count = j - i - 1; long r = mod.mult(ones[count], s[j - 1] + 1); if (count > 0) r = mod.add(r, mod.mult(9 - s[j - 1], ones[count - 1])); return (int) r; }; TreeSet<Pii> blocks = new TreeSet<>(); long answer = 1; for (int i = 0, l = 0; i < n; i++) { if (s[i] != 1 || i + 1 == n) { blocks.add(Pii.of(l, i + 1)); answer = mod.mult(answer, computeForBlock.applyAsInt(l, i + 1)); l = i + 1; } } for (int query = 0; query < m; query++) { int x = in.nextInt() - 1, d = in.nextInt(); Pii key = Pii.of(x, n); if (d != 1) { Pii block = blocks.floor(key); answer = mod.div(answer, computeForBlock.applyAsInt(block.first, block.second)); s[x] = d; if (block.second == x + 1) { answer = mod.mult(answer, computeForBlock.applyAsInt(block.first, block.second)); } else { Pii left = Pii.of(block.first, x + 1); Pii right = Pii.of(x + 1, block.second); blocks.remove(block); blocks.add(left); blocks.add(right); answer = mod.mult(answer, computeForBlock.applyAsInt(left.first, left.second)); answer = mod.mult(answer, computeForBlock.applyAsInt(right.first, right.second)); } } else { Pii block = blocks.floor(key); if (block.second == x + 1) { Pii next = blocks.higher(block); if (next != null) { Pii merged = Pii.of(block.first, next.second); blocks.remove(block); blocks.remove(next); blocks.add(merged); answer = mod.div(answer, computeForBlock.applyAsInt(block.first, block.second)); answer = mod.div(answer, computeForBlock.applyAsInt(next.first, next.second)); answer = mod.mult(answer, computeForBlock.applyAsInt(merged.first, merged.second)); } else { answer = mod.div(answer, computeForBlock.applyAsInt(block.first, block.second)); s[x] = d; answer = mod.mult(answer, computeForBlock.applyAsInt(block.first, block.second)); } } s[x] = d; } out.println(answer); } } } static class Pii implements Comparable<Pii> { public final int first; public final int second; public Pii(int first, int second) { this.first = first; this.second = second; } public static Pii of(int first, int second) { return new Pii(first, second); } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pii pair = (Pii) o; return first == pair.first && second == pair.second; } public int hashCode() { return Arrays.hashCode(new int[]{first, second}); } public String toString() { return "(" + first + ", " + second + ')'; } public int compareTo(Pii o) { if (first != o.first) return Integer.compare(first, o.first); return Integer.compare(second, o.second); } } static class InputReader { public final 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()); } } static class NumberTheory { private static void ASSERT(boolean assertion) { if (!assertion) throw new AssertionError(); } public abstract static class Modulus<M extends NumberTheory.Modulus<M>> { final ArrayList<Long> factorial = new ArrayList<>(); final ArrayList<Long> invFactorial = new ArrayList<>(); public abstract long modulus(); public Modulus() { super(); factorial.add(1L); invFactorial.add(1L); } public long normalize(long x) { x %= modulus(); if (x < 0) x += modulus(); return x; } public long add(long a, long b) { long v = a + b; return v < modulus() ? v : v - modulus(); } public long mult(long a, long b) { return (a * b) % modulus(); } public long div(long a, long b) { return mult(a, inv(b)); } public long inv(long value) { long g = modulus(), x = 0, y = 1; for (long r = value; r != 0; ) { long q = g / r; g %= r; long temp = g; g = r; r = temp; x -= q * y; temp = x; x = y; y = temp; } ASSERT(g == 1); ASSERT(y == modulus() || y == -modulus()); return normalize(x); } } public static class Mod998 extends NumberTheory.Modulus<NumberTheory.Mod998> { public long modulus() { return 998_244_353L; } } } }
Java
["2 3\n14\n2 4\n2 1\n1 0"]
5 seconds
["15\n12\n2"]
NoteAfter the first update $$$c$$$ is equal to $$$14$$$. The pairs that sum up to $$$14$$$ are: $$$(0, 14)$$$, $$$(1, 13)$$$, $$$(2, 12)$$$, $$$(3, 11)$$$, $$$(4, 10)$$$, $$$(5, 9)$$$, $$$(6, 8)$$$, $$$(7, 7)$$$, $$$(8, 6)$$$, $$$(9, 5)$$$, $$$(10, 4)$$$, $$$(11, 3)$$$, $$$(12, 2)$$$, $$$(13, 1)$$$, $$$(14, 0)$$$.After the second update $$$c$$$ is equal to $$$11$$$.After the third update $$$c$$$ is equal to $$$01$$$.
Java 8
standard input
[ "dp", "data structures", "matrices" ]
d3baf23c53ba50a03f5ef63d58d177cb
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^5$$$) — the length of the number $$$c$$$ and the number of updates. The second line contains a string $$$c$$$, consisting of exactly $$$n$$$ digits from $$$0$$$ to $$$9$$$. Each of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$d$$$ ($$$1 \le x \le n$$$, $$$0 \le d \le 9$$$) — the descriptions of updates.
2,600
Print $$$m$$$ integers — the $$$i$$$-th value should be equal to the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$ after $$$i$$$ updates are applied. Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
standard output
PASSED
7ed168184007e76930c9bdac46f6fe6f
train_002.jsonl
1594565100
Let $$$a$$$ and $$$b$$$ be some non-negative integers. Let's define strange addition of $$$a$$$ and $$$b$$$ as following: write down the numbers one under another and align them by their least significant digit; add them up digit by digit and concatenate the respective sums together. Assume that both numbers have an infinite number of leading zeros.For example, let's take a look at a strange addition of numbers $$$3248$$$ and $$$908$$$: You are given a string $$$c$$$, consisting of $$$n$$$ digits from $$$0$$$ to $$$9$$$. You are also given $$$m$$$ updates of form: $$$x~d$$$ — replace the digit at the $$$x$$$-th position of $$$c$$$ with a digit $$$d$$$. Note that string $$$c$$$ might have leading zeros at any point of time.After each update print the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$.Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author AnandOza */ 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); FStrangeAddition solver = new FStrangeAddition(); solver.solve(1, in, out); out.close(); } static class FStrangeAddition { private static final NumberTheory.Mod998 mod = new NumberTheory.Mod998(); private static final int[] ways = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(), m = in.nextInt(); int powerOfTwo = Integer.highestOneBit(n); n = powerOfTwo == n ? n : powerOfTwo * 2; char[] c = in.next().toCharArray(); StrangeSegmentTree st = new StrangeSegmentTree(n); for (int i = 0; i < c.length; i++) { st.update_LAZY(i, c[i] - '0'); } st.rebuild(); for (int i = 0; i < m; i++) { int x = in.nextInt() - 1; int d = in.nextInt(); st.update(x, d); out.println(st.answer[1]); } } public class StrangeSegmentTree { public final int size; public final int[] left; public final int[] right; public final long[] answer; public final long[] answerExceptLeft; public final long[] answerExceptRight; public final long[] answerExceptBoth; public StrangeSegmentTree(int size) { this.size = size; left = new int[2 * size]; right = new int[2 * size]; answer = new long[2 * size]; answerExceptLeft = new long[2 * size]; answerExceptRight = new long[2 * size]; answerExceptBoth = new long[2 * size]; Arrays.fill(answer, 1); Arrays.fill(left, 99); Arrays.fill(right, 99); } public void rebuild() { for (int i = size - 1; i > 0; i--) { combine(i); } } private void combine(int i) { left[i] = left[2 * i]; right[i] = right[2 * i + 1]; int middleDigit = right[2 * i] * 10 + left[2 * i + 1]; long w = middleDigit < ways.length ? ways[middleDigit] : 0; if (right[2 * i] == 0) w = 0; answerExceptRight[i] = mod.add(mod.mult(answer[2 * i], answerExceptRight[2 * i + 1]), mod.mult(answerExceptRight[2 * i], answerExceptBoth[2 * i + 1], w)); answerExceptLeft[i] = mod.add(mod.mult(answerExceptLeft[2 * i], answer[2 * i + 1]), mod.mult(answerExceptBoth[2 * i], answerExceptLeft[2 * i + 1], w)); answerExceptBoth[i] = mod.add(mod.mult(answerExceptLeft[2 * i], answerExceptRight[2 * i + 1]), mod.mult(answerExceptBoth[2 * i], answerExceptBoth[2 * i + 1], w)); answer[i] = mod.add(mod.mult(answer[2 * i], answer[2 * i + 1]), mod.mult(answerExceptRight[2 * i], answerExceptLeft[2 * i + 1], w)); } public void update(int i, int digit) { update_LAZY(i, digit); i += size; while (i > 1) { i /= 2; combine(i); } } public void update_LAZY(int i, int digit) { i += size; left[i] = right[i] = digit; answerExceptLeft[i] = answerExceptRight[i] = 1; answerExceptBoth[i] = 0; answer[i] = ways[digit]; } } } static class InputReader { public final 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()); } } static class NumberTheory { public abstract static class Modulus<M extends NumberTheory.Modulus<M>> { final ArrayList<Long> factorial = new ArrayList<>(); final ArrayList<Long> invFactorial = new ArrayList<>(); public abstract long modulus(); public Modulus() { super(); factorial.add(1L); invFactorial.add(1L); } public long add(long a, long b) { long v = a + b; return v < modulus() ? v : v - modulus(); } public long mult(long... x) { long r = 1; for (long i : x) r = mult(r, i); return r; } public long mult(long a, long b) { return (a * b) % modulus(); } } public static class Mod998 extends NumberTheory.Modulus<NumberTheory.Mod998> { public long modulus() { return 998_244_353L; } } } }
Java
["2 3\n14\n2 4\n2 1\n1 0"]
5 seconds
["15\n12\n2"]
NoteAfter the first update $$$c$$$ is equal to $$$14$$$. The pairs that sum up to $$$14$$$ are: $$$(0, 14)$$$, $$$(1, 13)$$$, $$$(2, 12)$$$, $$$(3, 11)$$$, $$$(4, 10)$$$, $$$(5, 9)$$$, $$$(6, 8)$$$, $$$(7, 7)$$$, $$$(8, 6)$$$, $$$(9, 5)$$$, $$$(10, 4)$$$, $$$(11, 3)$$$, $$$(12, 2)$$$, $$$(13, 1)$$$, $$$(14, 0)$$$.After the second update $$$c$$$ is equal to $$$11$$$.After the third update $$$c$$$ is equal to $$$01$$$.
Java 8
standard input
[ "dp", "data structures", "matrices" ]
d3baf23c53ba50a03f5ef63d58d177cb
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^5$$$) — the length of the number $$$c$$$ and the number of updates. The second line contains a string $$$c$$$, consisting of exactly $$$n$$$ digits from $$$0$$$ to $$$9$$$. Each of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$d$$$ ($$$1 \le x \le n$$$, $$$0 \le d \le 9$$$) — the descriptions of updates.
2,600
Print $$$m$$$ integers — the $$$i$$$-th value should be equal to the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$ after $$$i$$$ updates are applied. Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
standard output
PASSED
5b11bc8dde45fe02be664a4e29de5458
train_002.jsonl
1594565100
Let $$$a$$$ and $$$b$$$ be some non-negative integers. Let's define strange addition of $$$a$$$ and $$$b$$$ as following: write down the numbers one under another and align them by their least significant digit; add them up digit by digit and concatenate the respective sums together. Assume that both numbers have an infinite number of leading zeros.For example, let's take a look at a strange addition of numbers $$$3248$$$ and $$$908$$$: You are given a string $$$c$$$, consisting of $$$n$$$ digits from $$$0$$$ to $$$9$$$. You are also given $$$m$$$ updates of form: $$$x~d$$$ — replace the digit at the $$$x$$$-th position of $$$c$$$ with a digit $$$d$$$. Note that string $$$c$$$ might have leading zeros at any point of time.After each update print the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$.Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; import java.util.function.IntFunction; /** * 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); FStrangeAddition solver = new FStrangeAddition(); solver.solve(1, in, out); out.close(); } static class FStrangeAddition { private static final NumberTheory.Mod998 mod = new NumberTheory.Mod998(); private static final int[] ways = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(), m = in.nextInt(); char[] c = in.next().toCharArray(); FastSegmentTree<FStrangeAddition.V> st = new FastSegmentTree<>(n, FStrangeAddition.V::new, true); for (int i = 0; i < c.length; i++) { st.value.create(c[i] - '0'); st.update_LAZY(i); } st.rebuild(); for (int i = 0; i < m; i++) { int x = in.nextInt() - 1; int d = in.nextInt(); st.value.create(d); st.update(x); out.println(st.value.answer[1]); } } public static final class V implements FastSegmentTree.Storage<FStrangeAddition.V> { final long[] answer; final long[] answerExceptLeft; final long[] answerExceptRight; final long[] answerExceptBoth; final int[] left; final int[] right; public V(int capacity) { answer = new long[capacity]; answerExceptLeft = new long[capacity]; answerExceptRight = new long[capacity]; answerExceptBoth = new long[capacity]; left = new int[capacity]; right = new int[capacity]; } public void clear(int i) { answer[i] = -1; } public void set(int to, int from) { left[to] = left[from]; right[to] = right[from]; answer[to] = answer[from]; answerExceptLeft[to] = answerExceptLeft[from]; answerExceptRight[to] = answerExceptRight[from]; answerExceptBoth[to] = answerExceptBoth[from]; } public void combine(int target, int l, int r) { if (answer[l] == -1) { set(target, r); return; } if (answer[r] == -1) { set(target, l); return; } left[target] = left[l]; right[target] = right[r]; int middleDigit = right[l] * 10 + left[r]; long w = middleDigit < ways.length ? ways[middleDigit] : 0; if (right[l] == 0) w = 0; answerExceptRight[target] = mod.add(mod.mult(answer[l], answerExceptRight[r]), mod.mult(answerExceptRight[l], answerExceptBoth[r], w)); answerExceptLeft[target] = mod.add(mod.mult(answerExceptLeft[l], answer[r]), mod.mult(answerExceptBoth[l], answerExceptLeft[r], w)); answerExceptBoth[target] = mod.add(mod.mult(answerExceptLeft[l], answerExceptRight[r]), mod.mult(answerExceptBoth[l], answerExceptBoth[r], w)); answer[target] = mod.add(mod.mult(answer[l], answer[r]), mod.mult(answerExceptRight[l], answerExceptLeft[r], w)); } public void create(int digit) { left[0] = right[0] = digit; answerExceptLeft[0] = answerExceptRight[0] = 1; answerExceptBoth[0] = 0; answer[0] = ways[digit]; } } } static class NumberTheory { public abstract static class Modulus<M extends NumberTheory.Modulus<M>> { final ArrayList<Long> factorial = new ArrayList<>(); final ArrayList<Long> invFactorial = new ArrayList<>(); public abstract long modulus(); public Modulus() { super(); factorial.add(1L); invFactorial.add(1L); } public long add(long a, long b) { long v = a + b; return v < modulus() ? v : v - modulus(); } public long mult(long... x) { long r = 1; for (long i : x) r = mult(r, i); return r; } public long mult(long a, long b) { return (a * b) % modulus(); } } public static class Mod998 extends NumberTheory.Modulus<NumberTheory.Mod998> { public long modulus() { return 998_244_353L; } } } static class InputReader { public final 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()); } } static class FastSegmentTree<T extends FastSegmentTree.Storage<T>> { public final int size; public final T value; public FastSegmentTree(int size, IntFunction<T> constructor) { this.size = size; value = constructor.apply(2 * size + 4); for (int i = 0; i < 2 * size + 2; i++) { value.clear(i); } } public FastSegmentTree(int size, IntFunction<T> constructor, boolean powerOfTwo) { this(powerOfTwo ? powerOfTwo(size) : size, constructor); } public void rebuild() { for (int i = size - 1; i > 0; i--) { value.combine(i, 2 * i, 2 * i + 1); } } public void update(int i) { i += size; value.set(i, 0); while (i > 1) { i /= 2; value.combine(i, 2 * i, 2 * i + 1); } } public void update_LAZY(int i) { i += size; value.set(i, 0); } private static int powerOfTwo(int n) { int powerOfTwo = Integer.highestOneBit(n); if (powerOfTwo < n) powerOfTwo *= 2; return powerOfTwo; } public interface Storage<T extends FastSegmentTree.Storage<T>> { void clear(int i); void set(int to, int from); void combine(int target, int left, int right); } } }
Java
["2 3\n14\n2 4\n2 1\n1 0"]
5 seconds
["15\n12\n2"]
NoteAfter the first update $$$c$$$ is equal to $$$14$$$. The pairs that sum up to $$$14$$$ are: $$$(0, 14)$$$, $$$(1, 13)$$$, $$$(2, 12)$$$, $$$(3, 11)$$$, $$$(4, 10)$$$, $$$(5, 9)$$$, $$$(6, 8)$$$, $$$(7, 7)$$$, $$$(8, 6)$$$, $$$(9, 5)$$$, $$$(10, 4)$$$, $$$(11, 3)$$$, $$$(12, 2)$$$, $$$(13, 1)$$$, $$$(14, 0)$$$.After the second update $$$c$$$ is equal to $$$11$$$.After the third update $$$c$$$ is equal to $$$01$$$.
Java 8
standard input
[ "dp", "data structures", "matrices" ]
d3baf23c53ba50a03f5ef63d58d177cb
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^5$$$) — the length of the number $$$c$$$ and the number of updates. The second line contains a string $$$c$$$, consisting of exactly $$$n$$$ digits from $$$0$$$ to $$$9$$$. Each of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$d$$$ ($$$1 \le x \le n$$$, $$$0 \le d \le 9$$$) — the descriptions of updates.
2,600
Print $$$m$$$ integers — the $$$i$$$-th value should be equal to the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$ after $$$i$$$ updates are applied. Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
standard output
PASSED
c619430a0123c1a70255abd9e9477820
train_002.jsonl
1594565100
Let $$$a$$$ and $$$b$$$ be some non-negative integers. Let's define strange addition of $$$a$$$ and $$$b$$$ as following: write down the numbers one under another and align them by their least significant digit; add them up digit by digit and concatenate the respective sums together. Assume that both numbers have an infinite number of leading zeros.For example, let's take a look at a strange addition of numbers $$$3248$$$ and $$$908$$$: You are given a string $$$c$$$, consisting of $$$n$$$ digits from $$$0$$$ to $$$9$$$. You are also given $$$m$$$ updates of form: $$$x~d$$$ — replace the digit at the $$$x$$$-th position of $$$c$$$ with a digit $$$d$$$. Note that string $$$c$$$ might have leading zeros at any point of time.After each update print the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$.Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.util.TreeSet; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author AnandOza */ 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); FStrangeAddition solver = new FStrangeAddition(); solver.solve(1, in, out); out.close(); } static class FStrangeAddition { private static final NumberTheory.Mod998 mod = new NumberTheory.Mod998(); long[] ones; int[] s; private long computeForBlock(int i, int j) { int count = j - i - 1; long r = mod.mult(ones[count], s[j - 1] + 1); if (count > 0) r = mod.add(r, mod.mult(9 - s[j - 1], ones[count - 1])); return r; } public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(), m = in.nextInt(); char[] input = in.next().toCharArray(); s = new int[n]; for (int i = 0; i < n; i++) { s[i] = input[i] - '0'; } ones = new long[n + 1]; ones[0] = 1; ones[1] = 2; for (int i = 2; i <= n; i++) { ones[i] = mod.add(mod.mult(8, ones[i - 2]), mod.mult(2, ones[i - 1])); } TreeSet<Pii> blocks = new TreeSet<>(); long answer = 1; for (int i = 0, l = 0; i < n; i++) { if (s[i] != 1 || i + 1 == n) { blocks.add(Pii.of(l, i + 1)); answer = mod.mult(answer, computeForBlock(l, i + 1)); l = i + 1; } } for (int query = 0; query < m; query++) { int x = in.nextInt() - 1, d = in.nextInt(); Pii key = Pii.of(x, n); if (d != 1) { Pii block = blocks.floor(key); answer = mod.div(answer, computeForBlock(block.first, block.second)); s[x] = d; if (block.second == x + 1) { answer = mod.mult(answer, computeForBlock(block.first, block.second)); } else { Pii left = Pii.of(block.first, x + 1); Pii right = Pii.of(x + 1, block.second); blocks.remove(block); blocks.add(left); blocks.add(right); answer = mod.mult(answer, computeForBlock(left.first, left.second)); answer = mod.mult(answer, computeForBlock(right.first, right.second)); } } else { Pii block = blocks.floor(key); if (block.second == x + 1) { Pii next = blocks.higher(block); if (next != null) { Pii merged = Pii.of(block.first, next.second); blocks.remove(block); blocks.remove(next); blocks.add(merged); answer = mod.div(answer, computeForBlock(block.first, block.second)); answer = mod.div(answer, computeForBlock(next.first, next.second)); answer = mod.mult(answer, computeForBlock(merged.first, merged.second)); } else { answer = mod.div(answer, computeForBlock(block.first, block.second)); s[x] = d; answer = mod.mult(answer, computeForBlock(block.first, block.second)); } } s[x] = d; } out.println(answer); } } } static class Pii implements Comparable<Pii> { public final int first; public final int second; public Pii(int first, int second) { this.first = first; this.second = second; } public static Pii of(int first, int second) { return new Pii(first, second); } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pii pair = (Pii) o; return first == pair.first && second == pair.second; } public int hashCode() { return Arrays.hashCode(new int[]{first, second}); } public String toString() { return "(" + first + ", " + second + ')'; } public int compareTo(Pii o) { if (first != o.first) return Integer.compare(first, o.first); return Integer.compare(second, o.second); } } static class InputReader { public final 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()); } } static class NumberTheory { private static void ASSERT(boolean assertion) { if (!assertion) throw new AssertionError(); } public abstract static class Modulus<M extends NumberTheory.Modulus<M>> { final ArrayList<Long> factorial = new ArrayList<>(); final ArrayList<Long> invFactorial = new ArrayList<>(); public abstract long modulus(); public Modulus() { super(); factorial.add(1L); invFactorial.add(1L); } public long normalize(long x) { x %= modulus(); if (x < 0) x += modulus(); return x; } public long add(long a, long b) { long v = a + b; return v < modulus() ? v : v - modulus(); } public long mult(long a, long b) { return (a * b) % modulus(); } public long div(long a, long b) { return mult(a, inv(b)); } public long inv(long value) { long g = modulus(), x = 0, y = 1; for (long r = value; r != 0; ) { long q = g / r; g %= r; long temp = g; g = r; r = temp; x -= q * y; temp = x; x = y; y = temp; } ASSERT(g == 1); ASSERT(y == modulus() || y == -modulus()); return normalize(x); } } public static class Mod998 extends NumberTheory.Modulus<NumberTheory.Mod998> { public long modulus() { return 998_244_353L; } } } }
Java
["2 3\n14\n2 4\n2 1\n1 0"]
5 seconds
["15\n12\n2"]
NoteAfter the first update $$$c$$$ is equal to $$$14$$$. The pairs that sum up to $$$14$$$ are: $$$(0, 14)$$$, $$$(1, 13)$$$, $$$(2, 12)$$$, $$$(3, 11)$$$, $$$(4, 10)$$$, $$$(5, 9)$$$, $$$(6, 8)$$$, $$$(7, 7)$$$, $$$(8, 6)$$$, $$$(9, 5)$$$, $$$(10, 4)$$$, $$$(11, 3)$$$, $$$(12, 2)$$$, $$$(13, 1)$$$, $$$(14, 0)$$$.After the second update $$$c$$$ is equal to $$$11$$$.After the third update $$$c$$$ is equal to $$$01$$$.
Java 8
standard input
[ "dp", "data structures", "matrices" ]
d3baf23c53ba50a03f5ef63d58d177cb
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^5$$$) — the length of the number $$$c$$$ and the number of updates. The second line contains a string $$$c$$$, consisting of exactly $$$n$$$ digits from $$$0$$$ to $$$9$$$. Each of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$d$$$ ($$$1 \le x \le n$$$, $$$0 \le d \le 9$$$) — the descriptions of updates.
2,600
Print $$$m$$$ integers — the $$$i$$$-th value should be equal to the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$ after $$$i$$$ updates are applied. Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
standard output
PASSED
a88f190c4ca3c38dd514c0c6545433e8
train_002.jsonl
1594565100
Let $$$a$$$ and $$$b$$$ be some non-negative integers. Let's define strange addition of $$$a$$$ and $$$b$$$ as following: write down the numbers one under another and align them by their least significant digit; add them up digit by digit and concatenate the respective sums together. Assume that both numbers have an infinite number of leading zeros.For example, let's take a look at a strange addition of numbers $$$3248$$$ and $$$908$$$: You are given a string $$$c$$$, consisting of $$$n$$$ digits from $$$0$$$ to $$$9$$$. You are also given $$$m$$$ updates of form: $$$x~d$$$ — replace the digit at the $$$x$$$-th position of $$$c$$$ with a digit $$$d$$$. Note that string $$$c$$$ might have leading zeros at any point of time.After each update print the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$.Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main { static final long MOD = 998244353L; public static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); int N = sc.ni(); int Q = sc.ni(); String s = sc.next(); int[] num = new int[N]; for (int i = 0; i < N; i++) num[i] = s.charAt(N-1-i)-'0'; long[] ways = new long[100]; long[] sub = new long[100]; for (int i = 0; i < 10; i++) { sub[i] = i+1; for (int j = 0; j < 10; j++) ways[i+j] += 1L; } SegmentTree st = new SegmentTree(N-1); for (int i = 0; i < N-1; i++) { int n = 10*num[i+1]+num[i]; long[] mat = new long[]{ways[num[i+1]],ways[n]-sub[n],1L,0L}; st.update(i,mat); } for (int q = 0; q < Q; q++) { int idx = N-sc.ni(); int d = sc.ni(); num[idx] = d; if (idx < N-1) { int n = 10*num[idx+1]+num[idx]; long[] m = new long[]{ways[num[idx+1]],ways[n]-sub[n],1L,0L}; st.update(idx,m); } if (idx > 0) { int n = 10*num[idx]+num[idx-1]; long[] m = new long[]{ways[num[idx]],ways[n]-sub[n],1L,0L}; st.update(idx-1,m); } long[] mat = st.query(0, N-2); long ans = (mat[0]*ways[num[0]]+mat[1])%MOD; pw.println(ans); } pw.close(); } //No lazy propagation. 0 indexed. Very fast. static class SegmentTree { public long[][] tree; public long[] NONE; public int N; //Zero initialization public SegmentTree(int n) { N = n; tree = new long[4*N+1][4]; NONE = new long[]{1,0,0,1}; Arrays.fill(tree, NONE); } public long[] query(int i, int j) { return query(0,0,N-1,i,j); } public void update(int arrIndex, long[] val) { update(0,0,N-1,arrIndex,val); } private long[] query(int treeIndex, int lo, int hi, int i, int j) { // query for arr[i..j] if (lo > j || hi < i) return NONE; if (i <= lo && j >= hi) return tree[treeIndex]; int mid = lo + (hi - lo) / 2; if (i > mid) return query(2 * treeIndex + 2, mid + 1, hi, i, j); else if (j <= mid) return query(2 * treeIndex + 1, lo, mid, i, j); long[] leftQuery = query(2 * treeIndex + 1, lo, mid, i, mid); long[] rightQuery = query(2 * treeIndex + 2, mid + 1, hi, mid + 1, j); // merge query results return merge(leftQuery, rightQuery); } private void update(int treeIndex, int lo, int hi, int arrIndex, long[] val) { if (lo == hi) { tree[treeIndex] = val; return; } int mid = lo + (hi - lo) / 2; if (arrIndex > mid) update(2 * treeIndex + 2, mid + 1, hi, arrIndex, val); else if (arrIndex <= mid) update(2 * treeIndex + 1, lo, mid, arrIndex, val); // merge updates tree[treeIndex] = merge(tree[2 * treeIndex + 1], tree[2 * treeIndex + 2]); } private long[] merge(long[] a, long[] b) { long[] ret = new long[] {(b[0]*a[0]+b[1]*a[2])%MOD,(b[0]*a[1]+b[1]*a[3])%MOD,(b[2]*a[0]+b[3]*a[2])%MOD,(b[2]*a[1]+b[3]*a[3])%MOD}; return ret; } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { 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 ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["2 3\n14\n2 4\n2 1\n1 0"]
5 seconds
["15\n12\n2"]
NoteAfter the first update $$$c$$$ is equal to $$$14$$$. The pairs that sum up to $$$14$$$ are: $$$(0, 14)$$$, $$$(1, 13)$$$, $$$(2, 12)$$$, $$$(3, 11)$$$, $$$(4, 10)$$$, $$$(5, 9)$$$, $$$(6, 8)$$$, $$$(7, 7)$$$, $$$(8, 6)$$$, $$$(9, 5)$$$, $$$(10, 4)$$$, $$$(11, 3)$$$, $$$(12, 2)$$$, $$$(13, 1)$$$, $$$(14, 0)$$$.After the second update $$$c$$$ is equal to $$$11$$$.After the third update $$$c$$$ is equal to $$$01$$$.
Java 8
standard input
[ "dp", "data structures", "matrices" ]
d3baf23c53ba50a03f5ef63d58d177cb
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^5$$$) — the length of the number $$$c$$$ and the number of updates. The second line contains a string $$$c$$$, consisting of exactly $$$n$$$ digits from $$$0$$$ to $$$9$$$. Each of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$d$$$ ($$$1 \le x \le n$$$, $$$0 \le d \le 9$$$) — the descriptions of updates.
2,600
Print $$$m$$$ integers — the $$$i$$$-th value should be equal to the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$ after $$$i$$$ updates are applied. Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
standard output
PASSED
54785d81d4f0386384e8a93726f53227
train_002.jsonl
1594565100
Let $$$a$$$ and $$$b$$$ be some non-negative integers. Let's define strange addition of $$$a$$$ and $$$b$$$ as following: write down the numbers one under another and align them by their least significant digit; add them up digit by digit and concatenate the respective sums together. Assume that both numbers have an infinite number of leading zeros.For example, let's take a look at a strange addition of numbers $$$3248$$$ and $$$908$$$: You are given a string $$$c$$$, consisting of $$$n$$$ digits from $$$0$$$ to $$$9$$$. You are also given $$$m$$$ updates of form: $$$x~d$$$ — replace the digit at the $$$x$$$-th position of $$$c$$$ with a digit $$$d$$$. Note that string $$$c$$$ might have leading zeros at any point of time.After each update print the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$.Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
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 x1380F { 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 Q = Integer.parseInt(st.nextToken()); String input = infile.readLine(); LazySegTree segtree = new LazySegTree(N); for(int i=0; i < N; i++) { int d = Integer.parseInt(input.charAt(i)+""); segtree.update(i, new Node(d, d, d+1, 1L, 1L, 0L)); } StringBuilder sb = new StringBuilder(); while(Q-->0) { st = new StringTokenizer(infile.readLine()); int x = Integer.parseInt(st.nextToken())-1; int d = Integer.parseInt(st.nextToken()); segtree.update(x, new Node(d, d, d+1, 1L, 1L, 0L)); sb.append(segtree.query()+"\n"); } System.out.print(sb); } } class LazySegTree { //definitions public final long MOD = 998244353L; //ds stuff private Node[] tree; private int length; public LazySegTree(int N) { length = N; int b; for(b=0; (1<<b) < length; b++); tree = new Node[1<<(b+1)]; } public long query() { //left and right are 0-indexed return tree[1].ways; } public void update(int dex, Node delta) { add(1, 0, length-1, dex, dex, delta); } private void add(int v, int currL, int currR, int L, int R, Node delta) { if(L > R) return; if(currL == L && currR == R) { //exact covering tree[v] = delta; return; } int mid = (currL+currR)/2; add(v*2, currL, mid, L, Math.min(R, mid), delta); add(v*2+1, mid+1, currR, Math.max(L, mid+1), R, delta); tree[v] = comb(tree[v*2], tree[v*2+1]); } private Node comb(Node a, Node b) { if(a == null) return new Node(b.head, b.tail, b.ways, b.waysPref, b.waysSuff, b.waysBoth); else if(b == null) return new Node(a.head, a.tail, a.ways, a.waysPref, a.waysSuff, a.waysBoth); int head = a.head; int tail = b.tail; //19 = 0, 18 = 1, ..., 10 = 9 ways int multiplier = 9-b.head; long ways = (a.ways*b.ways)%MOD+lol(a.tail == 1)*multiplier*(a.waysPref*b.waysSuff)%MOD; if(ways >= MOD) ways -= MOD; long waysPref = (a.ways*b.waysPref)%MOD+lol(a.tail == 1)*multiplier*(a.waysPref*b.waysBoth)%MOD; if(waysPref >= MOD) waysPref -= MOD; long waysSuff = (a.waysSuff*b.ways)%MOD+lol(a.tail == 1)*multiplier*(a.waysBoth*b.waysSuff)%MOD; if(waysSuff >= MOD) waysSuff -= MOD; long waysBoth = (a.waysSuff*b.waysPref)%MOD+lol(a.tail == 1)*multiplier*(a.waysBoth*b.waysBoth)%MOD; if(waysBoth >= MOD) waysBoth -= MOD; return new Node(head, tail, ways, waysPref, waysSuff, waysBoth); } private int lol(boolean b) { return b ? 1 : 0; } } class Node { public int head; public int tail; public long ways; public long waysPref; public long waysSuff; public long waysBoth; public Node(int h, int t, long a, long b, long c, long d) { ways = a; waysPref = b; waysSuff = c; waysBoth = d; head = h; tail = t; } }
Java
["2 3\n14\n2 4\n2 1\n1 0"]
5 seconds
["15\n12\n2"]
NoteAfter the first update $$$c$$$ is equal to $$$14$$$. The pairs that sum up to $$$14$$$ are: $$$(0, 14)$$$, $$$(1, 13)$$$, $$$(2, 12)$$$, $$$(3, 11)$$$, $$$(4, 10)$$$, $$$(5, 9)$$$, $$$(6, 8)$$$, $$$(7, 7)$$$, $$$(8, 6)$$$, $$$(9, 5)$$$, $$$(10, 4)$$$, $$$(11, 3)$$$, $$$(12, 2)$$$, $$$(13, 1)$$$, $$$(14, 0)$$$.After the second update $$$c$$$ is equal to $$$11$$$.After the third update $$$c$$$ is equal to $$$01$$$.
Java 8
standard input
[ "dp", "data structures", "matrices" ]
d3baf23c53ba50a03f5ef63d58d177cb
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^5$$$) — the length of the number $$$c$$$ and the number of updates. The second line contains a string $$$c$$$, consisting of exactly $$$n$$$ digits from $$$0$$$ to $$$9$$$. Each of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$d$$$ ($$$1 \le x \le n$$$, $$$0 \le d \le 9$$$) — the descriptions of updates.
2,600
Print $$$m$$$ integers — the $$$i$$$-th value should be equal to the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$ after $$$i$$$ updates are applied. Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
standard output
PASSED
157042bfe35b633eac2c693a98782b30
train_002.jsonl
1594565100
Let $$$a$$$ and $$$b$$$ be some non-negative integers. Let's define strange addition of $$$a$$$ and $$$b$$$ as following: write down the numbers one under another and align them by their least significant digit; add them up digit by digit and concatenate the respective sums together. Assume that both numbers have an infinite number of leading zeros.For example, let's take a look at a strange addition of numbers $$$3248$$$ and $$$908$$$: You are given a string $$$c$$$, consisting of $$$n$$$ digits from $$$0$$$ to $$$9$$$. You are also given $$$m$$$ updates of form: $$$x~d$$$ — replace the digit at the $$$x$$$-th position of $$$c$$$ with a digit $$$d$$$. Note that string $$$c$$$ might have leading zeros at any point of time.After each update print the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$.Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
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; /** * 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 { private long[] a; private long[] b; private long[] c; private long[] d; private int[] s; private final long mod = 998244353; private final long[] modInv = {0, 1, 499122177, 332748118, 748683265, 598946612, 166374059, 855638017, 873463809, 443664157, 299473306}; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(), m = in.nextInt(); s = new int[n]; String tmp = in.next(); for (int i = 0; i < n; i++) { s[i] = tmp.charAt(i) - '0'; } a = new long[4 * n]; b = new long[4 * n]; c = new long[4 * n]; d = new long[4 * n]; build(0, 0, n - 1); for (int i = 0; i < m; i++) { int x = in.nextInt() - 1; s[x] = in.nextInt(); update(0, 0, n - 1, x); out.println((a[0] + b[0] + c[0] + d[0]) % mod); } } private void build(int i, int l, int r) { if (l == r) { a[i] = s[l] + 1; return; } build(2 * i + 1, l, (l + r) / 2); build(2 * i + 2, (l + r) / 2 + 1, r); calc(i, l, r); } private void update(int i, int l, int r, int x) { if (l == r) { a[i] = s[l] + 1; return; } if (x <= (l + r) / 2) { update(2 * i + 1, l, (l + r) / 2, x); } else { update(2 * i + 2, (l + r) / 2 + 1, r, x); } calc(i, l, r); } private void calc(int i, int l, int r) { int m = (l + r) / 2, u = 2 * i + 1, v = 2 * i + 2; if (l + 1 == r) { a[i] = (s[l] + 1) * (s[r] + 1); if (s[l] == 1) { d[i] = 9 - s[r]; } else { d[i] = 0; } } else if (l + 2 == r) { a[i] = (s[l] + 1) * (s[m] + 1) * (s[r] + 1); if (s[l] == 1) { c[i] = (9 - s[m]) * (s[r] + 1); } else { c[i] = 0; } if (s[m] == 1) { b[i] = (s[l] + 1) * (9 - s[r]); } else { b[i] = 0; } } else { a[i] = (a[u] + b[u]) * (a[v] + c[v]); b[i] = (a[u] + b[u]) * (b[v] + d[v]); c[i] = (c[u] + d[u]) * (a[v] + c[v]); d[i] = (c[u] + d[u]) * (b[v] + d[v]); if (s[m] == 1) { a[i] += modProduct(a[u], modInv[s[m] + 1], a[v], modInv[s[m + 1] + 1], 9 - s[m + 1]); b[i] += modProduct(a[u], modInv[s[m] + 1], b[v], modInv[s[m + 1] + 1], 9 - s[m + 1]); c[i] += modProduct(c[u], modInv[s[m] + 1], a[v], modInv[s[m + 1] + 1], 9 - s[m + 1]); d[i] += modProduct(c[u], modInv[s[m] + 1], b[v], modInv[s[m + 1] + 1], 9 - s[m + 1]); } a[i] %= mod; b[i] %= mod; c[i] %= mod; d[i] %= mod; } } private long modProduct(long a, long b, long c, long d, long e) { return ((((a * b) % mod) * ((c * d) % mod)) % mod) * e; } } static class InputReader { private BufferedReader br; private StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream), 32768); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["2 3\n14\n2 4\n2 1\n1 0"]
5 seconds
["15\n12\n2"]
NoteAfter the first update $$$c$$$ is equal to $$$14$$$. The pairs that sum up to $$$14$$$ are: $$$(0, 14)$$$, $$$(1, 13)$$$, $$$(2, 12)$$$, $$$(3, 11)$$$, $$$(4, 10)$$$, $$$(5, 9)$$$, $$$(6, 8)$$$, $$$(7, 7)$$$, $$$(8, 6)$$$, $$$(9, 5)$$$, $$$(10, 4)$$$, $$$(11, 3)$$$, $$$(12, 2)$$$, $$$(13, 1)$$$, $$$(14, 0)$$$.After the second update $$$c$$$ is equal to $$$11$$$.After the third update $$$c$$$ is equal to $$$01$$$.
Java 8
standard input
[ "dp", "data structures", "matrices" ]
d3baf23c53ba50a03f5ef63d58d177cb
The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 5 \cdot 10^5$$$) — the length of the number $$$c$$$ and the number of updates. The second line contains a string $$$c$$$, consisting of exactly $$$n$$$ digits from $$$0$$$ to $$$9$$$. Each of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$d$$$ ($$$1 \le x \le n$$$, $$$0 \le d \le 9$$$) — the descriptions of updates.
2,600
Print $$$m$$$ integers — the $$$i$$$-th value should be equal to the number of pairs $$$(a, b)$$$ such that both $$$a$$$ and $$$b$$$ are non-negative integers and the result of a strange addition of $$$a$$$ and $$$b$$$ is equal to $$$c$$$ after $$$i$$$ updates are applied. Note that the numbers of pairs can be quite large, so print them modulo $$$998244353$$$.
standard output
PASSED
d95c039182a795db3f12b9796063e753
train_002.jsonl
1485108900
Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters "a", ..., "z".The testtube is divided into n consecutive regions. Each region is occupied by a single colony of a certain bacteria type at any given moment. Hence, the population of the testtube at any moment can be described by a string of n Latin characters.Sometimes a colony can decide to conquer another colony in one of the adjacent regions. When that happens, the attacked colony is immediately eliminated and replaced by a colony of the same type as the attacking colony, while the attacking colony keeps its type. Note that a colony can only attack its neighbours within the boundaries of the testtube. At any moment, at most one attack can take place.For example, consider a testtube with population "babb". There are six options for an attack that may happen next: the first colony attacks the second colony (1 → 2), the resulting population is "bbbb"; 2 → 1, the result is "aabb"; 2 → 3, the result is "baab"; 3 → 2, the result is "bbbb" (note that the result is the same as the first option); 3 → 4 or 4 → 3, the population does not change.The pattern of attacks is rather unpredictable. Julia is now wondering how many different configurations of bacteria in the testtube she can obtain after a sequence of attacks takes place (it is possible that no attacks will happen at all). Since this number can be large, find it modulo 109 + 7.
256 megabytes
import java.io.*; import java.util.*; public class D { FastScanner in; PrintWriter out; void solve() { int n = in.nextInt(); char[] s = in.next().toCharArray(); final int mod = (int) 1e9 + 7; int[][] dp = new int[26][n + 1]; int[] sum = new int[n + 1]; sum[0] = 1; for (int i = 0; i < n; i++) { int id = s[i] - 'a'; for (int j = 1; j <= n; j++) { sum[j] -= dp[id][j]; if (sum[j] < 0) { sum[j] += mod; } dp[id][j] = sum[j - 1] - dp[id][j - 1]; if (dp[id][j] < 0) { dp[id][j] += mod; } sum[j] += dp[id][j]; if (sum[j] >= mod) { sum[j] -= mod; } } } long res = 0; int[] cPrev = new int[n + 1]; cPrev[0] = 1; int[] cNext = new int[n + 1]; for (int diff = 1; diff < n; diff++) { cNext[0] = 1; for (int j = 1; j <= n; j++) { cNext[j] = cPrev[j - 1] + cPrev[j]; if (cNext[j] >= mod) { cNext[j] -= mod; } } int[] tmp = cPrev; cPrev = cNext; cNext = tmp; } for (int diff = 1; diff <= n; diff++) { res += sum[diff] * 1L * cPrev[diff - 1] % mod; res %= mod; } out.println(res); } void run() { try { in = new FastScanner(new File("object.in")); out = new PrintWriter(new File("object.out")); solve(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } } void runIO() { in = new FastScanner(System.in); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] args) { new D().runIO(); } }
Java
["3\naaa", "2\nab", "4\nbabb", "7\nabacaba"]
2 seconds
["1", "3", "11", "589"]
NoteIn the first sample the population can never change since all bacteria are of the same type.In the second sample three configurations are possible: "ab" (no attacks), "aa" (the first colony conquers the second colony), and "bb" (the second colony conquers the first colony).To get the answer for the third sample, note that more than one attack can happen.
Java 8
standard input
[ "dp", "combinatorics", "string suffix structures", "brute force" ]
81ad3bb3d58a33016221d60a601790d4
The first line contains an integer n — the number of regions in the testtube (1 ≤ n ≤ 5 000). The second line contains n small Latin letters that describe the initial population of the testtube.
2,400
Print one number — the answer to the problem modulo 109 + 7.
standard output
PASSED
a8aa36ac60c55bc7fdd078be41b738ea
train_002.jsonl
1485108900
Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters "a", ..., "z".The testtube is divided into n consecutive regions. Each region is occupied by a single colony of a certain bacteria type at any given moment. Hence, the population of the testtube at any moment can be described by a string of n Latin characters.Sometimes a colony can decide to conquer another colony in one of the adjacent regions. When that happens, the attacked colony is immediately eliminated and replaced by a colony of the same type as the attacking colony, while the attacking colony keeps its type. Note that a colony can only attack its neighbours within the boundaries of the testtube. At any moment, at most one attack can take place.For example, consider a testtube with population "babb". There are six options for an attack that may happen next: the first colony attacks the second colony (1 → 2), the resulting population is "bbbb"; 2 → 1, the result is "aabb"; 2 → 3, the result is "baab"; 3 → 2, the result is "bbbb" (note that the result is the same as the first option); 3 → 4 or 4 → 3, the population does not change.The pattern of attacks is rather unpredictable. Julia is now wondering how many different configurations of bacteria in the testtube she can obtain after a sequence of attacks takes place (it is possible that no attacks will happen at all). Since this number can be large, find it modulo 109 + 7.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.Arrays; 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 << 29); 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); DBacterialMelee solver = new DBacterialMelee(); solver.solve(1, in, out); out.close(); } } static class DBacterialMelee { Debug debug = new Debug(true); public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { char c = in.readChar(); if (sb.length() == 0 || sb.charAt(sb.length() - 1) != c) { sb.append(c); } } int m = sb.length(); int[] seq = new int[sb.length() + 1]; for (int i = 1; i <= sb.length(); i++) { seq[i] = sb.charAt(i - 1) - 'a'; } seq[0] = -1; //debug.debug("seq", seq); int charset = 'z' - 'a' + 1; int[][] next = new int[m + 1][charset]; Arrays.fill(next[m], m + 1); for (int i = m - 1; i >= 0; i--) { for (int j = 0; j < charset; j++) { next[i][j] = next[i + 1][j]; } next[i][seq[i + 1]] = i + 1; } debug.elapse("init"); //debug.debug("next", next); int[][] dp = new int[m + 1][m + 1]; dp[0][0] = 1; Modular mod = new Modular(1e9 + 7); int[][] sum = new int[charset][m + 1]; int[] global = new int[m + 1]; for (int i = 0; i <= m; i++) { int c = seq[i]; if (i > 0) { for (int j = 0; j <= i; j++) { dp[i][j] = mod.plus(sum[c][j], global[j]); sum[c][j] = mod.valueOf(-global[j]); } } if (i == m) { break; } for (int j = 0; j <= i; j++) { global[j + 1] = mod.plus(global[j + 1], dp[i][j]); if (c >= 0) { sum[c][j + 1] = mod.subtract(sum[c][j + 1], dp[i][j]); } } } debug.elapse("dp"); int[] cnts = new int[m + 1]; for (int i = 1; i <= m; i++) { for (int j = 0; j <= m; j++) { cnts[j] = mod.plus(cnts[j], dp[i][j]); } } //debug.debug("cnts", cnts); int ans = 0; Power pow = new Power(mod); Combination comb = new Combination(n, pow); for (int i = 1; i <= m; i++) { int contrib = comb.combination(n - i + i - 1, i - 1); contrib = mod.mul(contrib, cnts[i]); ans = mod.plus(ans, contrib); } debug.elapse("calc ans"); out.println(ans); } } static class Debug { private boolean offline; private PrintStream out = System.err; private long time = System.currentTimeMillis(); public Debug(boolean enable) { offline = enable && System.getSecurityManager() == null; } public Debug elapse(String name) { if (offline) { debug(name, System.currentTimeMillis() - time); time = System.currentTimeMillis(); } return this; } public Debug debug(String name, long x) { if (offline) { debug(name, "" + x); } return this; } public Debug debug(String name, String x) { if (offline) { out.printf("%s=%s", name, x); out.println(); } return this; } } static class Combination implements IntCombination { final Factorial factorial; final Modular modular; public Combination(Factorial factorial) { this.factorial = factorial; this.modular = factorial.getMod(); } public Combination(int limit, Power pow) { this(new Factorial(limit, pow)); } public int combination(int m, int n) { if (n > m || n < 0) { return 0; } return modular.mul(modular.mul(factorial.fact(m), factorial.invFact(n)), factorial.invFact(m - n)); } } static class IntExtGCDObject { private int[] xy = new int[2]; public int extgcd(int a, int b) { return ExtGCD.extGCD(a, b, xy); } public int getX() { return xy[0]; } } static class Factorial { int[] fact; int[] inv; Modular mod; public Modular getMod() { return mod; } public Factorial(int[] fact, int[] inv, Power pow) { this.mod = pow.getModular(); this.fact = fact; this.inv = inv; fact[0] = inv[0] = 1; for (int i = 1; i < fact.length; i++) { fact[i] = i; fact[i] = mod.mul(fact[i], fact[i - 1]); } inv[inv.length - 1] = pow.inverse(fact[inv.length - 1]); for (int i = inv.length - 2; i >= 1; i--) { inv[i] = mod.mul(inv[i + 1], i + 1); } } public Factorial(int limit, Power pow) { this(new int[limit + 1], new int[limit + 1], pow); } public int fact(int n) { return fact[n]; } public int invFact(int n) { return inv[n]; } } static class SequenceUtils { public static void swap(int[] data, int i, int j) { int tmp = data[i]; data[i] = data[j]; data[j] = tmp; } } static class Power implements InverseNumber { static IntExtGCDObject extGCD = new IntExtGCDObject(); final Modular modular; public Modular getModular() { return modular; } public Power(Modular modular) { this.modular = modular; } public int inverse(int x) { int ans = inverseExtGCD(x); // if(modular.mul(ans, x) != 1){ // throw new IllegalStateException(); // } return ans; } public int inverseExtGCD(int x) { if (extGCD.extgcd(x, modular.getMod()) != 1) { throw new IllegalArgumentException(); } return modular.valueOf(extGCD.getX()); } } static class ExtGCD { public static int extGCD(int a, int b, int[] xy) { if (a >= b) { return extGCD0(a, b, xy); } int ans = extGCD0(b, a, xy); SequenceUtils.swap(xy, 0, 1); return ans; } private static int extGCD0(int a, int b, int[] xy) { if (b == 0) { xy[0] = 1; xy[1] = 0; return a; } int ans = extGCD0(b, a % b, xy); int x = xy[0]; int y = xy[1]; xy[0] = y; xy[1] = x - a / b * y; return ans; } } static interface InverseNumber { } static interface IntCombination { } static class Modular { int m; public int getMod() { return 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 mul(int x, int y) { return valueOf((long) x * y); } public int plus(int x, int y) { return valueOf(x + y); } public int subtract(int x, int y) { return valueOf(x - y); } public String toString() { return "mod " + m; } } 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; } public char readChar() { skipBlank(); char c = (char) next; next = read(); return c; } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); return this; } public FastOutput append(int c) { cache.append(c); return this; } public FastOutput println(int c) { return append(c).println(); } public FastOutput println() { cache.append(System.lineSeparator()); 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(); } } }
Java
["3\naaa", "2\nab", "4\nbabb", "7\nabacaba"]
2 seconds
["1", "3", "11", "589"]
NoteIn the first sample the population can never change since all bacteria are of the same type.In the second sample three configurations are possible: "ab" (no attacks), "aa" (the first colony conquers the second colony), and "bb" (the second colony conquers the first colony).To get the answer for the third sample, note that more than one attack can happen.
Java 8
standard input
[ "dp", "combinatorics", "string suffix structures", "brute force" ]
81ad3bb3d58a33016221d60a601790d4
The first line contains an integer n — the number of regions in the testtube (1 ≤ n ≤ 5 000). The second line contains n small Latin letters that describe the initial population of the testtube.
2,400
Print one number — the answer to the problem modulo 109 + 7.
standard output
PASSED
ab61d1ba9f39e25e774242ff43d4b9e3
train_002.jsonl
1485108900
Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters "a", ..., "z".The testtube is divided into n consecutive regions. Each region is occupied by a single colony of a certain bacteria type at any given moment. Hence, the population of the testtube at any moment can be described by a string of n Latin characters.Sometimes a colony can decide to conquer another colony in one of the adjacent regions. When that happens, the attacked colony is immediately eliminated and replaced by a colony of the same type as the attacking colony, while the attacking colony keeps its type. Note that a colony can only attack its neighbours within the boundaries of the testtube. At any moment, at most one attack can take place.For example, consider a testtube with population "babb". There are six options for an attack that may happen next: the first colony attacks the second colony (1 → 2), the resulting population is "bbbb"; 2 → 1, the result is "aabb"; 2 → 3, the result is "baab"; 3 → 2, the result is "bbbb" (note that the result is the same as the first option); 3 → 4 or 4 → 3, the population does not change.The pattern of attacks is rather unpredictable. Julia is now wondering how many different configurations of bacteria in the testtube she can obtain after a sequence of attacks takes place (it is possible that no attacks will happen at all). Since this number can be large, find it modulo 109 + 7.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.Arrays; 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 << 29); 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); DBacterialMelee solver = new DBacterialMelee(); solver.solve(1, in, out); out.close(); } } static class DBacterialMelee { Debug debug = new Debug(true); public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { char c = in.readChar(); if (sb.length() == 0 || sb.charAt(sb.length() - 1) != c) { sb.append(c); } } int m = sb.length(); int[] seq = new int[sb.length() + 1]; for (int i = 1; i <= sb.length(); i++) { seq[i] = sb.charAt(i - 1) - 'a'; } seq[0] = -1; //debug.debug("seq", seq); int charset = 'z' - 'a' + 1; int[][] next = new int[m + 1][charset]; Arrays.fill(next[m], m + 1); for (int i = m - 1; i >= 0; i--) { for (int j = 0; j < charset; j++) { next[i][j] = next[i + 1][j]; } next[i][seq[i + 1]] = i + 1; } debug.elapse("init"); //debug.debug("next", next); long[][] dp = new long[m + 1][m + 1]; dp[0][0] = 1; Modular mod = new Modular(1e9 + 7); int modVal = mod.getMod(); for (int i = 0; i <= m; i++) { for (int j = 0; j <= i; j++) { dp[i][j] %= modVal; } for (int k = 0; k < charset; k++) { if (k == seq[i] || next[i][k] == m + 1) { continue; } int g = next[i][k]; for (int j = 0; j <= i; j++) { dp[g][j + 1] = (dp[g][j + 1] + dp[i][j]); } } } debug.elapse("dp"); int[] cnts = new int[m + 1]; for (int i = 1; i <= m; i++) { for (int j = 0; j <= m; j++) { cnts[j] = mod.plus(cnts[j], dp[i][j]); } } //debug.debug("cnts", cnts); int ans = 0; Power pow = new Power(mod); Combination comb = new Combination(n, pow); for (int i = 1; i <= m; i++) { int contrib = comb.combination(n - i + i - 1, i - 1); contrib = mod.mul(contrib, cnts[i]); ans = mod.plus(ans, contrib); } debug.elapse("calc ans"); out.println(ans); } } static class Debug { private boolean offline; private PrintStream out = System.err; private long time = System.currentTimeMillis(); public Debug(boolean enable) { offline = enable && System.getSecurityManager() == null; } public Debug elapse(String name) { if (offline) { debug(name, System.currentTimeMillis() - time); time = System.currentTimeMillis(); } return this; } public Debug debug(String name, long x) { if (offline) { debug(name, "" + x); } return this; } public Debug debug(String name, String x) { if (offline) { out.printf("%s=%s", name, x); out.println(); } return this; } } static class SequenceUtils { public static void swap(int[] data, int i, int j) { int tmp = data[i]; data[i] = data[j]; data[j] = tmp; } } static class Combination implements IntCombination { final Factorial factorial; final Modular modular; public Combination(Factorial factorial) { this.factorial = factorial; this.modular = factorial.getMod(); } public Combination(int limit, Power pow) { this(new Factorial(limit, pow)); } public int combination(int m, int n) { if (n > m || n < 0) { return 0; } return modular.mul(modular.mul(factorial.fact(m), factorial.invFact(n)), factorial.invFact(m - n)); } } static class IntExtGCDObject { private int[] xy = new int[2]; public int extgcd(int a, int b) { return ExtGCD.extGCD(a, b, xy); } public int getX() { return xy[0]; } } static class Factorial { int[] fact; int[] inv; Modular mod; public Modular getMod() { return mod; } public Factorial(int[] fact, int[] inv, Power pow) { this.mod = pow.getModular(); this.fact = fact; this.inv = inv; fact[0] = inv[0] = 1; for (int i = 1; i < fact.length; i++) { fact[i] = i; fact[i] = mod.mul(fact[i], fact[i - 1]); } inv[inv.length - 1] = pow.inverse(fact[inv.length - 1]); for (int i = inv.length - 2; i >= 1; i--) { inv[i] = mod.mul(inv[i + 1], i + 1); } } public Factorial(int limit, Power pow) { this(new int[limit + 1], new int[limit + 1], pow); } public int fact(int n) { return fact[n]; } public int invFact(int n) { return inv[n]; } } static class Power implements InverseNumber { static IntExtGCDObject extGCD = new IntExtGCDObject(); final Modular modular; public Modular getModular() { return modular; } public Power(Modular modular) { this.modular = modular; } public int inverse(int x) { int ans = inverseExtGCD(x); // if(modular.mul(ans, x) != 1){ // throw new IllegalStateException(); // } return ans; } public int inverseExtGCD(int x) { if (extGCD.extgcd(x, modular.getMod()) != 1) { throw new IllegalArgumentException(); } return modular.valueOf(extGCD.getX()); } } static class ExtGCD { public static int extGCD(int a, int b, int[] xy) { if (a >= b) { return extGCD0(a, b, xy); } int ans = extGCD0(b, a, xy); SequenceUtils.swap(xy, 0, 1); return ans; } private static int extGCD0(int a, int b, int[] xy) { if (b == 0) { xy[0] = 1; xy[1] = 0; return a; } int ans = extGCD0(b, a % b, xy); int x = xy[0]; int y = xy[1]; xy[0] = y; xy[1] = x - a / b * y; return ans; } } static interface InverseNumber { } static interface IntCombination { } static class Modular { int m; public int getMod() { return 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 mul(int x, int y) { return valueOf((long) x * y); } public int plus(int x, int y) { return valueOf(x + y); } public int plus(long x, long y) { return valueOf(x + y); } public String toString() { return "mod " + m; } } 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; } public char readChar() { skipBlank(); char c = (char) next; next = read(); return c; } } static class FastOutput implements AutoCloseable, Closeable, Appendable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); return this; } public FastOutput append(int c) { cache.append(c); return this; } public FastOutput println(int c) { return append(c).println(); } public FastOutput println() { cache.append(System.lineSeparator()); 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(); } } }
Java
["3\naaa", "2\nab", "4\nbabb", "7\nabacaba"]
2 seconds
["1", "3", "11", "589"]
NoteIn the first sample the population can never change since all bacteria are of the same type.In the second sample three configurations are possible: "ab" (no attacks), "aa" (the first colony conquers the second colony), and "bb" (the second colony conquers the first colony).To get the answer for the third sample, note that more than one attack can happen.
Java 8
standard input
[ "dp", "combinatorics", "string suffix structures", "brute force" ]
81ad3bb3d58a33016221d60a601790d4
The first line contains an integer n — the number of regions in the testtube (1 ≤ n ≤ 5 000). The second line contains n small Latin letters that describe the initial population of the testtube.
2,400
Print one number — the answer to the problem modulo 109 + 7.
standard output
PASSED
2c083844f4337859930417bdd6bcd87e
train_002.jsonl
1485108900
Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters "a", ..., "z".The testtube is divided into n consecutive regions. Each region is occupied by a single colony of a certain bacteria type at any given moment. Hence, the population of the testtube at any moment can be described by a string of n Latin characters.Sometimes a colony can decide to conquer another colony in one of the adjacent regions. When that happens, the attacked colony is immediately eliminated and replaced by a colony of the same type as the attacking colony, while the attacking colony keeps its type. Note that a colony can only attack its neighbours within the boundaries of the testtube. At any moment, at most one attack can take place.For example, consider a testtube with population "babb". There are six options for an attack that may happen next: the first colony attacks the second colony (1 → 2), the resulting population is "bbbb"; 2 → 1, the result is "aabb"; 2 → 3, the result is "baab"; 3 → 2, the result is "bbbb" (note that the result is the same as the first option); 3 → 4 or 4 → 3, the population does not change.The pattern of attacks is rather unpredictable. Julia is now wondering how many different configurations of bacteria in the testtube she can obtain after a sequence of attacks takes place (it is possible that no attacks will happen at all). Since this number can be large, find it modulo 109 + 7.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.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); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { final int mod = (int) (1e9 + 7); long[] fact = IntegerUtils.generateFactorial(5005, mod); long[] revFact = IntegerUtils.generateReverseFactorials(5005, mod); private long comb(int n, int m) { return fact[n] * revFact[m] % mod * revFact[n - m] % mod; } int add(int a, int b) { a += b; if (a < 0) { a += mod; } if (mod <= a) { a -= mod; } return a; } public void solve(int testNumber, InputReader in, OutputWriter out) { int n; int[] str; n = in.readInt(); str = new int[n]; for (int i = 0; i < n; i++) { str[i] = in.readCharacter() - 'a'; } // n = 5000; // str = new int[n]; // Arrays.fill(str, 'd' - 'a'); int[][] dp = new int[26][n + 1]; int[] sumColumn = new int[n + 1]; for (int i = 0; i < n; i++) { int ch = str[i]; for (int length = 1; length <= n; length++) { if (length == 1) { if (dp[ch][length] == 0) { dp[ch][length] = 1; ++sumColumn[length]; } } else { int sum = add(sumColumn[length - 1], -dp[ch][length - 1]); sumColumn[length] = add(sumColumn[length], -dp[ch][length]); dp[ch][length] = sum; sumColumn[length] = add(sumColumn[length], dp[ch][length]); } } } int answer = 0; for (int length = 1; length <= n; length++) { int sum = 0; for (int ch = 0; ch < 26; ch++) { sum = add(sum, dp[ch][length]); } answer = (int) ((answer + sum * comb(n - 1, length - 1)) % mod); // out.printLine("", length, sum); } out.printLine(answer); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if ((c < '0') || (c > '9')) { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return (c == ' ') || (c == '\n') || (c == '\r') || (c == '\t') || (c == -1); } public char readCharacter() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class IntegerUtils { public static long[] generateFactorial(int count, long module) { long[] result = new long[count]; if (module == -1) { if (count != 0) { result[0] = 1; } for (int i = 1; i < count; i++) { result[i] = result[i - 1] * i; } } else { if (count != 0) { result[0] = 1 % module; } for (int i = 1; i < count; i++) { result[i] = (result[i - 1] * i) % module; } } return result; } public static long[] generateReverse(int upTo, long module) { long[] result = new long[upTo]; if (upTo > 1) { result[1] = 1; } for (int i = 2; i < upTo; i++) { result[i] = (module - (((module / i) * result[((int) (module % i))]) % module)) % module; } return result; } public static long[] generateReverseFactorials(int upTo, long module) { long[] result = generateReverse(upTo, module); if (upTo > 0) { result[0] = 1; } for (int i = 1; i < upTo; i++) { result[i] = (result[i] * result[i - 1]) % module; } return result; } } 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 printLine(int i) { writer.println(i); } } }
Java
["3\naaa", "2\nab", "4\nbabb", "7\nabacaba"]
2 seconds
["1", "3", "11", "589"]
NoteIn the first sample the population can never change since all bacteria are of the same type.In the second sample three configurations are possible: "ab" (no attacks), "aa" (the first colony conquers the second colony), and "bb" (the second colony conquers the first colony).To get the answer for the third sample, note that more than one attack can happen.
Java 8
standard input
[ "dp", "combinatorics", "string suffix structures", "brute force" ]
81ad3bb3d58a33016221d60a601790d4
The first line contains an integer n — the number of regions in the testtube (1 ≤ n ≤ 5 000). The second line contains n small Latin letters that describe the initial population of the testtube.
2,400
Print one number — the answer to the problem modulo 109 + 7.
standard output
PASSED
95d80d3964621979c2113b256140a763
train_002.jsonl
1485108900
Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters "a", ..., "z".The testtube is divided into n consecutive regions. Each region is occupied by a single colony of a certain bacteria type at any given moment. Hence, the population of the testtube at any moment can be described by a string of n Latin characters.Sometimes a colony can decide to conquer another colony in one of the adjacent regions. When that happens, the attacked colony is immediately eliminated and replaced by a colony of the same type as the attacking colony, while the attacking colony keeps its type. Note that a colony can only attack its neighbours within the boundaries of the testtube. At any moment, at most one attack can take place.For example, consider a testtube with population "babb". There are six options for an attack that may happen next: the first colony attacks the second colony (1 → 2), the resulting population is "bbbb"; 2 → 1, the result is "aabb"; 2 → 3, the result is "baab"; 3 → 2, the result is "bbbb" (note that the result is the same as the first option); 3 → 4 or 4 → 3, the population does not change.The pattern of attacks is rather unpredictable. Julia is now wondering how many different configurations of bacteria in the testtube she can obtain after a sequence of attacks takes place (it is possible that no attacks will happen at all). Since this number can be large, find it modulo 109 + 7.
256 megabytes
import java.util.*; public class Test { static final int N = 5120; static final int L = 26; static final long M = 1000000007; long[][] dp = new long[N][32]; int[][] prefix = new int[N][32]; int[] idx = new int[32]; int n; Scanner sca = new Scanner(System.in); void start() { n = sca.nextInt(); char[] cs = sca.next().toCharArray(); for (int i = 1; i <= n; i++) { int ci = cs[i - 1] - 'a' + 1; idx[ci] = 0; for (int c = 1; c <= L; c++) { dp[i][c] = dp[idx[c]][0]; prefix[i][c] = idx[c]; } long cnt; for (int j = i - 1; j > 1; j--) { cnt = dp[j][0]; for (int c = 1; c <= L; c++) cnt += dp[prefix[j][c]][0]; dp[j][0] = cnt % M; } cnt = 1; for (int j = i; j > 1; j--) { dp[j - 1][ci] = 0; for (int c = 1; c <= L; c++) cnt += dp[j - 1][c]; cnt += dp[i][ci]; } dp[i][ci] = cnt % M; dp[1][ci] = 1; for (int j = 2; j <= i; j++) { cnt = 0; for (int c = 1; c <= L; c++) cnt += dp[j - 1][c]; dp[j][ci] = cnt % M; } cnt = 0; for (int c = 1; c <= L; c++) cnt += dp[i][c]; idx[ci] = i; dp[i][0] = cnt % M; if (i == n) System.out.println(dp[i][0]); } } public static void main(String[] args) { new Test().start(); } }
Java
["3\naaa", "2\nab", "4\nbabb", "7\nabacaba"]
2 seconds
["1", "3", "11", "589"]
NoteIn the first sample the population can never change since all bacteria are of the same type.In the second sample three configurations are possible: "ab" (no attacks), "aa" (the first colony conquers the second colony), and "bb" (the second colony conquers the first colony).To get the answer for the third sample, note that more than one attack can happen.
Java 8
standard input
[ "dp", "combinatorics", "string suffix structures", "brute force" ]
81ad3bb3d58a33016221d60a601790d4
The first line contains an integer n — the number of regions in the testtube (1 ≤ n ≤ 5 000). The second line contains n small Latin letters that describe the initial population of the testtube.
2,400
Print one number — the answer to the problem modulo 109 + 7.
standard output
PASSED
36a770bd2837909f38c386d49322e804
train_002.jsonl
1485108900
Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters "a", ..., "z".The testtube is divided into n consecutive regions. Each region is occupied by a single colony of a certain bacteria type at any given moment. Hence, the population of the testtube at any moment can be described by a string of n Latin characters.Sometimes a colony can decide to conquer another colony in one of the adjacent regions. When that happens, the attacked colony is immediately eliminated and replaced by a colony of the same type as the attacking colony, while the attacking colony keeps its type. Note that a colony can only attack its neighbours within the boundaries of the testtube. At any moment, at most one attack can take place.For example, consider a testtube with population "babb". There are six options for an attack that may happen next: the first colony attacks the second colony (1 → 2), the resulting population is "bbbb"; 2 → 1, the result is "aabb"; 2 → 3, the result is "baab"; 3 → 2, the result is "bbbb" (note that the result is the same as the first option); 3 → 4 or 4 → 3, the population does not change.The pattern of attacks is rather unpredictable. Julia is now wondering how many different configurations of bacteria in the testtube she can obtain after a sequence of attacks takes place (it is possible that no attacks will happen at all). Since this number can be large, find it modulo 109 + 7.
256 megabytes
import java.util.*; public class Test { static final int N = 5120; static final int L = 26; static final long M = 1000000007; long[][] dp = new long[N][32]; long[] prefix = new long[N]; long[] sum = new long[N]; int[] last = new int[26]; int n; Scanner sca = new Scanner(System.in); void start() { n = sca.nextInt(); char[] cs = sca.next().toCharArray(); for (int i = 1; i <= n; i++) { int ci = cs[i - 1] - 'a'; last[ci] = 0; for (int c = 0; c < L; c++) dp[i][c] = prefix[last[c]]; long cnt; Arrays.fill(last, 0); for (int j = 1; j < i; j++) { int c = cs[j - 1] - 'a'; last[c] = j; cnt = 0; for (c = 0; c < L; c++) cnt += prefix[last[c]]; sum[j] = cnt % M; } for (int j = 2; j < i; j++) prefix[j] = sum[j]; cnt = 1; for (int j = i; j > 1; j--) { dp[j - 1][ci] = 0; for (int c = 0; c < L; c++) cnt += dp[j - 1][c]; cnt += dp[i][ci]; } dp[i][ci] = cnt % M; dp[1][ci] = 1; for (int j = 2; j <= i; j++) { cnt = 0; for (int c = 0; c < L; c++) cnt += dp[j - 1][c]; dp[j][ci] = cnt % M; } cnt = 0; for (int c = 0; c < L; c++) cnt += dp[i][c]; last[ci] = i; prefix[i] = cnt % M; if (i == n) System.out.println(prefix[i]); } } public static void main(String[] args) { new Test().start(); } }
Java
["3\naaa", "2\nab", "4\nbabb", "7\nabacaba"]
2 seconds
["1", "3", "11", "589"]
NoteIn the first sample the population can never change since all bacteria are of the same type.In the second sample three configurations are possible: "ab" (no attacks), "aa" (the first colony conquers the second colony), and "bb" (the second colony conquers the first colony).To get the answer for the third sample, note that more than one attack can happen.
Java 8
standard input
[ "dp", "combinatorics", "string suffix structures", "brute force" ]
81ad3bb3d58a33016221d60a601790d4
The first line contains an integer n — the number of regions in the testtube (1 ≤ n ≤ 5 000). The second line contains n small Latin letters that describe the initial population of the testtube.
2,400
Print one number — the answer to the problem modulo 109 + 7.
standard output
PASSED
aa3c27e90440a4faf2df5cf56779a373
train_002.jsonl
1485108900
Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters "a", ..., "z".The testtube is divided into n consecutive regions. Each region is occupied by a single colony of a certain bacteria type at any given moment. Hence, the population of the testtube at any moment can be described by a string of n Latin characters.Sometimes a colony can decide to conquer another colony in one of the adjacent regions. When that happens, the attacked colony is immediately eliminated and replaced by a colony of the same type as the attacking colony, while the attacking colony keeps its type. Note that a colony can only attack its neighbours within the boundaries of the testtube. At any moment, at most one attack can take place.For example, consider a testtube with population "babb". There are six options for an attack that may happen next: the first colony attacks the second colony (1 → 2), the resulting population is "bbbb"; 2 → 1, the result is "aabb"; 2 → 3, the result is "baab"; 3 → 2, the result is "bbbb" (note that the result is the same as the first option); 3 → 4 or 4 → 3, the population does not change.The pattern of attacks is rather unpredictable. Julia is now wondering how many different configurations of bacteria in the testtube she can obtain after a sequence of attacks takes place (it is possible that no attacks will happen at all). Since this number can be large, find it modulo 109 + 7.
256 megabytes
import java.util.*; public class Test { static final int N = 5120; static final int L = 26; static final long M = 1000000007; long[] ps = new long[N], sum = new long[N]; int[] last = new int[32]; int n; Scanner sca = new Scanner(System.in); void start() { n = sca.nextInt(); char[] cs = sca.next().toCharArray(); ps[1] = 1; for (int i = 0; i < n; i++) { sum[0] = 0; for (int j = 1; j <= n; j++) sum[j] = sum[j - 1] + ps[j]; Arrays.fill(last, 0); for (int j = 1; j <= n; j++) { int ci = cs[j - 1] - 'a'; ps[j] = (sum[j] - sum[last[ci]]) % M; last[ci] = j; } } long cnt = 0; for (int i = 1; i <= n; i++) cnt += ps[i]; cnt %= M; System.out.println(cnt); } public static void main(String[] args) { new Test().start(); } }
Java
["3\naaa", "2\nab", "4\nbabb", "7\nabacaba"]
2 seconds
["1", "3", "11", "589"]
NoteIn the first sample the population can never change since all bacteria are of the same type.In the second sample three configurations are possible: "ab" (no attacks), "aa" (the first colony conquers the second colony), and "bb" (the second colony conquers the first colony).To get the answer for the third sample, note that more than one attack can happen.
Java 8
standard input
[ "dp", "combinatorics", "string suffix structures", "brute force" ]
81ad3bb3d58a33016221d60a601790d4
The first line contains an integer n — the number of regions in the testtube (1 ≤ n ≤ 5 000). The second line contains n small Latin letters that describe the initial population of the testtube.
2,400
Print one number — the answer to the problem modulo 109 + 7.
standard output
PASSED
6f209227fde2a29fce3ad05e4c3e6a59
train_002.jsonl
1485108900
Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters "a", ..., "z".The testtube is divided into n consecutive regions. Each region is occupied by a single colony of a certain bacteria type at any given moment. Hence, the population of the testtube at any moment can be described by a string of n Latin characters.Sometimes a colony can decide to conquer another colony in one of the adjacent regions. When that happens, the attacked colony is immediately eliminated and replaced by a colony of the same type as the attacking colony, while the attacking colony keeps its type. Note that a colony can only attack its neighbours within the boundaries of the testtube. At any moment, at most one attack can take place.For example, consider a testtube with population "babb". There are six options for an attack that may happen next: the first colony attacks the second colony (1 → 2), the resulting population is "bbbb"; 2 → 1, the result is "aabb"; 2 → 3, the result is "baab"; 3 → 2, the result is "bbbb" (note that the result is the same as the first option); 3 → 4 or 4 → 3, the population does not change.The pattern of attacks is rather unpredictable. Julia is now wondering how many different configurations of bacteria in the testtube she can obtain after a sequence of attacks takes place (it is possible that no attacks will happen at all). Since this number can be large, find it modulo 109 + 7.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.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 Egor Kulikov (egor@egork.net) */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); char[] seq = IOUtils.readCharArray(in, n); for (int i = 0; i < n; i++) { seq[i] -= 'a'; } long[][] result = new long[26][n + 1]; long[] total = new long[n + 1]; total[0] = 1; for (char c : seq) { long variants = 0; for (int j = 0; j <= n; j++) { long toAdd = total[j] - result[c][j]; total[j] += variants; if (total[j] >= MiscUtils.MOD7) { total[j] -= MiscUtils.MOD7; } variants += toAdd; if (variants < 0) { variants += MiscUtils.MOD7; } else if (variants >= MiscUtils.MOD7) { variants -= MiscUtils.MOD7; } result[c][j] += variants; if (result[c][j] >= MiscUtils.MOD7) { result[c][j] -= MiscUtils.MOD7; } } } out.printLine(total[n]); } } static class IOUtils { public static char[] readCharArray(InputReader in, int size) { char[] array = new char[size]; for (int i = 0; i < size; i++) { array[i] = in.readCharacter(); } return array; } } 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 printLine(long i) { writer.println(i); } } static class MiscUtils { public static final int MOD7 = (int) (1e9 + 7); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public char readCharacter() { int c = read(); while (isSpaceChar(c)) { c = read(); } return (char) c; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["3\naaa", "2\nab", "4\nbabb", "7\nabacaba"]
2 seconds
["1", "3", "11", "589"]
NoteIn the first sample the population can never change since all bacteria are of the same type.In the second sample three configurations are possible: "ab" (no attacks), "aa" (the first colony conquers the second colony), and "bb" (the second colony conquers the first colony).To get the answer for the third sample, note that more than one attack can happen.
Java 8
standard input
[ "dp", "combinatorics", "string suffix structures", "brute force" ]
81ad3bb3d58a33016221d60a601790d4
The first line contains an integer n — the number of regions in the testtube (1 ≤ n ≤ 5 000). The second line contains n small Latin letters that describe the initial population of the testtube.
2,400
Print one number — the answer to the problem modulo 109 + 7.
standard output
PASSED
55ed38568c94dcdeb8726db9f9fec722
train_002.jsonl
1485108900
Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters "a", ..., "z".The testtube is divided into n consecutive regions. Each region is occupied by a single colony of a certain bacteria type at any given moment. Hence, the population of the testtube at any moment can be described by a string of n Latin characters.Sometimes a colony can decide to conquer another colony in one of the adjacent regions. When that happens, the attacked colony is immediately eliminated and replaced by a colony of the same type as the attacking colony, while the attacking colony keeps its type. Note that a colony can only attack its neighbours within the boundaries of the testtube. At any moment, at most one attack can take place.For example, consider a testtube with population "babb". There are six options for an attack that may happen next: the first colony attacks the second colony (1 → 2), the resulting population is "bbbb"; 2 → 1, the result is "aabb"; 2 → 3, the result is "baab"; 3 → 2, the result is "bbbb" (note that the result is the same as the first option); 3 → 4 or 4 → 3, the population does not change.The pattern of attacks is rather unpredictable. Julia is now wondering how many different configurations of bacteria in the testtube she can obtain after a sequence of attacks takes place (it is possible that no attacks will happen at all). Since this number can be large, find it modulo 109 + 7.
256 megabytes
import java.io.*; import java.util.*; public class ProblemC { static int MOD = 1000000007; public static void main(String[] args) { // TODO Auto-generated method stub FastScanner input = new FastScanner(); int n = input.nextInt(); String in = input.next(); ArrayList<Character> charList = new ArrayList<Character>(); char prev = '`'; int[] idxLast = new int[26]; Arrays.fill(idxLast, -1); int[] idxLastArr = new int[n + 1]; Arrays.fill(idxLastArr, -1); for (int a = 0; a < n; a++) { if (in.charAt(a) != prev) { prev = in.charAt(a); charList.add(prev); idxLastArr[charList.size()] = idxLast[in.charAt(a) - 'a']; idxLast[in.charAt(a) - 'a'] = charList.size(); } } int[][][] dynamicProgrammingByChar = new int[27][27][n + 1]; int[][] dynamicSumByChar = new int[27][n + 1]; int[][] dynamicProgramming = new int[27][n + 1]; int[] dynamicSum = new int[n + 1]; dynamicProgramming[26][0] = 1; dynamicSum[0] = 1; for (int a = 0; a < charList.size(); a++) { int start = 0; // for (int q = 0; q < 27; q++) { // for(int d = 0; d < n+1; d++){ // dynamicSum[a+1][d] = dynamicSum[a][d]; // dynamicProgramming[q][a+1][d] = dynamicProgramming[q][a][d]; // } // } for (int c = 0; c < n + 1; c++) { dynamicSum[c] += start; dynamicSum[c] = dynamicSum[c] % MOD; dynamicProgramming[charList.get(a) - 'a'][c] += start; dynamicProgramming[charList.get(a) - 'a'][c] = dynamicProgramming[charList.get(a) - 'a'][c] % MOD; start += dynamicSum[c]; start = start % MOD; start -= dynamicProgramming[charList.get(a) - 'a'][c]; start = ((start % MOD) + MOD) % MOD; if(idxLastArr[a+1] != -1){ // start -= dynamicSum[idxLastArr[a+1]][c]; // start = ((start % MOD) + MOD) % MOD; // start += dynamicProgramming[charList.get(a)-'a'][idxLastArr[a+1]][c]; // start = start % MOD; ///////////////////////////// start -= dynamicSumByChar[charList.get(a)-'a'][c]; start = ((start % MOD) + MOD) % MOD; start += dynamicProgrammingByChar[charList.get(a)-'a'][charList.get(a)-'a'][c]; start = start % MOD; ///////////////////////////// } dynamicSumByChar[charList.get(a)-'a'][c] = dynamicSum[c]; dynamicProgrammingByChar[charList.get(a)-'a'][charList.get(a)-'a'][c] = dynamicProgramming[charList.get(a) - 'a'][c]; } } System.out.println(dynamicSum[n]); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(Reader in) { br = new BufferedReader(in); } public FastScanner() { this(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 readNextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readIntArray(int n) { int[] a = new int[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextInt(); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int idx = 0; idx < n; idx++) { a[idx] = nextLong(); } return a; } } }
Java
["3\naaa", "2\nab", "4\nbabb", "7\nabacaba"]
2 seconds
["1", "3", "11", "589"]
NoteIn the first sample the population can never change since all bacteria are of the same type.In the second sample three configurations are possible: "ab" (no attacks), "aa" (the first colony conquers the second colony), and "bb" (the second colony conquers the first colony).To get the answer for the third sample, note that more than one attack can happen.
Java 8
standard input
[ "dp", "combinatorics", "string suffix structures", "brute force" ]
81ad3bb3d58a33016221d60a601790d4
The first line contains an integer n — the number of regions in the testtube (1 ≤ n ≤ 5 000). The second line contains n small Latin letters that describe the initial population of the testtube.
2,400
Print one number — the answer to the problem modulo 109 + 7.
standard output
PASSED
a0a9d8947209797fd87670d172ee3da2
train_002.jsonl
1485108900
Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters "a", ..., "z".The testtube is divided into n consecutive regions. Each region is occupied by a single colony of a certain bacteria type at any given moment. Hence, the population of the testtube at any moment can be described by a string of n Latin characters.Sometimes a colony can decide to conquer another colony in one of the adjacent regions. When that happens, the attacked colony is immediately eliminated and replaced by a colony of the same type as the attacking colony, while the attacking colony keeps its type. Note that a colony can only attack its neighbours within the boundaries of the testtube. At any moment, at most one attack can take place.For example, consider a testtube with population "babb". There are six options for an attack that may happen next: the first colony attacks the second colony (1 → 2), the resulting population is "bbbb"; 2 → 1, the result is "aabb"; 2 → 3, the result is "baab"; 3 → 2, the result is "bbbb" (note that the result is the same as the first option); 3 → 4 or 4 → 3, the population does not change.The pattern of attacks is rather unpredictable. Julia is now wondering how many different configurations of bacteria in the testtube she can obtain after a sequence of attacks takes place (it is possible that no attacks will happen at all). Since this number can be large, find it modulo 109 + 7.
256 megabytes
import static java.lang.Double.parseDouble; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.System.exit; import static java.util.Arrays.fill; 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 D { static BufferedReader in; static PrintWriter out; static StringTokenizer tok; static final int MOD = 1000000007; static int add(int a, int b) { int res = a + b; if (res >= MOD) { res -= MOD; } return res; } static int sub(int a, int b) { int res = a - b; if (res < 0) { res += MOD; } return res; } static void solve() throws Exception { int n = nextInt(); char s[] = next().toCharArray(); int pos[] = new int[26]; fill(pos, -1); int ppos[] = new int[n]; for (int i = 0; i < n; i++) { ppos[i] = pos[s[i] - 'a']; pos[s[i] - 'a'] = i; } int vals[] = new int[n]; int sums[] = new int[n + 1]; vals[0] = 1; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { sums[j + 1] = add(sums[j], vals[j]); } for (int j = 0; j < n; j++) { vals[j] = sub(sums[j + 1], sums[ppos[j] + 1]); } } int ans = 0; for (int i = 0; i < n; i++) { ans = add(ans, vals[i]); } out.print(ans); } static int nextInt() throws IOException { return parseInt(next()); } static long nextLong() throws IOException { return parseLong(next()); } static double nextDouble() throws IOException { return parseDouble(next()); } static String next() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } 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(); exit(1); } } }
Java
["3\naaa", "2\nab", "4\nbabb", "7\nabacaba"]
2 seconds
["1", "3", "11", "589"]
NoteIn the first sample the population can never change since all bacteria are of the same type.In the second sample three configurations are possible: "ab" (no attacks), "aa" (the first colony conquers the second colony), and "bb" (the second colony conquers the first colony).To get the answer for the third sample, note that more than one attack can happen.
Java 8
standard input
[ "dp", "combinatorics", "string suffix structures", "brute force" ]
81ad3bb3d58a33016221d60a601790d4
The first line contains an integer n — the number of regions in the testtube (1 ≤ n ≤ 5 000). The second line contains n small Latin letters that describe the initial population of the testtube.
2,400
Print one number — the answer to the problem modulo 109 + 7.
standard output
PASSED
635c387388fb14b1b42914336ce5a686
train_002.jsonl
1485108900
Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters "a", ..., "z".The testtube is divided into n consecutive regions. Each region is occupied by a single colony of a certain bacteria type at any given moment. Hence, the population of the testtube at any moment can be described by a string of n Latin characters.Sometimes a colony can decide to conquer another colony in one of the adjacent regions. When that happens, the attacked colony is immediately eliminated and replaced by a colony of the same type as the attacking colony, while the attacking colony keeps its type. Note that a colony can only attack its neighbours within the boundaries of the testtube. At any moment, at most one attack can take place.For example, consider a testtube with population "babb". There are six options for an attack that may happen next: the first colony attacks the second colony (1 → 2), the resulting population is "bbbb"; 2 → 1, the result is "aabb"; 2 → 3, the result is "baab"; 3 → 2, the result is "bbbb" (note that the result is the same as the first option); 3 → 4 or 4 → 3, the population does not change.The pattern of attacks is rather unpredictable. Julia is now wondering how many different configurations of bacteria in the testtube she can obtain after a sequence of attacks takes place (it is possible that no attacks will happen at all). Since this number can be large, find it modulo 109 + 7.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { static PrintWriter out; static Reader in; public static void main(String[] args) throws IOException { //out = new PrintWriter(new File("out.txt")); //PrintWriter out = new PrintWriter(System.out); //in = new Reader(new FileInputStream("in.txt")); //Reader in = new Reader(); input_output(); Main solver = new Main(); solver.solve(); out.flush(); out.close(); } static int INF = (int)1e9; static int maxn = (int)1e5+5; static int mod = (int)1e9+7; static int n, m, q, k, t; void solve() throws IOException{ n = in.nextInt(); String s = in.next(); int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = s.charAt(i)-'a'+1; long[][] dp = new long[27][n+1]; dp[0][1] = 1; dp[arr[0]][1] = 1; for (int i = 1; i < n; i++) { if (arr[i] == arr[i-1]) continue; for (int j = 0; j < n; j++) { long res = 0; res = (dp[0][j]-dp[arr[i]][j]+mod)%mod; dp[0][j+1] = (dp[0][j+1]-dp[arr[i]][j+1]+mod)%mod; dp[arr[i]][j+1] = res; dp[0][j+1] = (dp[0][j+1]+dp[arr[i]][j+1])%mod; } if (dp[arr[i]][1] == 0) { dp[arr[i]][1] = 1; dp[0][1]++; } } long[] size = new long[n+1]; for (int i = 1; i <= n; i++) size[i] = dp[0][i]; long inverse[]=new long[n + 1]; inverse[0] = inverse[1] = 1; for (int i = 2; i <= n; i++) inverse[i] = inverse[mod % i] * (mod - mod / i) % mod; long[] fact = new long[n+1]; fact[0] = fact[1] = 1; for (int i = 2; i <= n; i++) { fact[i] = (fact[i-1]*i)%mod; inverse[i] = (inverse[i]*inverse[i-1])%mod; } long ans = 0; for (int i = 1; i <= n; i++) { size[i] = (size[i]*fact[n-1])%mod; size[i] = (size[i]*inverse[i-1])%mod; size[i] = (size[i]*inverse[n-i])%mod; ans = (ans+size[i])%mod; } out.println(ans); } //<> static class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public Reader() { this(System.in); } public Reader(InputStream is) { mIs = is; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = mIs.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } static void input_output() throws IOException { File f = new File("in.txt"); if(f.exists() && !f.isDirectory()) { in = new Reader(new FileInputStream("in.txt")); } else in = new Reader(); f = new File("out.txt"); if(f.exists() && !f.isDirectory()) { out = new PrintWriter(new File("out.txt")); } else out = new PrintWriter(System.out); } }
Java
["3\naaa", "2\nab", "4\nbabb", "7\nabacaba"]
2 seconds
["1", "3", "11", "589"]
NoteIn the first sample the population can never change since all bacteria are of the same type.In the second sample three configurations are possible: "ab" (no attacks), "aa" (the first colony conquers the second colony), and "bb" (the second colony conquers the first colony).To get the answer for the third sample, note that more than one attack can happen.
Java 8
standard input
[ "dp", "combinatorics", "string suffix structures", "brute force" ]
81ad3bb3d58a33016221d60a601790d4
The first line contains an integer n — the number of regions in the testtube (1 ≤ n ≤ 5 000). The second line contains n small Latin letters that describe the initial population of the testtube.
2,400
Print one number — the answer to the problem modulo 109 + 7.
standard output
PASSED
73798d112ce7615eeda185be43149f87
train_002.jsonl
1485108900
Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters "a", ..., "z".The testtube is divided into n consecutive regions. Each region is occupied by a single colony of a certain bacteria type at any given moment. Hence, the population of the testtube at any moment can be described by a string of n Latin characters.Sometimes a colony can decide to conquer another colony in one of the adjacent regions. When that happens, the attacked colony is immediately eliminated and replaced by a colony of the same type as the attacking colony, while the attacking colony keeps its type. Note that a colony can only attack its neighbours within the boundaries of the testtube. At any moment, at most one attack can take place.For example, consider a testtube with population "babb". There are six options for an attack that may happen next: the first colony attacks the second colony (1 → 2), the resulting population is "bbbb"; 2 → 1, the result is "aabb"; 2 → 3, the result is "baab"; 3 → 2, the result is "bbbb" (note that the result is the same as the first option); 3 → 4 or 4 → 3, the population does not change.The pattern of attacks is rather unpredictable. Julia is now wondering how many different configurations of bacteria in the testtube she can obtain after a sequence of attacks takes place (it is possible that no attacks will happen at all). Since this number can be large, find it modulo 109 + 7.
256 megabytes
import java.util.*; import java.io.*; public class D { int MOD = 1_000_000_007; void solve() { int initN = in.nextInt(); String s = in.nextToken(); String t = ""; for (int i = 0; i < s.length(); i++) { if (i == 0 || s.charAt(i) != s.charAt(i - 1)) { t += s.charAt(i); } } s = t; int n = s.length(); int[] last = new int[26]; Arrays.fill(last, -1); int[] prev = new int[n]; for (int i = 0; i < n; i++) { prev[i] = last[s.charAt(i) - 'a']; last[s.charAt(i) - 'a'] = i; } int[][] dp = new int[n + 1][n + 1]; int[] sum = new int[n + 1]; dp[0][0] = 1; sum[0] = 1; for (int i = 0; i < n; i++) { for (int j = 1; j <= n; j++) { if (prev[i] != -1) { dp[i + 1][j] = sum[j - 1] - dp[prev[i] + 1][j - 1]; if (dp[i + 1][j] < 0) { dp[i + 1][j] += MOD; } } else { dp[i + 1][j] = sum[j - 1]; } } for (int j = 0; j <= n; j++) { if (prev[i] != -1) { sum[j] += dp[i + 1][j] - dp[prev[i] + 1][j]; if (sum[j] >= MOD) { sum[j] -= MOD; } if (sum[j] < 0) { sum[j] += MOD; } } else { sum[j] += dp[i + 1][j]; if (sum[j] >= MOD) { sum[j] -= MOD; } } } } int[] choose = new int[initN + 1]; int[] tmp = new int[initN + 1]; choose[0] = 1; for (int i = 1; i < initN; i++) { tmp[0] = 1; for (int j = 1; j <= i; j++) { tmp[j] = choose[j - 1] + choose[j]; if (tmp[j] >= MOD) { tmp[j] -= MOD; } } System.arraycopy(tmp, 0, choose, 0, choose.length); } long result = 0; for (int cnt = 1; cnt <= n; cnt++) { result += 1L * sum[cnt] * choose[cnt - 1] % MOD; // choose (initN - 1, cnt - 1) } out.println(result % MOD); } FastScanner in; PrintWriter out; void run() { in = new FastScanner(); out = new PrintWriter(System.out); solve(); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } public static void main(String[] args) { new D().run(); } }
Java
["3\naaa", "2\nab", "4\nbabb", "7\nabacaba"]
2 seconds
["1", "3", "11", "589"]
NoteIn the first sample the population can never change since all bacteria are of the same type.In the second sample three configurations are possible: "ab" (no attacks), "aa" (the first colony conquers the second colony), and "bb" (the second colony conquers the first colony).To get the answer for the third sample, note that more than one attack can happen.
Java 8
standard input
[ "dp", "combinatorics", "string suffix structures", "brute force" ]
81ad3bb3d58a33016221d60a601790d4
The first line contains an integer n — the number of regions in the testtube (1 ≤ n ≤ 5 000). The second line contains n small Latin letters that describe the initial population of the testtube.
2,400
Print one number — the answer to the problem modulo 109 + 7.
standard output
PASSED
ffd966f2779275ce1185adeafb047ae3
train_002.jsonl
1485108900
Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters "a", ..., "z".The testtube is divided into n consecutive regions. Each region is occupied by a single colony of a certain bacteria type at any given moment. Hence, the population of the testtube at any moment can be described by a string of n Latin characters.Sometimes a colony can decide to conquer another colony in one of the adjacent regions. When that happens, the attacked colony is immediately eliminated and replaced by a colony of the same type as the attacking colony, while the attacking colony keeps its type. Note that a colony can only attack its neighbours within the boundaries of the testtube. At any moment, at most one attack can take place.For example, consider a testtube with population "babb". There are six options for an attack that may happen next: the first colony attacks the second colony (1 → 2), the resulting population is "bbbb"; 2 → 1, the result is "aabb"; 2 → 3, the result is "baab"; 3 → 2, the result is "bbbb" (note that the result is the same as the first option); 3 → 4 or 4 → 3, the population does not change.The pattern of attacks is rather unpredictable. Julia is now wondering how many different configurations of bacteria in the testtube she can obtain after a sequence of attacks takes place (it is possible that no attacks will happen at all). Since this number can be large, find it modulo 109 + 7.
256 megabytes
//package eightvc.f; 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 D2 { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int mod = 1000000007; int n = ni(); char[] s = ns(n); int[][] bucket = new int[26][n+1]; boolean[] aped = new boolean[26]; int[] cum = new int[n+1]; for(int i = 0;i < n;i++){ int ind = s[i]-'a'; for(int len = i;len >= 0;len--){ int v = cum[len]; if(!aped[ind] && len == 0){ v++; aped[ind] = true; }else{ v += mod - bucket[ind][len]; } if(v >= mod)v -= mod; cum[len+1] += v; if(cum[len+1] >= mod)cum[len+1] -= mod; bucket[ind][len+1] = cum[len+1]; } } int[][] fif = enumFIF(20000, mod); long ret = 0; for(int i = 1;i <= n;i++){ ret += cum[i]*C(n-1, i-1, mod, fif)%mod; } out.println(ret%mod); } public static int[][] enumFIF(int n, int mod) { int[] f = new int[n + 1]; int[] invf = new int[n + 1]; f[0] = 1; for (int i = 1; i <= n; i++) { f[i] = (int) ((long) f[i - 1] * i % mod); } long a = f[n]; long b = mod; long p = 1, q = 0; while (b > 0) { long c = a / b; long d; d = a; a = b; b = d % b; d = p; p = q; q = d - c * q; } invf[n] = (int) (p < 0 ? p + mod : p); for (int i = n - 1; i >= 0; i--) { invf[i] = (int) ((long) invf[i + 1] * (i + 1) % mod); } return new int[][] { f, invf }; } public static long C(int n, int r, int mod, int[][] fif) { if (n < 0 || r < 0 || r > n) return 0; return (long) fif[0][n] * fif[1][r] % mod * fif[1][n - r] % mod; } 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 D2().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\naaa", "2\nab", "4\nbabb", "7\nabacaba"]
2 seconds
["1", "3", "11", "589"]
NoteIn the first sample the population can never change since all bacteria are of the same type.In the second sample three configurations are possible: "ab" (no attacks), "aa" (the first colony conquers the second colony), and "bb" (the second colony conquers the first colony).To get the answer for the third sample, note that more than one attack can happen.
Java 8
standard input
[ "dp", "combinatorics", "string suffix structures", "brute force" ]
81ad3bb3d58a33016221d60a601790d4
The first line contains an integer n — the number of regions in the testtube (1 ≤ n ≤ 5 000). The second line contains n small Latin letters that describe the initial population of the testtube.
2,400
Print one number — the answer to the problem modulo 109 + 7.
standard output
PASSED
c243dc0d6a39b194f9674e7b292e3a86
train_002.jsonl
1485108900
Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters "a", ..., "z".The testtube is divided into n consecutive regions. Each region is occupied by a single colony of a certain bacteria type at any given moment. Hence, the population of the testtube at any moment can be described by a string of n Latin characters.Sometimes a colony can decide to conquer another colony in one of the adjacent regions. When that happens, the attacked colony is immediately eliminated and replaced by a colony of the same type as the attacking colony, while the attacking colony keeps its type. Note that a colony can only attack its neighbours within the boundaries of the testtube. At any moment, at most one attack can take place.For example, consider a testtube with population "babb". There are six options for an attack that may happen next: the first colony attacks the second colony (1 → 2), the resulting population is "bbbb"; 2 → 1, the result is "aabb"; 2 → 3, the result is "baab"; 3 → 2, the result is "bbbb" (note that the result is the same as the first option); 3 → 4 or 4 → 3, the population does not change.The pattern of attacks is rather unpredictable. Julia is now wondering how many different configurations of bacteria in the testtube she can obtain after a sequence of attacks takes place (it is possible that no attacks will happen at all). Since this number can be large, find it modulo 109 + 7.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public long[] fact; public long[] invfact; public int mod = 1000000007; public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); char[] s = in.next().toCharArray(); ArrayList<Character> arr = new ArrayList<>(); for (int i = 0; i < s.length; i++) { if (i == 0 || (s[i] != s[i - 1])) { arr.add(s[i]); } } char[] k = new char[arr.size()]; for (int i = 0; i < arr.size(); i++) { k[i] = arr.get(i); } String dd = new String(k); int w = dd.length(); int[][] last = new int[w + 1][26]; Arrays.fill(last[0], -1); for (int i = 1; i <= w; i++) { last[i] = Arrays.copyOf(last[i - 1], 26); last[i][dd.charAt(i - 1) - 'a'] = i; } long[][] dp = new long[w + 1][w + 1]; // [i][j] -> number of distinct subsequences of [1..i] of length j for (int i = 0; i <= w; i++) dp[i][0] = 1; for (int length = 1; length <= w; length++) { for (int i = 1; i <= w; i++) { dp[i][length] = (dp[i - 1][length] + dp[i - 1][length - 1]); if (dp[i][length] >= mod) dp[i][length] -= mod; int q = last[i - 1][dd.charAt(i - 1) - 'a']; if (q != -1) { dp[i][length] += (mod - dp[q][length - 1]); if (dp[i][length] >= mod) dp[i][length] -= mod; } } } long[][] x = Factorials.getFIF(10000, mod); fact = x[0]; invfact = x[1]; long ret = 0; for (int length = 1; length <= dd.length(); length++) { ret = (ret + dp[w][length] * comb(n - 1, length - 1)) % mod; } out.println(ret); } public long comb(int n, int k) { if (k < 0 || k > n) return 0; return fact[n] * invfact[k] % mod * invfact[n - k] % mod; } } static class Factorials { public static long[][] getFIF(int max, int mod) { long[] fact = new long[max]; long[] ifact = new long[max]; long[] inv = new long[max]; inv[1] = 1; for (int i = 2; i < max; i++) { inv[i] = (mod - mod / i) * inv[mod % i] % mod; } fact[0] = 1; ifact[0] = 1; for (int i = 1; i < max; i++) { fact[i] = fact[i - 1] * i % mod; ifact[i] = ifact[i - 1] * inv[i] % mod; } return new long[][]{fact, ifact, inv}; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(long i) { writer.println(i); } } static class InputReader { 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\naaa", "2\nab", "4\nbabb", "7\nabacaba"]
2 seconds
["1", "3", "11", "589"]
NoteIn the first sample the population can never change since all bacteria are of the same type.In the second sample three configurations are possible: "ab" (no attacks), "aa" (the first colony conquers the second colony), and "bb" (the second colony conquers the first colony).To get the answer for the third sample, note that more than one attack can happen.
Java 8
standard input
[ "dp", "combinatorics", "string suffix structures", "brute force" ]
81ad3bb3d58a33016221d60a601790d4
The first line contains an integer n — the number of regions in the testtube (1 ≤ n ≤ 5 000). The second line contains n small Latin letters that describe the initial population of the testtube.
2,400
Print one number — the answer to the problem modulo 109 + 7.
standard output
PASSED
a730c26d3615594041fd375fc02b9cfe
train_002.jsonl
1485108900
Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters "a", ..., "z".The testtube is divided into n consecutive regions. Each region is occupied by a single colony of a certain bacteria type at any given moment. Hence, the population of the testtube at any moment can be described by a string of n Latin characters.Sometimes a colony can decide to conquer another colony in one of the adjacent regions. When that happens, the attacked colony is immediately eliminated and replaced by a colony of the same type as the attacking colony, while the attacking colony keeps its type. Note that a colony can only attack its neighbours within the boundaries of the testtube. At any moment, at most one attack can take place.For example, consider a testtube with population "babb". There are six options for an attack that may happen next: the first colony attacks the second colony (1 → 2), the resulting population is "bbbb"; 2 → 1, the result is "aabb"; 2 → 3, the result is "baab"; 3 → 2, the result is "bbbb" (note that the result is the same as the first option); 3 → 4 or 4 → 3, the population does not change.The pattern of attacks is rather unpredictable. Julia is now wondering how many different configurations of bacteria in the testtube she can obtain after a sequence of attacks takes place (it is possible that no attacks will happen at all). Since this number can be large, find it modulo 109 + 7.
256 megabytes
import java.io.*; import java.util.*; public class D { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; void test(int n) { char from = 'a'; char to = (char) (from + n - 1); StringBuilder sb = new StringBuilder(); for (char c = from; c <= to; c++) { sb.append(c); } String s = sb.toString(); HashSet<String> seen = new HashSet<>(); seen.add(s); ArrayDeque<String> q = new ArrayDeque<>(); q.add(s); while (!q.isEmpty()) { s = q.poll(); out.println(s); for (int i = 0; i + 1 < n; i++) { String t = morph(s, i, i + 1); if (!seen.contains(t)) { seen.add(t); q.add(t); } t = morph(s, i + 1, i); if (!seen.contains(t)) { seen.add(t); q.add(t); } } } out.println(seen.size()); } String morph(String s, int from, int to) { char[] buf = s.toCharArray(); buf[to] = buf[from]; return new String(buf); } static final int ALPH = 26; static final int P = 1_000_000_007; void solve() throws IOException { int n = nextInt(); String s = nextToken(); int[][] pref = new int[n + 1][n + 1]; // pos, length pref[0][0] = 1; int[] last = new int[ALPH]; Arrays.fill(last, -1); for (int i = 0; i < n; i++) { int idx = s.charAt(i) - 'a'; int prev = last[idx]; for (int len = 1; len <= i + 1; len++) { int delta = pref[i][len - 1]; if (prev != -1) { delta -= pref[prev + 1][len - 1]; if (delta < 0) { delta += P; } } pref[i + 1][len] = pref[i][len] + delta; if (pref[i + 1][len] >= P) { pref[i + 1][len] -= P; } } pref[i + 1][0] = 1; last[idx] = i; } // System.err.println(Arrays.toString(pref[n])); int[] inv = new int[n + 2]; inv[0] = 0; inv[1] = 1; for (int i = 2; i < inv.length; i++) { inv[i] = P - (int) ((long) (P / i) * inv[P % i] % P); } // HINT: p % x = p - (p / x) * x // here '/' stands for integer division int ans = 0; int coef = 1; for (int k = 1; k <= n; k++) { ans += (int)((long)pref[n][k] * coef % P); if (ans >= P) { ans -= P; } coef = (int)((long)coef * inv[k] % P * (n - k) % P); } out.println(ans); } D() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); // test(6); out.close(); } public static void main(String[] args) throws IOException { new D(); } String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["3\naaa", "2\nab", "4\nbabb", "7\nabacaba"]
2 seconds
["1", "3", "11", "589"]
NoteIn the first sample the population can never change since all bacteria are of the same type.In the second sample three configurations are possible: "ab" (no attacks), "aa" (the first colony conquers the second colony), and "bb" (the second colony conquers the first colony).To get the answer for the third sample, note that more than one attack can happen.
Java 8
standard input
[ "dp", "combinatorics", "string suffix structures", "brute force" ]
81ad3bb3d58a33016221d60a601790d4
The first line contains an integer n — the number of regions in the testtube (1 ≤ n ≤ 5 000). The second line contains n small Latin letters that describe the initial population of the testtube.
2,400
Print one number — the answer to the problem modulo 109 + 7.
standard output
PASSED
f53749dd94452c313b6337520d199fd0
train_002.jsonl
1597415700
You are given three multisets of pairs of colored sticks: $$$R$$$ pairs of red sticks, the first pair has length $$$r_1$$$, the second pair has length $$$r_2$$$, $$$\dots$$$, the $$$R$$$-th pair has length $$$r_R$$$; $$$G$$$ pairs of green sticks, the first pair has length $$$g_1$$$, the second pair has length $$$g_2$$$, $$$\dots$$$, the $$$G$$$-th pair has length $$$g_G$$$; $$$B$$$ pairs of blue sticks, the first pair has length $$$b_1$$$, the second pair has length $$$b_2$$$, $$$\dots$$$, the $$$B$$$-th pair has length $$$b_B$$$; You are constructing rectangles from these pairs of sticks with the following process: take a pair of sticks of one color; take a pair of sticks of another color different from the first one; add the area of the resulting rectangle to the total area. Thus, you get such rectangles that their opposite sides are the same color and their adjacent sides are not the same color.Each pair of sticks can be used at most once, some pairs can be left unused. You are not allowed to split a pair into independent sticks.What is the maximum area you can achieve?
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.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; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { static int numsR[]; static int numsG[]; static int numsB[]; static long dp[][][]; public void solve(int testNumber, Scanner in, PrintWriter out) { int R = in.nextInt(), G = in.nextInt(), B = in.nextInt(); numsR = CPUtils.readIntArray(R, in); numsG = CPUtils.readIntArray(G, in); numsB = CPUtils.readIntArray(B, in); Arrays.sort(numsR); Arrays.sort(numsG); Arrays.sort(numsB); dp = new long[200 + 2][200 + 2][200 + 2]; for (int rIdx = 0; rIdx <= R; rIdx++) { for (int gIdx = 0; gIdx <= G; gIdx++) { for (int bIdx = 0; bIdx <= B; bIdx++) { if (rIdx > 0 && gIdx > 0) dp[rIdx][gIdx][bIdx] = Math.max(dp[rIdx][gIdx][bIdx], numsR[rIdx - 1] * numsG[gIdx - 1] + dp[rIdx - 1][gIdx - 1][bIdx]); if (bIdx > 0 && gIdx > 0) dp[rIdx][gIdx][bIdx] = Math.max(dp[rIdx][gIdx][bIdx], numsG[gIdx - 1] * numsB[bIdx - 1] + dp[rIdx][gIdx - 1][bIdx - 1]); if (rIdx > 0 && bIdx > 0) dp[rIdx][gIdx][bIdx] = Math.max(dp[rIdx][gIdx][bIdx], numsR[rIdx - 1] * numsB[bIdx - 1] + dp[rIdx - 1][gIdx][bIdx - 1]); } } } out.print(dp[R][G][B]); } } static class CPUtils { public static int[] readIntArray(int size, Scanner in) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = in.nextInt(); } return array; } } }
Java
["1 1 1\n3\n5\n4", "2 1 3\n9 5\n1\n2 8 5", "10 1 1\n11 7 20 15 19 14 2 4 13 14\n8\n11"]
2 seconds
["20", "99", "372"]
NoteIn the first example you can construct one of these rectangles: red and green with sides $$$3$$$ and $$$5$$$, red and blue with sides $$$3$$$ and $$$4$$$ and green and blue with sides $$$5$$$ and $$$4$$$. The best area of them is $$$4 \times 5 = 20$$$.In the second example the best rectangles are: red/blue $$$9 \times 8$$$, red/blue $$$5 \times 5$$$, green/blue $$$2 \times 1$$$. So the total area is $$$72 + 25 + 2 = 99$$$.In the third example the best rectangles are: red/green $$$19 \times 8$$$ and red/blue $$$20 \times 11$$$. The total area is $$$152 + 220 = 372$$$. Note that you can't construct more rectangles because you are not allowed to have both pairs taken to be the same color.
Java 8
standard input
[ "dp", "sortings", "greedy" ]
9e6cb1e8037e1d35b6c6fe43f805a22f
The first line contains three integers $$$R$$$, $$$G$$$, $$$B$$$ ($$$1 \le R, G, B \le 200$$$) — the number of pairs of red sticks, the number of pairs of green sticks and the number of pairs of blue sticks. The second line contains $$$R$$$ integers $$$r_1, r_2, \dots, r_R$$$ ($$$1 \le r_i \le 2000$$$) — the lengths of sticks in each pair of red sticks. The third line contains $$$G$$$ integers $$$g_1, g_2, \dots, g_G$$$ ($$$1 \le g_i \le 2000$$$) — the lengths of sticks in each pair of green sticks. The fourth line contains $$$B$$$ integers $$$b_1, b_2, \dots, b_B$$$ ($$$1 \le b_i \le 2000$$$) — the lengths of sticks in each pair of blue sticks.
1,800
Print the maximum possible total area of the constructed rectangles.
standard output
PASSED
68af32c8d6e040e8f81a796b338bb0af
train_002.jsonl
1597415700
You are given three multisets of pairs of colored sticks: $$$R$$$ pairs of red sticks, the first pair has length $$$r_1$$$, the second pair has length $$$r_2$$$, $$$\dots$$$, the $$$R$$$-th pair has length $$$r_R$$$; $$$G$$$ pairs of green sticks, the first pair has length $$$g_1$$$, the second pair has length $$$g_2$$$, $$$\dots$$$, the $$$G$$$-th pair has length $$$g_G$$$; $$$B$$$ pairs of blue sticks, the first pair has length $$$b_1$$$, the second pair has length $$$b_2$$$, $$$\dots$$$, the $$$B$$$-th pair has length $$$b_B$$$; You are constructing rectangles from these pairs of sticks with the following process: take a pair of sticks of one color; take a pair of sticks of another color different from the first one; add the area of the resulting rectangle to the total area. Thus, you get such rectangles that their opposite sides are the same color and their adjacent sides are not the same color.Each pair of sticks can be used at most once, some pairs can be left unused. You are not allowed to split a pair into independent sticks.What is the maximum area you can achieve?
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class D { private static FastReader fr; private static OutputStream out; private static int mod = (int)(1e9+7); public static long[] red, green, blue; public static long dp[][][]; private void solve() { int r = fr.nextInt(); int g = fr.nextInt(); int b = fr.nextInt(); red = nextArray(r); green = nextArray(g); blue = nextArray(b); Arrays.sort(red); Arrays.sort(green); Arrays.sort(blue); // printArray(blue); dp = new long[r][g][b]; long ans = recursion(r-1, g-1, b-1); println(ans); } private static long recursion(int r, int g, int b) { int count = (r == -1 ? 1 : 0) + (g == -1 ? 1 : 0) + (b == -1 ? 1 : 0); if(count >= 2) { return 0L; }else if(r == -1) { return green[g] * blue[b] + recursion(r, g-1, b-1); }else if(g == -1) { return red[r] * blue[b] + recursion(r -1, g, b-1); }else if(b == -1) { return red[r] * green[g] + recursion(r-1, g-1, b); } if(dp[r][g][b] != 0) { return dp[r][g][b]; } long ans = 0; if(r >= 0 && g >= 0) { ans = Math.max(red[r] * green[g] + recursion(r-1, g-1, b), ans); } if(r >= 0 && b >= 0) { ans = Math.max(red[r] * blue[b] + recursion(r -1, g, b-1), ans); } if(g >= 0 && b >= 0) { ans = Math.max(green[g] * blue[b] + recursion(r, g-1, b-1), ans); } dp[r][g][b] = ans; // println(ans); return ans; } private static void printArray(long arr[]) { for(long val : arr) { print(val + " "); } println(); } private static long[] nextArray(int n) { long temp[] = new long[n]; for(int i=0;i<n;i++) { temp[i] = fr.nextLong(); } return temp; } private static int modInverse(int a) { int m0 = mod; int y = 0, x = 1; if (mod == 1) return 0; while (a > 1) { int q = (int)(a / mod); int t = mod; mod = a % mod; a = t; t = y; y = x - q * y; x = t; } if (x < 0) x += m0; return x; } public static void main(String args[]) throws IOException{ new D().run(); } private ArrayList<Integer> factors(int n, boolean include){ ArrayList<Integer> factors = new ArrayList<>(); if(n < 0) return factors; if(include) { factors.add(1); if(n > 1) factors.add(n); } int i = 2; for(;i*i<n;i++) { if(n % i == 0) { factors.add(i); factors.add(n / i); } } if(i * i == n) { factors.add(i); } return factors; } private ArrayList<Integer> PrimeFactors(int n) { ArrayList<Integer> primes = new ArrayList<>(); int i = 2; while (i * i <= n) { if (n % i == 0) { primes.add(i); n /= i; while (n % i == 0) { primes.add(i); n /= i; } } i++; } if(n > 1) primes.add(i); return primes; } private boolean isPrime(int n) { if(n == 0 || n == 1) { return false; } if(n % 2 == 0) { return false; } for(int i=3;i*i<=n;i+=2) { if(n % i == 0) { return false; } } return true; } private ArrayList<Integer> Sieve(int n){ boolean bool[] = new boolean[n+1]; Arrays.fill(bool, true); bool[0] = bool[1] = false; for(int i=2;i*i<=n;i++) { if(bool[i]) { int j = 2; while(i*j <= n) { bool[i*j] = false; j++; } } } ArrayList<Integer> primes = new ArrayList<>(); for(int i=2;i<=n;i++) { if(bool[i]) primes.add(i); } return primes; } private HashMap<Integer, Integer> addToHashMap(HashMap<Integer, Integer> map, int arr[]){ for(int val: arr) { if(!map.containsKey(val)) { map.put(val, 1); }else { map.put(val, map.get(val) + 1); } } return map; } private int factorial(int n) { long fac = 1; for(int i=2;i<=n;i++) { fac *= i; fac %= mod; } return (int)(fac % mod); } // private static int pow(int base,int exp){ // if(exp == 0){ // return 1; // }else if(exp == 1){ // return base; // } // int a = pow(base,exp/2); // a = ((a % mod) * (a % mod)) % mod; // if(exp % 2 == 1) { // a = ((a % mod) * (base % mod)); // } // return a; // } private static int gcd(int a,int b){ if(a == 0){ return b; } return gcd(b%a,a); } private static int lcm(int a,int b){ return (a * b)/gcd(a,b); } private void run() throws IOException{ fr = new FastReader(); out = new BufferedOutputStream(System.out); solve(); out.flush(); out.close(); } private static class FastReader{ private static BufferedReader br; private static StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedOutputStream(System.out); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public char[] nextCharArray() { return next().toCharArray(); } public int[] nextIntArray(int n) { int arr[] = new int[n]; for(int i=0;i<n;i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long arr[] = new long[n]; for(int i=0;i<n;i++) { arr[i] = nextLong(); } return arr; } public String[] nextStringArray(int n) { String arr[] = new String[n]; for(int i=0;i<n;i++) { arr[i] = next(); } return arr; } } public static void print(Object str) { try { out.write(str.toString().getBytes()); } catch (IOException e) { e.printStackTrace(); } } public static void println(Object str) { try { out.write((str.toString() + "\n").getBytes()); } catch (IOException e) { e.printStackTrace(); } } public static void println() { println(""); } public static void printArray(Object str[]){ for(Object s : str) { try { out.write(str.toString().getBytes()); } catch (IOException e) { e.printStackTrace(); } } } }
Java
["1 1 1\n3\n5\n4", "2 1 3\n9 5\n1\n2 8 5", "10 1 1\n11 7 20 15 19 14 2 4 13 14\n8\n11"]
2 seconds
["20", "99", "372"]
NoteIn the first example you can construct one of these rectangles: red and green with sides $$$3$$$ and $$$5$$$, red and blue with sides $$$3$$$ and $$$4$$$ and green and blue with sides $$$5$$$ and $$$4$$$. The best area of them is $$$4 \times 5 = 20$$$.In the second example the best rectangles are: red/blue $$$9 \times 8$$$, red/blue $$$5 \times 5$$$, green/blue $$$2 \times 1$$$. So the total area is $$$72 + 25 + 2 = 99$$$.In the third example the best rectangles are: red/green $$$19 \times 8$$$ and red/blue $$$20 \times 11$$$. The total area is $$$152 + 220 = 372$$$. Note that you can't construct more rectangles because you are not allowed to have both pairs taken to be the same color.
Java 8
standard input
[ "dp", "sortings", "greedy" ]
9e6cb1e8037e1d35b6c6fe43f805a22f
The first line contains three integers $$$R$$$, $$$G$$$, $$$B$$$ ($$$1 \le R, G, B \le 200$$$) — the number of pairs of red sticks, the number of pairs of green sticks and the number of pairs of blue sticks. The second line contains $$$R$$$ integers $$$r_1, r_2, \dots, r_R$$$ ($$$1 \le r_i \le 2000$$$) — the lengths of sticks in each pair of red sticks. The third line contains $$$G$$$ integers $$$g_1, g_2, \dots, g_G$$$ ($$$1 \le g_i \le 2000$$$) — the lengths of sticks in each pair of green sticks. The fourth line contains $$$B$$$ integers $$$b_1, b_2, \dots, b_B$$$ ($$$1 \le b_i \le 2000$$$) — the lengths of sticks in each pair of blue sticks.
1,800
Print the maximum possible total area of the constructed rectangles.
standard output
PASSED
ceba52c28fa0d4ad613f866a6a5edff3
train_002.jsonl
1597415700
You are given three multisets of pairs of colored sticks: $$$R$$$ pairs of red sticks, the first pair has length $$$r_1$$$, the second pair has length $$$r_2$$$, $$$\dots$$$, the $$$R$$$-th pair has length $$$r_R$$$; $$$G$$$ pairs of green sticks, the first pair has length $$$g_1$$$, the second pair has length $$$g_2$$$, $$$\dots$$$, the $$$G$$$-th pair has length $$$g_G$$$; $$$B$$$ pairs of blue sticks, the first pair has length $$$b_1$$$, the second pair has length $$$b_2$$$, $$$\dots$$$, the $$$B$$$-th pair has length $$$b_B$$$; You are constructing rectangles from these pairs of sticks with the following process: take a pair of sticks of one color; take a pair of sticks of another color different from the first one; add the area of the resulting rectangle to the total area. Thus, you get such rectangles that their opposite sides are the same color and their adjacent sides are not the same color.Each pair of sticks can be used at most once, some pairs can be left unused. You are not allowed to split a pair into independent sticks.What is the maximum area you can achieve?
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ 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.Collections; import java.util.PriorityQueue; import java.util.StringTokenizer; /** * * @Author: linhd * @Created on: Aug 5, 2020 9:22:07 PM */ public class D { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); Task solver = new Task(); solver.solve(in, out); out.close(); } private static class InputReader { BufferedReader bf; StringTokenizer st; public InputReader(InputStream in) { bf = new BufferedReader(new InputStreamReader(in)); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(bf.readLine()); } catch (IOException ex) { } } return st.nextToken(); } public char nextChar() { return next().charAt(0); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { try { return bf.readLine(); } catch (IOException ex) { } return null; } } private static class PI implements Comparable<PI> { int first; int second; public PI(int f, int s) { this.first = f; this.second = s; } @Override public int compareTo(PI o) { return first == o.first ? second - o.second : first - o.first; } } private static class Pair<T, E> implements Comparable<Pair<T, E>> { T first; E second; public Pair(T first, E second) { this.first = first; this.second = second; } @Override public int compareTo(Pair<T, E> o) { int c = ((Comparable<T>) first).compareTo(o.first); return c; // return c == 0 ? ((Comparable<E>) second).compareTo(o.second) : c; } } private static class Node implements Comparable<Node> { long w; int i; private Node(long l, int i) { this.w = l; this.i = i; } @Override public int compareTo(Node o) { long cmp = o.w - w; if (cmp < 0) { return -1; } else if (cmp > 0) { return 1; } return 0; } public String toString() { return w + " " + i; } } private static class Task { public void solve(InputReader in, PrintWriter out) { int nR = in.nextInt(), nG = in.nextInt(), nB = in.nextInt(); ArrayList<Integer> r = new ArrayList<>(); ArrayList<Integer> g = new ArrayList<>(); ArrayList<Integer> b = new ArrayList<>(); for (int i = 0; i < nR; ++i) r.add(in.nextInt()); for (int i = 0; i < nG; ++i) g.add(in.nextInt()); for (int i = 0; i < nB; ++i) b.add(in.nextInt()); Collections.sort(r); Collections.sort(g); Collections.sort(b); int[][][] f = new int [nR + 1][nG + 1][nB + 1]; for (int i = 0; i <= nR; ++i) for (int j = 0; j <= nG; ++j) for (int k = 0; k <= nB; ++k) { if (i > 0 && j > 0) f[i][j][k] = Math.max(f[i][j][k], f[i - 1][j - 1][k] + r.get(i - 1) * g.get(j - 1)); if (i > 0 && k > 0) f[i][j][k] = Math.max(f[i][j][k], f[i - 1][j][k - 1] + r.get(i - 1) * b.get(k - 1)); if (k > 0 && j > 0) f[i][j][k] = Math.max(f[i][j][k], f[i][j - 1][k - 1] + g.get(j - 1) * b.get(k - 1)); } out.print(f[nR][nG][nB]); } } }
Java
["1 1 1\n3\n5\n4", "2 1 3\n9 5\n1\n2 8 5", "10 1 1\n11 7 20 15 19 14 2 4 13 14\n8\n11"]
2 seconds
["20", "99", "372"]
NoteIn the first example you can construct one of these rectangles: red and green with sides $$$3$$$ and $$$5$$$, red and blue with sides $$$3$$$ and $$$4$$$ and green and blue with sides $$$5$$$ and $$$4$$$. The best area of them is $$$4 \times 5 = 20$$$.In the second example the best rectangles are: red/blue $$$9 \times 8$$$, red/blue $$$5 \times 5$$$, green/blue $$$2 \times 1$$$. So the total area is $$$72 + 25 + 2 = 99$$$.In the third example the best rectangles are: red/green $$$19 \times 8$$$ and red/blue $$$20 \times 11$$$. The total area is $$$152 + 220 = 372$$$. Note that you can't construct more rectangles because you are not allowed to have both pairs taken to be the same color.
Java 8
standard input
[ "dp", "sortings", "greedy" ]
9e6cb1e8037e1d35b6c6fe43f805a22f
The first line contains three integers $$$R$$$, $$$G$$$, $$$B$$$ ($$$1 \le R, G, B \le 200$$$) — the number of pairs of red sticks, the number of pairs of green sticks and the number of pairs of blue sticks. The second line contains $$$R$$$ integers $$$r_1, r_2, \dots, r_R$$$ ($$$1 \le r_i \le 2000$$$) — the lengths of sticks in each pair of red sticks. The third line contains $$$G$$$ integers $$$g_1, g_2, \dots, g_G$$$ ($$$1 \le g_i \le 2000$$$) — the lengths of sticks in each pair of green sticks. The fourth line contains $$$B$$$ integers $$$b_1, b_2, \dots, b_B$$$ ($$$1 \le b_i \le 2000$$$) — the lengths of sticks in each pair of blue sticks.
1,800
Print the maximum possible total area of the constructed rectangles.
standard output
PASSED
d657ec18fe975df77367ad7ea5c069a9
train_002.jsonl
1597415700
You are given three multisets of pairs of colored sticks: $$$R$$$ pairs of red sticks, the first pair has length $$$r_1$$$, the second pair has length $$$r_2$$$, $$$\dots$$$, the $$$R$$$-th pair has length $$$r_R$$$; $$$G$$$ pairs of green sticks, the first pair has length $$$g_1$$$, the second pair has length $$$g_2$$$, $$$\dots$$$, the $$$G$$$-th pair has length $$$g_G$$$; $$$B$$$ pairs of blue sticks, the first pair has length $$$b_1$$$, the second pair has length $$$b_2$$$, $$$\dots$$$, the $$$B$$$-th pair has length $$$b_B$$$; You are constructing rectangles from these pairs of sticks with the following process: take a pair of sticks of one color; take a pair of sticks of another color different from the first one; add the area of the resulting rectangle to the total area. Thus, you get such rectangles that their opposite sides are the same color and their adjacent sides are not the same color.Each pair of sticks can be used at most once, some pairs can be left unused. You are not allowed to split a pair into independent sticks.What is the maximum area you can achieve?
256 megabytes
import java.io.*; import java.util.*; public class Main { static Scanner sc = new Scanner(System.in); static PrintWriter out = new PrintWriter(System.out); static int[][][] memo; static int[] red, green, blue; static int dp(int r, int g, int b) { if(r + g == 0 || g + b == 0 || r + b == 0) return 0; if(memo[r][g][b] != -1) return memo[r][g][b]; int ret = 0; if(r > 0 && g > 0) { ret = Math.max(ret, dp(r - 1, g - 1, b) + red[r] * green[g]); } if(g > 0 && b > 0) { ret = Math.max(ret, dp(r, g - 1, b - 1) + blue[b] * green[g]); } if(r > 0 && b > 0) { ret = Math.max(ret, dp(r - 1, g, b - 1) + red[r] * blue[b]); } return memo[r][g][b] = ret; } public static void main(String[] args) throws Exception { int r = sc.nextInt(), g = sc.nextInt(), b = sc.nextInt(); memo = new int[r + 5][g + 5][b + 5]; red = new int[r + 1]; green = new int[g + 1]; blue = new int[b + 1]; for(int a[][] : memo) { for(int arr[] : a) { Arrays.fill(arr, -1); } } for(int i = 1; i <= r; i++) { red[i] = sc.nextInt(); } for(int i = 1; i <= g; i++) { green[i] = sc.nextInt(); } for(int i = 1; i <= b; i++) { blue[i] = sc.nextInt(); } Arrays.sort(red); Arrays.sort(blue); Arrays.sort(green); out.println(dp(r, g, b)); out.close(); } } class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public Long nextLong() throws IOException { return Long.parseLong(next()); } }
Java
["1 1 1\n3\n5\n4", "2 1 3\n9 5\n1\n2 8 5", "10 1 1\n11 7 20 15 19 14 2 4 13 14\n8\n11"]
2 seconds
["20", "99", "372"]
NoteIn the first example you can construct one of these rectangles: red and green with sides $$$3$$$ and $$$5$$$, red and blue with sides $$$3$$$ and $$$4$$$ and green and blue with sides $$$5$$$ and $$$4$$$. The best area of them is $$$4 \times 5 = 20$$$.In the second example the best rectangles are: red/blue $$$9 \times 8$$$, red/blue $$$5 \times 5$$$, green/blue $$$2 \times 1$$$. So the total area is $$$72 + 25 + 2 = 99$$$.In the third example the best rectangles are: red/green $$$19 \times 8$$$ and red/blue $$$20 \times 11$$$. The total area is $$$152 + 220 = 372$$$. Note that you can't construct more rectangles because you are not allowed to have both pairs taken to be the same color.
Java 8
standard input
[ "dp", "sortings", "greedy" ]
9e6cb1e8037e1d35b6c6fe43f805a22f
The first line contains three integers $$$R$$$, $$$G$$$, $$$B$$$ ($$$1 \le R, G, B \le 200$$$) — the number of pairs of red sticks, the number of pairs of green sticks and the number of pairs of blue sticks. The second line contains $$$R$$$ integers $$$r_1, r_2, \dots, r_R$$$ ($$$1 \le r_i \le 2000$$$) — the lengths of sticks in each pair of red sticks. The third line contains $$$G$$$ integers $$$g_1, g_2, \dots, g_G$$$ ($$$1 \le g_i \le 2000$$$) — the lengths of sticks in each pair of green sticks. The fourth line contains $$$B$$$ integers $$$b_1, b_2, \dots, b_B$$$ ($$$1 \le b_i \le 2000$$$) — the lengths of sticks in each pair of blue sticks.
1,800
Print the maximum possible total area of the constructed rectangles.
standard output
PASSED
41d3856330851ff8be4f83c0772ee343
train_002.jsonl
1597415700
You are given three multisets of pairs of colored sticks: $$$R$$$ pairs of red sticks, the first pair has length $$$r_1$$$, the second pair has length $$$r_2$$$, $$$\dots$$$, the $$$R$$$-th pair has length $$$r_R$$$; $$$G$$$ pairs of green sticks, the first pair has length $$$g_1$$$, the second pair has length $$$g_2$$$, $$$\dots$$$, the $$$G$$$-th pair has length $$$g_G$$$; $$$B$$$ pairs of blue sticks, the first pair has length $$$b_1$$$, the second pair has length $$$b_2$$$, $$$\dots$$$, the $$$B$$$-th pair has length $$$b_B$$$; You are constructing rectangles from these pairs of sticks with the following process: take a pair of sticks of one color; take a pair of sticks of another color different from the first one; add the area of the resulting rectangle to the total area. Thus, you get such rectangles that their opposite sides are the same color and their adjacent sides are not the same color.Each pair of sticks can be used at most once, some pairs can be left unused. You are not allowed to split a pair into independent sticks.What is the maximum area you can achieve?
256 megabytes
import java.io.*; import java.util.*; //import sun.tools.serialver.resources.serialver; public class Main { static long dp[][][]; static int nr,ng,nb; static int ar[],ag[],ab[]; public static long solve(int r,int g,int b) { if(dp[r][g][b]==-1) { long best=0; if(r<nr) best=Math.max(best, solve(r+1, g, b)); if(g<ng) best=Math.max(best, solve(r, g+1, b)); if(b<nb) best=Math.max(best, solve(r, g, b+1)); if(r<nr&&g<ng) best=Math.max(best, solve(r+1, g+1, b)+ar[r]*ag[g]); if(r<nr&&b<nb) best=Math.max(best, solve(r+1, g, b+1)+ar[r]*ab[b]); if(b<nb&&g<ng) best=Math.max(best, solve(r, g+1, b+1)+ab[b]*ag[g]); dp[r][g][b]=best; } return dp[r][g][b]; } public static void main(String[] args) throws IOException { FastScanner sc = new FastScanner(); nr=sc.nextInt(); ng=sc.nextInt(); nb=sc.nextInt(); ar=sc.readArray(nr); ag=sc.readArray(ng); ab=sc.readArray(nb); Arrays.sort(ar); Arrays.sort(ag); Arrays.sort(ab); dp=new long[201][201][201]; for(int i=0;i<201;i++) for(int j=0;j<201;j++) Arrays.fill(dp[i][j], -1); System.out.println(solve(0, 0, 0)); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["1 1 1\n3\n5\n4", "2 1 3\n9 5\n1\n2 8 5", "10 1 1\n11 7 20 15 19 14 2 4 13 14\n8\n11"]
2 seconds
["20", "99", "372"]
NoteIn the first example you can construct one of these rectangles: red and green with sides $$$3$$$ and $$$5$$$, red and blue with sides $$$3$$$ and $$$4$$$ and green and blue with sides $$$5$$$ and $$$4$$$. The best area of them is $$$4 \times 5 = 20$$$.In the second example the best rectangles are: red/blue $$$9 \times 8$$$, red/blue $$$5 \times 5$$$, green/blue $$$2 \times 1$$$. So the total area is $$$72 + 25 + 2 = 99$$$.In the third example the best rectangles are: red/green $$$19 \times 8$$$ and red/blue $$$20 \times 11$$$. The total area is $$$152 + 220 = 372$$$. Note that you can't construct more rectangles because you are not allowed to have both pairs taken to be the same color.
Java 8
standard input
[ "dp", "sortings", "greedy" ]
9e6cb1e8037e1d35b6c6fe43f805a22f
The first line contains three integers $$$R$$$, $$$G$$$, $$$B$$$ ($$$1 \le R, G, B \le 200$$$) — the number of pairs of red sticks, the number of pairs of green sticks and the number of pairs of blue sticks. The second line contains $$$R$$$ integers $$$r_1, r_2, \dots, r_R$$$ ($$$1 \le r_i \le 2000$$$) — the lengths of sticks in each pair of red sticks. The third line contains $$$G$$$ integers $$$g_1, g_2, \dots, g_G$$$ ($$$1 \le g_i \le 2000$$$) — the lengths of sticks in each pair of green sticks. The fourth line contains $$$B$$$ integers $$$b_1, b_2, \dots, b_B$$$ ($$$1 \le b_i \le 2000$$$) — the lengths of sticks in each pair of blue sticks.
1,800
Print the maximum possible total area of the constructed rectangles.
standard output
PASSED
42b5a679662e8ba4bdee3e91ffd7a241
train_002.jsonl
1597415700
You are given three multisets of pairs of colored sticks: $$$R$$$ pairs of red sticks, the first pair has length $$$r_1$$$, the second pair has length $$$r_2$$$, $$$\dots$$$, the $$$R$$$-th pair has length $$$r_R$$$; $$$G$$$ pairs of green sticks, the first pair has length $$$g_1$$$, the second pair has length $$$g_2$$$, $$$\dots$$$, the $$$G$$$-th pair has length $$$g_G$$$; $$$B$$$ pairs of blue sticks, the first pair has length $$$b_1$$$, the second pair has length $$$b_2$$$, $$$\dots$$$, the $$$B$$$-th pair has length $$$b_B$$$; You are constructing rectangles from these pairs of sticks with the following process: take a pair of sticks of one color; take a pair of sticks of another color different from the first one; add the area of the resulting rectangle to the total area. Thus, you get such rectangles that their opposite sides are the same color and their adjacent sides are not the same color.Each pair of sticks can be used at most once, some pairs can be left unused. You are not allowed to split a pair into independent sticks.What is the maximum area you can achieve?
256 megabytes
// Submitted By Subhash Yadav import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Scanner; import java.util.*; public class D { static long dp[][][]; static int nr,ng,nb; static int ar[],ag[],ab[]; public static long Solve(int r,int g,int b) { if (dp[r][g][b]!=-1) return dp[r][g][b]; long best=0; if(r<nr) best=Math.max(best, Solve(r+1, g, b)); if(g<ng) best=Math.max(best, Solve(r, g+1, b)); if(b<nb) best=Math.max(best, Solve(r, g, b+1)); if(r<nr&&g<ng) best=Math.max(best, (ar[r]*ag[g])+Solve(r+1, g+1, b)); if(r<nr&&b<nb) best=Math.max(best, (ar[r]*ab[b])+Solve(r+1, g, b+1)); if(b<nb&&g<ng) best=Math.max(best, (ab[b]*ag[g])+Solve(r, g+1, b+1)); return dp[r][g][b]=best; } public static void main(String[] args) { FastScanner sc = new FastScanner(); nr=sc.nextInt();ng=sc.nextInt();nb=sc.nextInt(); ar=sc.readArray(nr); ag=sc.readArray(ng); ab=sc.readArray(nb); Arrays.sort(ar); Arrays.sort(ag); Arrays.sort(ab); dp=new long[201][201][201]; for(int i=0;i<201;i++) for(int j=0;j<201;j++) Arrays.fill(dp[i][j], -1); long ans=Solve(0, 0, 0); System.out.println(ans); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["1 1 1\n3\n5\n4", "2 1 3\n9 5\n1\n2 8 5", "10 1 1\n11 7 20 15 19 14 2 4 13 14\n8\n11"]
2 seconds
["20", "99", "372"]
NoteIn the first example you can construct one of these rectangles: red and green with sides $$$3$$$ and $$$5$$$, red and blue with sides $$$3$$$ and $$$4$$$ and green and blue with sides $$$5$$$ and $$$4$$$. The best area of them is $$$4 \times 5 = 20$$$.In the second example the best rectangles are: red/blue $$$9 \times 8$$$, red/blue $$$5 \times 5$$$, green/blue $$$2 \times 1$$$. So the total area is $$$72 + 25 + 2 = 99$$$.In the third example the best rectangles are: red/green $$$19 \times 8$$$ and red/blue $$$20 \times 11$$$. The total area is $$$152 + 220 = 372$$$. Note that you can't construct more rectangles because you are not allowed to have both pairs taken to be the same color.
Java 8
standard input
[ "dp", "sortings", "greedy" ]
9e6cb1e8037e1d35b6c6fe43f805a22f
The first line contains three integers $$$R$$$, $$$G$$$, $$$B$$$ ($$$1 \le R, G, B \le 200$$$) — the number of pairs of red sticks, the number of pairs of green sticks and the number of pairs of blue sticks. The second line contains $$$R$$$ integers $$$r_1, r_2, \dots, r_R$$$ ($$$1 \le r_i \le 2000$$$) — the lengths of sticks in each pair of red sticks. The third line contains $$$G$$$ integers $$$g_1, g_2, \dots, g_G$$$ ($$$1 \le g_i \le 2000$$$) — the lengths of sticks in each pair of green sticks. The fourth line contains $$$B$$$ integers $$$b_1, b_2, \dots, b_B$$$ ($$$1 \le b_i \le 2000$$$) — the lengths of sticks in each pair of blue sticks.
1,800
Print the maximum possible total area of the constructed rectangles.
standard output