exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
βŒ€
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
sequencelengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
βŒ€
difficulty
int64
-1
3.5k
βŒ€
prob_desc_output_spec
stringlengths
17
1.47k
βŒ€
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
101b2edb2a9e2c2f91b8bdab6a3584e1
train_000.jsonl
1517582100
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r β€” for every replace ai with D(ai); SUM l r β€” calculate . Print the answer for each SUM query.
256 megabytes
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; public class CF920F { static final boolean IS_OJ = System.getProperty("ONLINE_JUDGE") != null; public static BlockReader input; public static void main(String[] args) throws FileNotFoundException { if (!IS_OJ) { System.setIn(new FileInputStream("D:\\DataBase\\TESTCASE\\codeforces\\CF920F.in")); } input = new BlockReader(System.in); StringBuilder builder = new StringBuilder(); int n = input.nextInteger(); int m = input.nextInteger(); int[] cache = getD(1000000); Node[] nodes = new Node[n + 2]; Node[] buffer = new Node[n + 2]; Bit bit = new Bit(n); for (int i = 1; i <= n; i++) { nodes[i] = new Node(); nodes[i].val = input.nextInteger(); nodes[i].next = i; bit.update(i, nodes[i].val); } nodes[n + 1] = new Node(); nodes[n + 1].next = n + 1; for (int i = 1; i <= m; i++) { int t = input.nextInteger(); int l = input.nextInteger(); int r = input.nextInteger(); //REPLACE l r β€” for every replace ai with D(ai); if (t == 1) { int j = l; while ((j = nodes[j].getP(buffer).next) <= r) { int newVal = cache[nodes[j].val]; if (newVal == nodes[j].val) { Node.union(nodes[j], nodes[j + 1], buffer); } else { bit.update(j, newVal - nodes[j].val); nodes[j].val = newVal; j++; } } } else { //SUM l r β€” calculate . long s = bit.query(r) - bit.query(l - 1); builder.append(s).append('\n'); } } System.out.print(builder); } public static int[] getD(int n) { int[] data = new int[n + 1]; data[1] = 1; int[] primes = new int[n + 1]; int primeCnt = 0; boolean[] isComposite = new boolean[n + 1]; for (int i = 2; i <= n; i++) { if (!isComposite[i]) { primes[primeCnt++] = i; data[i] = 2; } //p * i <= n -> p <= n / i -> p<= floor(n / i) for (int j = 0, bound = n / i; j < primeCnt && primes[j] <= bound; j++) { int p = primes[j]; int pi = p * i; isComposite[pi] = true; if (i % p == 0) { // the same as gcd(i, p) > 1 data[pi] = data[i] * 2 - data[i / p]; break; } data[pi] = data[i] * data[p]; } } return data; } public static class Bit { long[] data; public Bit(int cap) { data = new long[cap + 1]; } public long query(int i) { long s = 0; for (; i > 0; i -= i & -i) { s += data[i]; } return s; } public void update(int i, int v) { for (int bound = data.length; i < bound; i += i & -i) { data[i] += v; } } } public static class Node { int rank; int next; int val; Node p = this; public static void union(Node a, Node b, Node[] que) { a = a.getP(que); b = b.getP(que); if (a == b) { return; } if (a.rank == b.rank) { a.rank++; } if (a.rank > b.rank) { b.p = a; a.next = Math.max(a.next, b.next); } else { a.p = b; b.next = Math.max(a.next, b.next); } } public Node getP(Node[] que) { int queTop = 0; Node trace; for (trace = this; trace.p != trace; trace = trace.p) { que[queTop++] = trace; } while (queTop > 0) { que[--queTop].p = trace; } return trace; } @Override public String toString() { return "(" + val + "->" + next + ")"; } } public static class BlockReader { static final int EOF = -1; InputStream is; byte[] dBuf; int dPos, dSize, next; StringBuilder builder = new StringBuilder(); public BlockReader(InputStream is) { this(is, 4096); } public BlockReader(InputStream is, int bufSize) { this.is = is; dBuf = new byte[bufSize]; next = nextByte(); } public int nextByte() { while (dPos >= dSize) { if (dSize == -1) { return EOF; } dPos = 0; try { dSize = is.read(dBuf); } catch (Exception e) { } } return dBuf[dPos++]; } public String nextBlock() { builder.setLength(0); skipBlank(); while (next != EOF && !Character.isWhitespace(next)) { builder.append((char) next); next = nextByte(); } return builder.toString(); } public void skipBlank() { while (Character.isWhitespace(next)) { next = nextByte(); } } public int nextInteger() { skipBlank(); int ret = 0; boolean rev = false; if (next == '+' || next == '-') { rev = next == '-'; next = nextByte(); } while (next >= '0' && next <= '9') { ret = (ret << 3) + (ret << 1) + next - '0'; next = nextByte(); } return rev ? -ret : ret; } public int nextBlock(char[] data, int offset) { skipBlank(); int index = offset; int bound = data.length; while (next != EOF && index < bound && !Character.isWhitespace(next)) { data[index++] = (char) next; next = nextByte(); } return index - offset; } public boolean hasMore() { skipBlank(); return next != EOF; } } }
Java
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
2 seconds
["30\n13\n4\n22"]
null
Java 8
standard input
[ "data structures", "dsu", "number theory", "brute force" ]
078cdef32cb5e60dc66c66cae3d4a57a
The first line contains two integers n and m (1 ≀ n, m ≀ 3Β·105) β€” the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 106) β€” the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n). There is at least one SUM query.
2,000
For each SUM query print the answer to it.
standard output
PASSED
54de9367f02872636a14094254134e27
train_000.jsonl
1517582100
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r β€” for every replace ai with D(ai); SUM l r β€” calculate . Print the answer for each SUM query.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class lp{ static PrintWriter out = new PrintWriter(System.out); static void fun(int div[]) { for(int i=1;i<div.length;i++) for(int j=i;j<div.length;j=j+i) div[j]++; } static void update(long BIT[],int i,int sum) { while(i<BIT.length) { BIT[i] = BIT[i]+sum; i = i + (i&(-i)); } } static long sum(long BIT[],int i) { long s=0; while(i>0) { s=s+BIT[i]; i = i - (i&(-i)); } return s; } static int find(int x,int p[]) { if(x==p[x]) return x; return p[x] = find(p[x],p); } static void update(int l,int r,long bit[],int p[],int a[],int ct[],int div[],int n) { for(int i=l;i<=r;) { int root = find(i,p); if(root>r) return; update(bit,root+1,div[a[root]]-a[root]); a[root] = div[a[root]]; ct[root]++; if(ct[root]==10) { int rr = find(root+1,p); p[root]=rr; } i=root+1; } } static void solve() { int div[] = new int[1000002]; fun(div); int n = ni(); int m = ni(); int a[] = ai(n); int ct[] = new int[n]; int p[] = new int[n+1]; long bit[] = new long[n+1]; for(int i=0;i<n;i++){ update(bit,i+1,a[i]); p[i]=i; } p[n]=n; for(int o=1;o<=m;o++) { int t = ni(); int l=ni(); int r = ni(); if(t==1) update(l-1,r-1,bit,p,a,ct,div,n); else{ long s = sum(bit,r)-sum(bit,l-1); pn(s); } } out.flush(); } public static void main(String[] args) throws Exception{ // use this block when you need more recursion depth new Thread(null, null, "Name", 999999999) { public void run() { try { solve(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static int[] ai(int n) // it will give in array of size n { int a[] = new int[n]; for(int i=0;i<n;i++) a[i] = ni(); return a; } static long[] al(int n) // it will give in array of size n { long a[] = new long[n]; for(int i=0;i<n;i++) a[i] = nl(); return a; } static void p(Object o) { out.print(o); } static void pn(Object o) { out.println(o); } static int abs(int x) { return x>0 ? x : -x; } static long gcd(long a,long b) { if(a==0) return b; if(b==0) return a; if(b%a==0) return a; return gcd(b%a,a); } static int count_set(int n) { int c=0; while(n>0) { if(n%2==1) c++; n=n/2; } return c; } static void subtract_1(char s[]) // it will subtract 1 from the given number. number should be positive { if(s[0]=='0') // number is zero return; int n = s.length,i=n-1; while(s[i]=='0') i--; s[i] = (char)((int)(s[i]-'0') + 47); for(int j=i+1;j<n;j++) s[j]='9'; } static long pow(long a,long b,long md) { long ans=1; while(b>0) { if(b%2==1) ans = (ans*a)%md; a = (a*a)%md; b = b/2; } return ans; } static long min(long a,long b){ return a<b ? a : b; } static long max(long a,long b){ return a>b ? a : b; } static boolean pal(String s) { int n = s.length(),i1=0,i2=n-1; while(i1<i2) { if(s.charAt(i1)!=s.charAt(i2)) return false; i1++; i2--; } return true; } static String rev(String r) { String s = ""; int i= r.length()-1; while(i>=0) { s=s+r.charAt(i); i--; } return s; } static FastReader sc=new FastReader(); static int ni(){ int x = sc.nextInt(); return(x); } static long nl(){ long x = sc.nextLong(); return(x); } static String n(){ String str = sc.next(); return(str); } static String ns(){ String str = sc.nextLine(); return(str); } static double nd(){ double d = sc.nextDouble(); return(d); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
2 seconds
["30\n13\n4\n22"]
null
Java 8
standard input
[ "data structures", "dsu", "number theory", "brute force" ]
078cdef32cb5e60dc66c66cae3d4a57a
The first line contains two integers n and m (1 ≀ n, m ≀ 3Β·105) β€” the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 106) β€” the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n). There is at least one SUM query.
2,000
For each SUM query print the answer to it.
standard output
PASSED
6061166fe432bd4b3382aaebb0825ace
train_000.jsonl
1517582100
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r β€” for every replace ai with D(ai); SUM l r β€” calculate . Print the answer for each SUM query.
256 megabytes
/* Idea is that after at most 1o replace operations a number will become contstant. After that we do not need to aply replce operations. Use dsu to find next index where we can apply replace operation. Use BIT to update and find sum in given range */ import java.util.*; import java.io.*; import java.math.BigInteger; public class lp{ static PrintWriter out = new PrintWriter(System.out); static void fun(int div[]) { for(int i=1;i<div.length;i++) for(int j=i;j<div.length;j=j+i) div[j]++; } static void update(long BIT[],int i,int sum) { while(i<BIT.length) { BIT[i] = BIT[i]+sum; i = i + (i&(-i)); } } static long sum(long BIT[],int i) { long s=0; while(i>0) { s=s+BIT[i]; i = i - (i&(-i)); } return s; } static int find(int x,int p[]) { if(x==p[x]) return x; return p[x] = find(p[x],p); } static void update(int l,int r,long bit[],int p[],int a[],int ct[],int div[],int n) { for(int i=l;i<=r;) { int root = find(i,p); if(root>r) return; update(bit,root+1,div[a[root]]-a[root]); a[root] = div[a[root]]; ct[root]++; if(ct[root]==10) { int rr = find(root+1,p); p[root]=rr; } i=root+1; } } static void solve() { int div[] = new int[1000002]; fun(div); int n = ni(); int m = ni(); int a[] = ai(n); int ct[] = new int[n]; int p[] = new int[n+1]; long bit[] = new long[n+1]; for(int i=0;i<n;i++){ update(bit,i+1,a[i]); p[i]=i; } p[n]=n; for(int o=1;o<=m;o++) { int t = ni(); int l=ni(); int r = ni(); if(t==1) update(l-1,r-1,bit,p,a,ct,div,n); else{ long s = sum(bit,r)-sum(bit,l-1); pn(s); } } out.flush(); } public static void main(String[] args) throws Exception{ // use this block when you need more recursion depth new Thread(null, null, "Name", 999999999) { public void run() { try { solve(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static int[] ai(int n) // it will give in array of size n { int a[] = new int[n]; for(int i=0;i<n;i++) a[i] = ni(); return a; } static long[] al(int n) // it will give in array of size n { long a[] = new long[n]; for(int i=0;i<n;i++) a[i] = nl(); return a; } static void p(Object o) { out.print(o); } static void pn(Object o) { out.println(o); } static int abs(int x) { return x>0 ? x : -x; } static long gcd(long a,long b) { if(a==0) return b; if(b==0) return a; if(b%a==0) return a; return gcd(b%a,a); } static int count_set(int n) { int c=0; while(n>0) { if(n%2==1) c++; n=n/2; } return c; } static void subtract_1(char s[]) // it will subtract 1 from the given number. number should be positive { if(s[0]=='0') // number is zero return; int n = s.length,i=n-1; while(s[i]=='0') i--; s[i] = (char)((int)(s[i]-'0') + 47); for(int j=i+1;j<n;j++) s[j]='9'; } static long pow(long a,long b,long md) { long ans=1; while(b>0) { if(b%2==1) ans = (ans*a)%md; a = (a*a)%md; b = b/2; } return ans; } static long min(long a,long b){ return a<b ? a : b; } static long max(long a,long b){ return a>b ? a : b; } static boolean pal(String s) { int n = s.length(),i1=0,i2=n-1; while(i1<i2) { if(s.charAt(i1)!=s.charAt(i2)) return false; i1++; i2--; } return true; } static String rev(String r) { String s = ""; int i= r.length()-1; while(i>=0) { s=s+r.charAt(i); i--; } return s; } static FastReader sc=new FastReader(); static int ni(){ int x = sc.nextInt(); return(x); } static long nl(){ long x = sc.nextLong(); return(x); } static String n(){ String str = sc.next(); return(str); } static String ns(){ String str = sc.nextLine(); return(str); } static double nd(){ double d = sc.nextDouble(); return(d); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
2 seconds
["30\n13\n4\n22"]
null
Java 8
standard input
[ "data structures", "dsu", "number theory", "brute force" ]
078cdef32cb5e60dc66c66cae3d4a57a
The first line contains two integers n and m (1 ≀ n, m ≀ 3Β·105) β€” the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 106) β€” the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n). There is at least one SUM query.
2,000
For each SUM query print the answer to it.
standard output
PASSED
2eacb8c6469cc91179db7f319e0e06e7
train_000.jsonl
1517582100
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r β€” for every replace ai with D(ai); SUM l r β€” calculate . Print the answer for each SUM query.
256 megabytes
/* Keep solving problems. */ import java.util.*; import java.io.*; public class CFF { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; final long MOD = 1000L * 1000L * 1000L + 7; int[] dx = {0, -1, 0, 1}; int[] dy = {1, 0, -1, 0}; private static final String yes = "YES"; private static final String no = "NO"; int arr[]; long maxTree[]; long sumTree[]; void build_tree(int node, int nodeStartIndex, int nodeEndIndex) { if(nodeStartIndex > nodeEndIndex) return; // Out of range if(nodeStartIndex == nodeEndIndex) { // Leaf node maxTree[node] = arr[nodeStartIndex]; // Init value sumTree[node] = arr[nodeStartIndex]; // Init value return; } build_tree(node * 2, nodeStartIndex, (nodeStartIndex + nodeEndIndex) / 2); // Init left child build_tree(node * 2 + 1, 1 + (nodeStartIndex + nodeEndIndex) / 2, nodeEndIndex); // Init right child sumTree[node] = sumTree[node * 2] + sumTree[node * 2 + 1]; // Init root value maxTree[node] = Math.max(maxTree[node * 2], maxTree[node * 2 + 1]); // Init root value } /** * Increment elements within range [queryStartIndex, queryEndIndex] with value */ void update_tree(int node, int nodeStartIndex, int nodeEndIndex, int queryStartIndex, int queryEndIndex) { if(nodeStartIndex > nodeEndIndex || nodeStartIndex > queryEndIndex || nodeEndIndex < queryStartIndex) // Current segment is not within range [i, j] return; if(nodeStartIndex >= queryStartIndex && nodeEndIndex <= queryEndIndex) { // Segment is fully within range if (maxTree[node] <= 2) { return; } if (nodeStartIndex == nodeEndIndex) { arr[nodeStartIndex] = seive[arr[nodeStartIndex]]; maxTree[node] = arr[nodeStartIndex]; // Init value sumTree[node] = arr[nodeStartIndex]; // Init value return; } } update_tree(node * 2, nodeStartIndex, (nodeStartIndex + nodeEndIndex) / 2, queryStartIndex, queryEndIndex); // Updating left child update_tree(node * 2 + 1, 1 + (nodeStartIndex + nodeEndIndex) / 2, nodeEndIndex, queryStartIndex, queryEndIndex); // Updating right child sumTree[node] = sumTree[node * 2] + sumTree[node * 2 + 1]; // Init root value maxTree[node] = Math.max(maxTree[node * 2], maxTree[node * 2 + 1]); // Init root value } /** * Query tree to get max element value within range [queryStartIndex, queryEndIndex] */ long query_tree(int node, int nodeStartIndex, int nodeEndIndex, int queryStartIndex, int queryEndIndex) { if(nodeStartIndex > nodeEndIndex || nodeStartIndex > queryEndIndex || nodeEndIndex < queryStartIndex) return 0; // Out of range if(nodeStartIndex >= queryStartIndex && nodeEndIndex <= queryEndIndex) { return sumTree[node]; } long q1 = query_tree(node * 2, nodeStartIndex, (nodeStartIndex + nodeEndIndex) / 2, queryStartIndex, queryEndIndex); // Query left child long q2 = query_tree(1 + node * 2, 1 + (nodeStartIndex + nodeEndIndex) / 2, nodeEndIndex, queryStartIndex, queryEndIndex); // Query right child return q1 + q2; } int len = 1000010; // int len = 100; int[] seive = new int[1 + len]; void solve() throws IOException { int n = nextInt(); int m = nextInt(); Arrays.fill(seive, 1); for (int i = 2; i <= len; i++) { for (int j = 1; j * i <= len; j++) { seive[j * i]++; } } arr = nextIntArr(n); sumTree = new long[5 * n]; maxTree = new long[5 * n]; build_tree(1, 0, n - 1); for (int i = 0; i < m; i++) { int q = nextInt(); int l = nextInt() - 1; int r = nextInt() - 1; if (q == 1) { update_tree(1, 0, n - 1, l, r); } else { long res = query_tree(1, 0, n - 1, l, r); outln(res); } } } 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; } } long gcd(long a, long b) { while(a != 0 && b != 0) { long c = b; b = a % b; a = c; } return a + b; } private void outln(Object o) { out.println(o); } private void out(Object o) { out.print(o); } public CFF() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new CFF(); } public long[] nextLongArr(int n) throws IOException{ long[] res = new long[n]; for(int i = 0; i < n; i++) res[i] = nextLong(); return res; } public int[] nextIntArr(int n) throws IOException { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } public String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
2 seconds
["30\n13\n4\n22"]
null
Java 8
standard input
[ "data structures", "dsu", "number theory", "brute force" ]
078cdef32cb5e60dc66c66cae3d4a57a
The first line contains two integers n and m (1 ≀ n, m ≀ 3Β·105) β€” the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 106) β€” the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n). There is at least one SUM query.
2,000
For each SUM query print the answer to it.
standard output
PASSED
e6dcade4681767a370a760acac069c22
train_000.jsonl
1517582100
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r β€” for every replace ai with D(ai); SUM l r β€” calculate . Print the answer for each SUM query.
256 megabytes
import java.io.BufferedReader; 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.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.PriorityQueue; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class Main { static ArrayList<Integer> adj[]; static int k; static int[] a; static int b[]; static int m; static class Pair implements Comparable<Pair> { int a; int b; public Pair(int c,int l) { a = c; b = l; } @Override public int compareTo(Pair o) { if(o.a==this.a) return this.b-o.b; return this.a-o.a; } } static ArrayList<Pair> adjlist[]; // static char c[]; static long mod = (long) (1e9+7); static int V; static long INF = (long) 1E16; static int n; static char c[]; static Pair p[]; static int grid[][]; static Scanner sc = new Scanner(System.in); static PrintWriter out = new PrintWriter(System.out); static long div[]; public static void main(String args[]) throws Exception { int maxN=(int)(1e6); div=new long [maxN+1]; for(int i=1;i<=maxN;i++) for(int j=i;j<=maxN;j+=i) div[j]++; int n=sc.nextInt(); int N=1; while(N<n) N<<=1; long a[]=new long[N+1]; int q=sc.nextInt(); for (int i =1; i<=n; i++) { a[i]=sc.nextInt(); } SegmentTree st=new SegmentTree(a); while(q-->0) { int t=sc.nextInt(); int l=sc.nextInt(); int r=sc.nextInt(); if(t==1) { st.update_range(l,r,0); } else if(t==2) { out.println(st.query(l,r)); } } out.flush(); } static int s; static class Query implements Comparable<Query> { // length of a block , s = sqrt(n) int left, right, idx; int block; Query(int a, int b, int c) { left = a; right = b; idx = c; block=left/s; } public int compareTo(Query q) { if(q.block==this.block) return right-q.right; return block-q.block; } } static void dfs(int u) { vis[u]=true; for(int v:adj[u]) { if(!vis[v]) { dfs(v); } } } static int[] compreessarray(int c[]) { int b[]=new int[c.length]; for (int i = 0; i < b.length; i++) { b[i]=c[i]; } sortarray(c); TreeMap<Integer,Integer> map=new TreeMap<>(); int id=0; for (int i = 0; i < c.length; i++) { if(!map.containsKey(c[i])) id++; map.put(c[i],map.getOrDefault(c[i],id)); } int idx=0; for (int i = 0; i < c.length; i++) { joke.put(b[i],map.get(b[i])); b[i]=map.get(b[i]); } return b; } static TreeMap<Integer,Integer> joke=new TreeMap<>(); static int div4[]; static long [] reversearray(long a[]) { for (int i = 0; i <a.length/2; i++) { long temp=a[i]; a[i]=a[a.length-i-1]; a[a.length-i-1]=temp; } return a; } static int [] reversearray(int a[]) { for (int i = 0; i <=a.length/2; i++) { int temp=a[i]; a[i]=a[a.length-i-1]; a[a.length-i-1]=temp; } return a; } static class SegmentTree { // 1-based DS, OOP int N; //the number of elements in the array as a power of 2 (i.e. after padding) long[] array, sTree, lazy; long max[]; SegmentTree(long[] in) { array = in; N = in.length - 1; sTree = new long[N<<1]; //no. of nodes = 2*N - 1, we add one to cross out index zero lazy = new long[N<<1]; max=new long[N<<1]; build(1,1,N); } void build(int node, int b, int e) // O(n) { if(b == e) { sTree[node] = array[b]; max[node]=array[b]; } else { int mid = b + e >> 1; build(node<<1,b,mid); build(node<<1|1,mid+1,e); sTree[node] = sTree[node<<1]+sTree[node<<1|1]; max[node]=Math.max(max[node<<1],max[node<<1|1]); } } void update_point(int index, int val) // O(log n) { index += N - 1; sTree[index] += val; while(index>1) { index >>= 1; sTree[index] = sTree[index<<1] + sTree[index<<1|1]; } } void update_range(int i, int j, int val) // O(log n) { update_range(1,1,N,i,j,val); } void update_range(int node, int b, int e, int i, int j, int val) { if(i > e || j < b||max[node]==1||max[node]==2) return; if(b==e) { sTree[node]=div[(int) sTree[node]]; max[node]=sTree[node]; } else { int mid = b + e >> 1; // propagate(node, b, mid, e); update_range(node<<1,b,mid,i,j,val); update_range(node<<1|1,mid+1,e,i,j,val); sTree[node] = sTree[node<<1] + sTree[node<<1|1]; max[node]=Math.max(max[node<<1],max[node<<1|1]); } } // void propagate(int node, int b, int mid, int e) // { // lazy[node<<1] += lazy[node]; // lazy[node<<1|1] += lazy[node]; // sTree[node<<1] += (mid-b+1)*lazy[node]; // sTree[node<<1|1] += (e-mid)*lazy[node]; // lazy[node] = 0; // } long query(int i, int j) { return query(1,1,N,i,j); } long query(int node, int b, int e, int i, int j) // O(log n) { if(i>e || j <b) return 0; if(b>= i && e <= j) return sTree[node]; int mid = b + e >> 1; // propagate(node, b, mid, e); long q1 = query(node<<1,b,mid,i,j); long q2 = query(node<<1|1,mid+1,e,i,j); return q1+q2; } } static TreeSet<Integer> ts=new TreeSet(); static HashMap<Integer, Integer> compress(int a[]) { ts = new TreeSet<>(); HashMap<Integer, Integer> hm = new HashMap<>(); for (int x : a) ts.add(x); for (int x : ts) { hm.put(x, hm.size() + 1); } return hm; } static class FenwickTree { // one-based DS int n; long[] ft; FenwickTree(int size) { n = size; ft = new long[n+1]; } long rsq(int b) //O(log n) { long sum = 0; while(b<=n) { sum += ft[b]; b += b & -b;} //min? return sum; } long rsq(int a, int b) { return rsq(b) - rsq(a-1); } /** * @param k * @param l */ void point_update(int k, long l) //O(log n), update = increment { while(k>0) { ft[k] += l; k -= k & -k; } } } static ArrayList<Integer> euler=new ArrayList<>(); static long total; static TreeMap<Integer,Integer> map1; static int zz; //static int dp(int idx,int left,int state) { //if(idx>=k-((zz-left)*2)||idx+1==n) { // return 0; //} //if(memo[idx][left][state]!=-1) { // return memo[idx][left][state]; //} //int ans=a[idx+1]+dp(idx+1,left,0); //if(left>0&&state==0&&idx>0) { // ans=Math.max(ans,a[idx-1]+dp(idx-1,left-1,1)); //} //return memo[idx][left][state]=ans; //}21 static HashMap<Integer,Integer> map; static int maxa=0; static int ff=123123; static int[][] memo; static long modmod=998244353; static int dx[]= {1,-1,0,0}; static int dy[]= {0,0,1,-1}; static class BBOOK implements Comparable<BBOOK>{ int t; int alice; int bob; public BBOOK(int x,int y,int z) { t=x; alice=y; bob=z; } @Override public int compareTo(BBOOK o) { return this.t-o.t; } } private static long lcm(long a2, long b2) { return (a2*b2)/gcd(a2,b2); } static class Edge implements Comparable<Edge> { int node;long cost ; long time; Edge(int a, long b,long c) { node = a; cost = b; time=c; } public int compareTo(Edge e){ return Long.compare(time,e.time); } } static void sieve(int N) // O(N log log N) { isComposite = new int[N+1]; isComposite[0] = isComposite[1] = 1; // 0 indicates a prime number primes = new ArrayList<Integer>(); for (int i = 2; i <= N; ++i) //can loop till i*i <= N if primes array is not needed O(N log log sqrt(N)) if (isComposite[i] == 0) //can loop in 2 and odd integers for slightly better performance { primes.add(i); if(1l * i * i <= N) for (int j = i * i; j <= N; j += i) // j = i * 2 will not affect performance too much, may alter in modified sieve isComposite[j] = 1; } } static TreeSet<Integer> factors; static TreeSet<Integer> primeFactors(int N) // O(sqrt(N) / ln sqrt(N)) { factors = new TreeSet<Integer>(); //take abs(N) in case of -ve integers int idx = 0, p = primes.get(idx); while(1l*p * p <= N) { while(N % p == 0) { factors.add(p); N /= p; } p = primes.get(++idx); } if(N != 1) // last prime factor may be > sqrt(N) factors.add(N); // for integers whose largest prime factor has a power of 1 return factors; } static class UnionFind { int[] p, rank, setSize; int numSets; long max[]; long largest=0; public UnionFind(int N) { p = new int[numSets = N]; rank = new int[N]; setSize = new int[N]; max=new long[N]; for (int i = 0; i < N; i++) { p[i] = i; setSize[i] = 1; } largest=0; } public int findSet(int i) { return p[i] == i ? i : (p[i] = findSet(p[i])); } public void addmax(int i,int val) { max[i]=val; largest=Math.max(largest,max[i]); } public boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); } public void unionSet(int i, int j) { if (isSameSet(i, j)) return; numSets--; int x = findSet(i), y = findSet(j); if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; max[x]+=max[y]; } else { p[x] = y; setSize[y] += setSize[x]; if (rank[x] == rank[y]) rank[y]++; max[y]+=max[x]; } largest=Math.max(max[x],largest); largest=Math.max(max[y],largest); } public int numDisjointSets() { return numSets; } public int sizeOfSet(int i) { return setSize[findSet(i)]; } } static class Quad implements Comparable<Quad> { int u; int v; char state; int turns; public Quad(int i, int j, char c, int k) { u = i; v = j; state = c; turns = k; } public int compareTo(Quad e) { return (int) (turns - e.turns); } } static long manhatandistance(long x, long x2, long y, long y2) { return Math.abs(x - x2) + Math.abs(y - y2); } static long fib[]; static long fib(int n) { if (n == 1 || n == 0) { return 1; } if (fib[n] != -1) { return fib[n]; } else return fib[n] = ((fib(n - 2) % mod + fib(n - 1) % mod) % mod); } static class Point implements Comparable<Point>{ long x, y; Point(long counth, long counts) { x = counth; y = counts; } @Override public int compareTo(Point p ) { return Long.compare(p.y*1l*x, p.x*1l*y); } } static TreeSet<Long> primeFactors(long N) // O(sqrt(N) / ln sqrt(N)) { TreeSet<Long> factors = new TreeSet<Long>(); // take abs(N) in case of -ve integers int idx = 0, p = primes.get(idx); while (p * p <= N) { while (N % p == 0) { factors.add((long) p); N /= p; } if (primes.size() > idx + 1) p = primes.get(++idx); else break; } if (N != 1) // last prime factor may be > sqrt(N) factors.add(N); // for integers whose largest prime factor has a power of 1 return factors; } static boolean visited[]; /** * static int bfs(int s) { Queue<Integer> q = new LinkedList<Integer>(); * q.add(s); int count=0; int maxcost=0; int dist[]=new int[n]; dist[s]=0; * while(!q.isEmpty()) { * * int u = q.remove(); if(dist[u]==k) { break; } for(Pair v: adj[u]) { * maxcost=Math.max(maxcost, v.cost); * * * * if(!visited[v.v]) { * * visited[v.v]=true; q.add(v.v); dist[v.v]=dist[u]+1; maxcost=Math.max(maxcost, * v.cost); } } * * } return maxcost; } **/ static boolean[] vis2; static boolean f2 = false; static long[][] matMul(long[][] a2, long[][] b, int p, int q, int r) // C(p x r) = A(p x q) x (q x r) -- O(p x q x // r) { long[][] C = new long[p][r]; for (int i = 0; i < p; ++i) { for (int j = 0; j < r; ++j) { for (int k = 0; k < q; ++k) { C[i][j] = (C[i][j] + (a2[i][k] % mod * b[k][j] % mod)) % mod; C[i][j] %= mod; } } } return C; } public static int[] schuffle(int[] a2) { for (int i = 0; i < a2.length; i++) { int x = (int) (Math.random() * a2.length); int temp = a2[x]; a2[x] = a2[i]; a2[i] = temp; } return a2; } static boolean vis[]; static HashSet<Integer> set = new HashSet<Integer>(); static long modPow(long ways, long count, long mod) // O(log e) { ways %= mod; long res = 1; while (count > 0) { if ((count & 1) == 1) res = (res * ways) % mod; ways = (ways * ways) % mod; count >>= 1; } return res % mod; } static long gcd(long l, long o) { if (o == 0) { return l; } return gcd(o, l % o); } static int[] isComposite; static int[] valid; static ArrayList<Integer> primes; static ArrayList<Integer> l1; static TreeSet<Integer> primus = new TreeSet<Integer>(); static void sieveLinear(int N) { int[] lp = new int[N + 1]; //lp[i] = least prime divisor of i for(int i = 2; i <= N; ++i) { if(lp[i] == 0) { primus.add(i); lp[i] = i; } int curLP = lp[i]; for(int p: primus) if(p > curLP || p * i > N) break; else lp[p * i] = i; } } public static long[] schuffle(long[] a2) { for (int i = 0; i < a2.length; i++) { int x = (int) (Math.random() * a2.length); long temp = a2[x]; a2[x] = a2[i]; a2[i] = temp; } return a2; } static 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 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); } public int[] nxtArr(int n) throws IOException { int[] ans = new int[n]; for (int i = 0; i < n; i++) ans[i] = nextInt(); return ans; } } public static int[] sortarray(int a[]) { schuffle(a); Arrays.sort(a); return a; } public static long[] sortarray(long a[]) { schuffle(a); Arrays.sort(a); return a; } }
Java
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
2 seconds
["30\n13\n4\n22"]
null
Java 8
standard input
[ "data structures", "dsu", "number theory", "brute force" ]
078cdef32cb5e60dc66c66cae3d4a57a
The first line contains two integers n and m (1 ≀ n, m ≀ 3Β·105) β€” the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 106) β€” the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n). There is at least one SUM query.
2,000
For each SUM query print the answer to it.
standard output
PASSED
4144259e31c4d2b128f9cd84d1cf0e6b
train_000.jsonl
1517582100
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r β€” for every replace ai with D(ai); SUM l r β€” calculate . Print the answer for each SUM query.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.System.in; public class Main { static int n,n0=1,m; static int[] dat, dic,a; static long[] sum; // static ArrayList<Integer>[] graph,tree; public static void main(String[] args)throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); //Scanner sc = new Scanner(System.in); String[] buf = reader.readLine().split(" "); n = Integer.parseInt(buf[0]); m = Integer.parseInt(buf[1]); buf = reader.readLine().split(" "); a = new int[n]; for(int i=0;i<n;i++) a[i]=Integer.parseInt(buf[i]); ini(a); PrintWriter out = new PrintWriter(System.out); for(int pass=0;pass<m;pass++){ buf = reader.readLine().split(" "); int t = Integer.parseInt(buf[0]); int a = Integer.parseInt(buf[1])-1,b = Integer.parseInt(buf[2]); if(t==1) update(0,a,b,0,n0); else { long ans = query(0,a,b,0,n0); out.println(ans); } } out.flush(); } static void ini(int[] a){ while(n0<n) n0*=2; dat = new int[2*n0-1]; sum = new long[2*n0-1]; // dat[] used to record the max value int maxa = 1; for(int w:a) maxa = Math.max(maxa,w); dic = new int[maxa+1]; Arrays.fill(dic,1); for(int i=2;i<=maxa;i++){ for(int j=i;j<=maxa;j+=i) dic[j]++; } for(int i=0;i<n;i++){ int idx = i+n0-1, now = a[i]; sum[idx] = now; dat[idx] = now; while(idx>0){ idx = (idx-1)/2; dat[idx] = Math.max(dat[idx*2+1],dat[idx*2+2]); sum[idx] += now; } } } static long query(int k, int a, int b, int le, int ri){ if(b<=le||ri<=a) return 0; if(a<=le&&ri<=b) return sum[k]; long left = query(k*2+1,a,b,le,(le+ri)>>1); long right = query(k*2+2,a,b,(le+ri)>>1,ri); return left+right; } static void update(int k, int a, int b, int le, int ri){ if(dat[k]<=2||le>=ri) return; if(ri<=a||b<=le) return; if(le+1==ri){ // single-point update int cur = dat[k]; dat[k] = dic[cur]; sum[k] = dic[cur]; return; } int mid = (le+ri)>>1; update(k*2+1,a,b,le,mid); update(k*2+2,a,b,mid,ri); sum[k] = sum[2*k+1]+sum[2*k+2]; dat[k] = Math.max(dat[2*k+1],dat[2*k+2]); } }
Java
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
2 seconds
["30\n13\n4\n22"]
null
Java 8
standard input
[ "data structures", "dsu", "number theory", "brute force" ]
078cdef32cb5e60dc66c66cae3d4a57a
The first line contains two integers n and m (1 ≀ n, m ≀ 3Β·105) β€” the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 106) β€” the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n). There is at least one SUM query.
2,000
For each SUM query print the answer to it.
standard output
PASSED
85e10b57872d72994fa2da5fe8379e3e
train_000.jsonl
1517582100
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r β€” for every replace ai with D(ai); SUM l r β€” calculate . Print the answer for each SUM query.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.System.in; public class Main { static int n,n0=2,m; static int[] dat, dic,a; static long[] sum; // static ArrayList<Integer>[] graph,tree; public static void main(String[] args)throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); //Scanner sc = new Scanner(System.in); String[] buf = reader.readLine().split(" "); n = Integer.parseInt(buf[0]); m = Integer.parseInt(buf[1]); buf = reader.readLine().split(" "); a = new int[n]; for(int i=0;i<n;i++) a[i]=Integer.parseInt(buf[i]); ini(a); PrintWriter out = new PrintWriter(System.out); for(int pass=0;pass<m;pass++){ buf = reader.readLine().split(" "); int t = Integer.parseInt(buf[0]); int a = Integer.parseInt(buf[1])-1,b = Integer.parseInt(buf[2]); if(t==1) update(0,a,b,0,n0); else { long ans = query(0,a,b,0,n0); out.println(ans); } } out.flush(); } static void ini(int[] a){ while(n0<n) n0*=2; dat = new int[2*n0-1]; sum = new long[2*n0-1]; // dat[] used to record the max value int maxa = 1; for(int w:a) maxa = Math.max(maxa,w); dic = new int[maxa+1]; Arrays.fill(dic,1); for(int i=2;i<=maxa;i++){ for(int j=i;j<=maxa;j+=i) dic[j]++; } for(int i=0;i<n;i++){ int idx = i+n0-1; sum[idx] = a[i]; dat[idx] = a[i]; while(idx>0){ idx = (idx-1)/2; dat[idx] = Math.max(dat[idx*2+1],dat[idx*2+2]); } } int start = n0; while(start>0){ start = (start-1)/2; for(int j=start;j<=2*start;j++) sum[j] = sum[j*2+1]+sum[j*2+2]; } } static long query(int k, int a, int b, int le, int ri){ if(b<=le||ri<=a) return 0; if(a<=le&&ri<=b) return sum[k]; long left = query(k*2+1,a,b,le,(le+ri)>>1); long right = query(k*2+2,a,b,(le+ri)>>1,ri); return left+right; } static void update(int k, int a, int b, int le, int ri){ if(dat[k]<=2||le>=ri) return; if(ri<=a||b<=le) return; if(le+1==ri){ // single-point update int cur = dat[k]; dat[k] = dic[cur]; sum[k] = dic[cur]; return; } int mid = (le+ri)>>1; update(k*2+1,a,b,le,mid); update(k*2+2,a,b,mid,ri); sum[k] = sum[2*k+1]+sum[2*k+2]; dat[k] = Math.max(dat[2*k+1],dat[2*k+2]); } }
Java
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
2 seconds
["30\n13\n4\n22"]
null
Java 8
standard input
[ "data structures", "dsu", "number theory", "brute force" ]
078cdef32cb5e60dc66c66cae3d4a57a
The first line contains two integers n and m (1 ≀ n, m ≀ 3Β·105) β€” the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 106) β€” the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n). There is at least one SUM query.
2,000
For each SUM query print the answer to it.
standard output
PASSED
5606a96eca7be9148fcd2721509a3769
train_000.jsonl
1517582100
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r β€” for every replace ai with D(ai); SUM l r β€” calculate . Print the answer for each SUM query.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.System.in; public class Main { static int n,n0=2,m; static int[] dat, dic,a; static long[] sum; // static ArrayList<Integer>[] graph,tree; public static void main(String[] args)throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); //Scanner sc = new Scanner(System.in); String[] buf = reader.readLine().split(" "); n = Integer.parseInt(buf[0]); m = Integer.parseInt(buf[1]); buf = reader.readLine().split(" "); a = new int[n]; for(int i=0;i<n;i++) a[i]=Integer.parseInt(buf[i]); ini(a); PrintWriter out = new PrintWriter(System.out); for(int pass=0;pass<m;pass++){ buf = reader.readLine().split(" "); int t = Integer.parseInt(buf[0]); int a = Integer.parseInt(buf[1])-1,b = Integer.parseInt(buf[2]); if(t==1) update(0,a,b,0,n0); else { long ans = query(0,a,b,0,n0); out.println(ans); } } out.flush(); } static void ini(int[] a){ while(n0<n) n0*=2; dat = new int[2*n0-1]; sum = new long[2*n0-1]; // dat[] used to record the max value int maxa = 1; for(int w:a) maxa = Math.max(maxa,w); dic = new int[maxa+1]; Arrays.fill(dic,1); for(int i=2;i<=maxa;i++){ for(int j=i;j<=maxa;j+=i) dic[j]++; } for(int i=0;i<n;i++){ int idx = i+n0-1, now = a[i]; sum[idx] = now; dat[idx] = now; while(idx>0){ idx = (idx-1)/2; dat[idx] = Math.max(dat[idx*2+1],dat[idx*2+2]); sum[idx] += now; } } } static long query(int k, int a, int b, int le, int ri){ if(b<=le||ri<=a) return 0; if(a<=le&&ri<=b) return sum[k]; long left = query(k*2+1,a,b,le,(le+ri)>>1); long right = query(k*2+2,a,b,(le+ri)>>1,ri); return left+right; } static void update(int k, int a, int b, int le, int ri){ if(dat[k]<=2||le>=ri) return; if(ri<=a||b<=le) return; if(le+1==ri){ // single-point update int cur = dat[k]; dat[k] = dic[cur]; sum[k] = dic[cur]; return; } int mid = (le+ri)>>1; update(k*2+1,a,b,le,mid); update(k*2+2,a,b,mid,ri); sum[k] = sum[2*k+1]+sum[2*k+2]; dat[k] = Math.max(dat[2*k+1],dat[2*k+2]); } }
Java
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
2 seconds
["30\n13\n4\n22"]
null
Java 8
standard input
[ "data structures", "dsu", "number theory", "brute force" ]
078cdef32cb5e60dc66c66cae3d4a57a
The first line contains two integers n and m (1 ≀ n, m ≀ 3Β·105) β€” the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 106) β€” the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n). There is at least one SUM query.
2,000
For each SUM query print the answer to it.
standard output
PASSED
04a7a651aa5ec48a9af71a1cfb044bac
train_000.jsonl
1517582100
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r β€” for every replace ai with D(ai); SUM l r β€” calculate . Print the answer for each SUM query.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ work(); out.flush(); } long mod=998244353; long gcd(long a,long b) { return b==0?a:gcd(b,a%b); } int[] dp; void work() { int[] rec=new int[1000001]; Arrays.fill(rec,1); for(int i=2;i*i<=1000000;i++) { if(rec[i]==1) { for(int j=i;j*i<=1000000;j++) { rec[i*j]=i; } } } dp=new int[1000001]; dp[1]=1; for(int i=2;i<=1000000;i++) { int d=rec[i]; if(d==1)dp[i]=2; else { int c=0; int num=i; while(num%d==0) { c++; num/=d; } dp[i]=dp[num]*(c+1); } } int n=in.nextInt(),m=in.nextInt(); int[] A=new int[n]; for(int i=0;i<n;i++)A[i]=in.nextInt(); Node root=new Node(); for(int i=0;i<n;i++) { insert(root,A[i],i,0,n-1); } for(int i=0;i<m;i++) { int type=in.nextInt(); if(type==1) { update(root,in.nextInt()-1,in.nextInt()-1,0,n-1); }else { out.println(query(root,in.nextInt()-1,in.nextInt()-1,0,n-1)); } } } private long query(Node node, int s, int e, int l, int r) { if(l>=s&&r<=e) { return node.sum; } Node lnode=getLnode(node); Node rnode=getRnode(node); long ret=0; int m=(l+r)/2; if(m>=s) { ret+=query(lnode,s,e,l,m); } if(m<e) { ret+=query(rnode,s,e,m+1,r); } return ret; } private void update(Node node,int s, int e,int l,int r) { if(l==r) { node.sum=dp[(int)node.sum]; if(dp[(int)node.sum]==node.sum)node.cnt--; return; } Node lnode=getLnode(node); Node rnode=getRnode(node); int m=(l+r)/2; if(m>=s&&lnode.cnt>0) { update(lnode,s,e,l,m); } if(m<e&&rnode.cnt>0) { update(rnode,s,e,m+1,r); } node.sum=lnode.sum+rnode.sum; node.cnt=lnode.cnt+rnode.cnt; } private void insert(Node node, long v,int idx, int l, int r) { if(l==r) { node.sum=v; if(dp[(int)v]!=v)node.cnt++; return; } int m=(l+r)/2; Node lnode=getLnode(node); Node rnode=getRnode(node); if(idx<=m) { insert(lnode,v,idx,l,m); }else { insert(rnode,v,idx,m+1,r); } node.cnt=lnode.cnt+rnode.cnt; node.sum=lnode.sum+rnode.sum; } private Node getRnode(Node node) { if(node.rnode==null) node.rnode=new Node(); return node.rnode; } private Node getLnode(Node node) { if(node.lnode==null) node.lnode=new Node(); return node.lnode; } class Node{ Node lnode,rnode; int cnt; long sum; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { if(st==null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
Java
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
2 seconds
["30\n13\n4\n22"]
null
Java 8
standard input
[ "data structures", "dsu", "number theory", "brute force" ]
078cdef32cb5e60dc66c66cae3d4a57a
The first line contains two integers n and m (1 ≀ n, m ≀ 3Β·105) β€” the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 106) β€” the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n). There is at least one SUM query.
2,000
For each SUM query print the answer to it.
standard output
PASSED
e9c621eafb666c841cf10b481ba0b163
train_000.jsonl
1517582100
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r β€” for every replace ai with D(ai); SUM l r β€” calculate . Print the answer for each SUM query.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ work(); out.flush(); } long mod=998244353; long gcd(long a,long b) { return b==0?a:gcd(b,a%b); } int[] dp; void work() { dp=new int[1000001]; for(int i=1;i<=1000000;i++) { for(int j=i;j<=1000000;j+=i) { dp[j]++; } } int n=in.nextInt(),m=in.nextInt(); int[] A=new int[n]; for(int i=0;i<n;i++)A[i]=in.nextInt(); Node root=new Node(); for(int i=0;i<n;i++) { insert(root,A[i],i,0,n-1); } for(int i=0;i<m;i++) { int type=in.nextInt(); if(type==1) { update(root,in.nextInt()-1,in.nextInt()-1,0,n-1); }else { out.println(query(root,in.nextInt()-1,in.nextInt()-1,0,n-1)); } } } private long query(Node node, int s, int e, int l, int r) { if(l>=s&&r<=e) { return node.sum; } Node lnode=getLnode(node); Node rnode=getRnode(node); long ret=0; int m=(l+r)/2; if(m>=s) { ret+=query(lnode,s,e,l,m); } if(m<e) { ret+=query(rnode,s,e,m+1,r); } return ret; } private void update(Node node,int s, int e,int l,int r) { if(l==r) { node.sum=dp[(int)node.sum]; if(dp[(int)node.sum]==node.sum)node.cnt--; return; } Node lnode=getLnode(node); Node rnode=getRnode(node); int m=(l+r)/2; if(m>=s&&lnode.cnt>0) { update(lnode,s,e,l,m); } if(m<e&&rnode.cnt>0) { update(rnode,s,e,m+1,r); } node.sum=lnode.sum+rnode.sum; node.cnt=lnode.cnt+rnode.cnt; } private void insert(Node node, long v,int idx, int l, int r) { if(l==r) { node.sum=v; if(dp[(int)v]!=v)node.cnt++; return; } int m=(l+r)/2; Node lnode=getLnode(node); Node rnode=getRnode(node); if(idx<=m) { insert(lnode,v,idx,l,m); }else { insert(rnode,v,idx,m+1,r); } node.cnt=lnode.cnt+rnode.cnt; node.sum=lnode.sum+rnode.sum; } private Node getRnode(Node node) { if(node.rnode==null) node.rnode=new Node(); return node.rnode; } private Node getLnode(Node node) { if(node.lnode==null) node.lnode=new Node(); return node.lnode; } class Node{ Node lnode,rnode; int cnt; long sum; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { if(st==null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
Java
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
2 seconds
["30\n13\n4\n22"]
null
Java 8
standard input
[ "data structures", "dsu", "number theory", "brute force" ]
078cdef32cb5e60dc66c66cae3d4a57a
The first line contains two integers n and m (1 ≀ n, m ≀ 3Β·105) β€” the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 106) β€” the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n). There is at least one SUM query.
2,000
For each SUM query print the answer to it.
standard output
PASSED
bbf145728bf95bdf0a678b657697209c
train_000.jsonl
1517582100
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r β€” for every replace ai with D(ai); SUM l r β€” calculate . Print the answer for each SUM query.
256 megabytes
import java.util.*; import java.io.*; public class F { String INPUT = "7 6\n" + "6 4 1 10 3 2 4\n" + "2 1 7\n" + "2 4 5\n" + "1 3 5\n" + "2 4 4\n" + "1 5 7\n" + "2 1 7"; int N = 1000005; int[] d = new int[N]; Pair[] t = new Pair[4*N]; int[] a = new int[N]; void solve() { preprocess(); int n = i(),q = i(); for (int i = 1; i <=n ; i++) { a[i] = i(); } build(1,1,n); while(q-->0) { int type = i(), l = i(), r= i(); if(type==2) { out.println(query(1,1,n,l,r)); } else { update(1,1,n,l,r); } } } void build(int n,int s,int e) { if(s==e) { t[n] = new Pair(a[s],a[s]==1?1:0); return; } int m = (s+e)>>1; build(2*n,s,m); build(2*n+1,m+1,e); t[n] = new Pair(t[2*n].a+t[2*n+1].a,0); } void update(int n,int s,int e,int l,int r) { if(l>e || r<s) return; if(e-s+1 == t[n].b) return; if(s == e) { int x = d[(int)t[n].a]; if(x == 2) t[n].b = 1; t[n].a = x; return; } int m = (s+e)>>1; update(2*n,s,m,l,r); update(2*n+1,m+1,e,l,r); t[n].a = t[2*n].a + t[2*n+1].a; t[n].b = t[2*n].b + t[2*n+1].b; } long query(int n,int s,int e,int l,int r) { if(l>e || r<s) return 0; if(l<=s && r>=e) return t[n].a; int m = (s+e)>>1; long p = query(2*n,s,m,l,r); long q = query(2*n+1,m+1,e,l,r); return p+q; } static class Pair{ long a,b; Pair(long a,long b){this.a = a; this.b = b;} } private void preprocess() { d[1] = 1; for (int i = 2; i <N ; i++) { d[i]++; for (int j = i; j<N ; j+=i) d[j]++; } } void run() throws Exception{ is = oj ? System.in: new ByteArrayInputStream(INPUT.getBytes()); //is = System.in; out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args)throws Exception { new F().run(); } InputStream is; PrintWriter out; 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 d() { return Double.parseDouble(s()); } private char c() { return (char)skip(); } private String s() { 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[] sa(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] = sa(m); return map; } private int[] ia(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = i(); return a; } private int i() { 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 l() { 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
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
2 seconds
["30\n13\n4\n22"]
null
Java 8
standard input
[ "data structures", "dsu", "number theory", "brute force" ]
078cdef32cb5e60dc66c66cae3d4a57a
The first line contains two integers n and m (1 ≀ n, m ≀ 3Β·105) β€” the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 106) β€” the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n). There is at least one SUM query.
2,000
For each SUM query print the answer to it.
standard output
PASSED
51606ac87c1b1d25e948761e717bc1a9
train_000.jsonl
1517582100
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r β€” for every replace ai with D(ai); SUM l r β€” calculate . Print the answer for each SUM query.
256 megabytes
import java.io.*; import java.util.*; public class F { FastScanner in; PrintWriter out; boolean systemIO = true; int[] divisors; int INF = (int) 1e6; int[] ones; public void solve() throws IOException { precalc(); int n = in.nextInt(); int m = in.nextInt(); long tree[] = new long[4 * n]; int a[] = new int[n]; ones = new int[n]; for (int i = 0; i < n; ++i) { a[i] = in.nextInt(); if (i == 0) { ones[i] = (a[i] == 1 ? 1 : 0); continue; } ones[i] = ones[i - 1] + (a[i] == 1 ? 1 : 0); } build(tree, 0, 0, n - 1, a); for (int i = 0; i < m; ++i) { int t = in.nextInt(); if (t == 1) { int l = in.nextInt(); int r = in.nextInt(); modify(tree, 0, 0, n - 1, l - 1, r - 1); } else { int l = in.nextInt(); int r = in.nextInt(); out.println(query(tree, 0, 0, n - 1, l - 1, r - 1)); } } } private void precalc() { divisors = new int[INF + 1]; for (int i = 1; i <= INF; ++i) { for (int j = i; j <= INF; j += i) { ++divisors[j]; } } } private void build(long[] tree, int v, int vl, int vr, int[] a) { if (vl == vr) { tree[v] = a[vl]; return; } int vm = (vl + vr) / 2; build(tree, 2 * v + 1, vl, vm, a); build(tree, 2 * v + 2, vm + 1, vr, a); tree[v] = tree[2 * v + 1] + tree[2 * v + 2]; } private long query(long[] tree, int v, int vl, int vr, int ql, int qr) { if (ql > vr || vl > qr) return 0; if (ql <= vl && vr <= qr) return tree[v]; int vm = (vl + vr) / 2; return query(tree, 2 * v + 1, vl, vm, ql, qr) + query(tree, 2 * v + 2, vm + 1, vr, ql, qr); } private void modify(long[] tree, int v, int vl, int vr, int ql, int qr) { if (ql > vr || vl > qr) return; if (ql <= vl && vr <= qr) { int cntOnes = getOnes(vl, vr); if ((tree[v] - cntOnes) == 2L * (vr - vl + 1 - cntOnes)) return; if (vl == vr) { tree[v] = divisors[(int) tree[v]]; return; } } int vm = (vl + vr) / 2; modify(tree, 2 * v + 1, vl, vm, ql, qr); modify(tree, 2 * v + 2, vm + 1, vr, ql, qr); tree[v] = tree[2 * v + 1] + tree[2 * v + 2]; } private int getOnes(int vl, int vr) { return ones[vr] - (vl > 0 ? ones[vl - 1] : 0); } public void run() { try { if (systemIO) { in = new FastScanner(System.in); out = new PrintWriter(System.out); } else { in = new FastScanner(new File("input.txt")); out = new PrintWriter(new File("output.txt")); } solve(); out.close(); } catch (IOException e) { e.printStackTrace(); } } class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } String next() { while (st == null || !st.hasMoreTokens()) { 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()); } } public static void main(String[] arg) { new F().run(); } }
Java
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
2 seconds
["30\n13\n4\n22"]
null
Java 8
standard input
[ "data structures", "dsu", "number theory", "brute force" ]
078cdef32cb5e60dc66c66cae3d4a57a
The first line contains two integers n and m (1 ≀ n, m ≀ 3Β·105) β€” the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 106) β€” the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n). There is at least one SUM query.
2,000
For each SUM query print the answer to it.
standard output
PASSED
d655499dd34d42909ed483e99845244e
train_000.jsonl
1517582100
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r β€” for every replace ai with D(ai); SUM l r β€” calculate . Print the answer for each SUM query.
256 megabytes
import java.util.*; import java.io.*; public class F { static int segmax[]; static long segsum[]; static int a[]; static int l, r; static int D[]; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()), m = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); a = new int[n+1]; for(int i=1;i<=n;i++) a[i] = Integer.parseInt(st.nextToken()); D = divisors(); segmax = new int[n*4]; segsum = new long[n*4]; build(1, 1, n); StringBuffer sb = new StringBuffer(); while(m-->0){ st = new StringTokenizer(br.readLine()); int i = Integer.parseInt(st.nextToken()); l = Integer.parseInt(st.nextToken()); r = Integer.parseInt(st.nextToken()); if(i==1){ replace(1, 1, n); } else{ sb.append(query(1, 1, n)+"\n"); } } System.out.print(sb); } static long query(int idx, int L, int R) { if(l<=L && R<=r) return segsum[idx]; int M = (L+R)/2; long sum = 0; if(l<=M) sum += query(idx*2, L, M); if(r>M) sum += query(idx*2 + 1 , M+1, R); return sum; } static void replace(int idx, int L, int R) { if(segmax[idx] <= 2) return; if(L==R){ a[L] = D[a[L]]; segsum[idx] = a[L]; segmax[idx] = a[L]; return; } int M = (L+R)/2; if(l<=M) replace(idx*2, L, M); if(r>M) replace(idx*2 + 1 , M+1, R); segmax[idx] = Math.max(segmax[idx*2], segmax[idx*2+1]); segsum[idx] = segsum[idx*2] + segsum[idx*2+1]; } static void build(int idx, int L, int R) { if(L==R){ segmax[idx] = a[L]; segsum[idx] = a[L]; return; } int M = (L+R)/2; build(idx*2, L, M); build(idx*2 + 1 , M+1, R); segmax[idx] = Math.max(segmax[idx*2], segmax[idx*2+1]); segsum[idx] = segsum[idx*2] + segsum[idx*2+1]; } static int[] divisors() { int D[] = new int[1000001]; for(int i=1;i<D.length;i++){ for(int j=i;j<D.length;j+=i){ D[j]++; } } return D; } }
Java
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
2 seconds
["30\n13\n4\n22"]
null
Java 8
standard input
[ "data structures", "dsu", "number theory", "brute force" ]
078cdef32cb5e60dc66c66cae3d4a57a
The first line contains two integers n and m (1 ≀ n, m ≀ 3Β·105) β€” the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 106) β€” the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n). There is at least one SUM query.
2,000
For each SUM query print the answer to it.
standard output
PASSED
f8ad89e0a01d984fd294c057b4b4ccb8
train_000.jsonl
1517582100
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r β€” for every replace ai with D(ai); SUM l r β€” calculate . Print the answer for each SUM query.
256 megabytes
import java.util.*; public class F { static int segmax[]; static long segsum[]; static long pfsum[]; static int a[]; static int l, r; static int D[]; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(), m = sc.nextInt(); a = new int[n+1]; for(int i=1;i<=n;i++) a[i] = sc.nextInt(); D = divisors(); pfsum = new long[n+1]; for(int i=1;i<n+1;i++) pfsum[i] = pfsum[i-1] + a[i]; segmax = new int[n*4]; segsum = new long[n*4]; build(1, 1, n); StringBuffer sb = new StringBuffer(); while(m-->0){ int i = sc.nextInt(); l = sc.nextInt(); r = sc.nextInt(); if(i==1){ replace(1, 1, n); } else{ sb.append(query(1, 1, n)+"\n"); } } System.out.print(sb); } static long query(int idx, int L, int R) { if(l<=L && R<=r) return segsum[idx]; int M = (L+R)/2; long sum = 0; if(l<=M) sum += query(idx*2, L, M); if(r>M) sum += query(idx*2 + 1 , M+1, R); return sum; } static void replace(int idx, int L, int R) { if(segmax[idx] <= 2) return; if(L==R){ a[L] = D[a[L]]; segsum[idx] = a[L]; segmax[idx] = a[L]; return; } int M = (L+R)/2; if(l<=M) replace(idx*2, L, M); if(r>M) replace(idx*2 + 1 , M+1, R); segmax[idx] = Math.max(segmax[idx*2], segmax[idx*2+1]); segsum[idx] = segsum[idx*2] + segsum[idx*2+1]; } static void build(int idx, int L, int R) { if(L==R){ segmax[idx] = a[L]; segsum[idx] = a[L]; return; } int M = (L+R)/2; build(idx*2, L, M); build(idx*2 + 1 , M+1, R); segmax[idx] = Math.max(segmax[idx*2], segmax[idx*2+1]); segsum[idx] = segsum[idx*2] + segsum[idx*2+1]; } static int[] divisors() { int D[] = new int[1000001]; for(int i=1;i<D.length;i++){ for(int j=i;j<D.length;j+=i){ D[j]++; } } return D; } }
Java
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
2 seconds
["30\n13\n4\n22"]
null
Java 8
standard input
[ "data structures", "dsu", "number theory", "brute force" ]
078cdef32cb5e60dc66c66cae3d4a57a
The first line contains two integers n and m (1 ≀ n, m ≀ 3Β·105) β€” the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 106) β€” the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n). There is at least one SUM query.
2,000
For each SUM query print the answer to it.
standard output
PASSED
a74040b68fa7c1cd0abb6dbeedd02a67
train_000.jsonl
1517582100
Let D(x) be the number of positive divisors of a positive integer x. For example, D(2) = 2 (2 is divisible by 1 and 2), D(6) = 4 (6 is divisible by 1, 2, 3 and 6).You are given an array a of n integers. You have to process two types of queries: REPLACE l r β€” for every replace ai with D(ai); SUM l r β€” calculate . Print the answer for each SUM query.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { void solve() { int n=ni(),m=ni(); cnt=new int[1000001]; for(int i=1;i<=1e6;i++){ for(int j=i;j<=1e6;j+=i) cnt[j]++; } constant=new boolean[4*n+1]; tree=new long[4*n+1]; a=new int[n+1]; for(int i=1;i<=n;i++) { a[i] = ni(); } build(1,1,n); while(m-->0){ int t=ni(),l=ni(),r=ni(); if(t==1){ update(1,l,r,1,n); }else { long ans=querry(1,l,r,1,n); pw.println(ans); } } } int cnt[]; long tree[]; boolean constant[]; int a[]; void build(int id,int l,int r){ if(l==r){ tree[id]=a[l]; if(a[l]<=2) constant[id]=true; }else { int mid=(l+r)/2; build(2*id,l,mid); build(2*id+1,mid+1,r); tree[id]=tree[2*id]+tree[2*id+1]; constant[id]=constant[2*id] && constant[2*id+1]; } } void update(int id,int x,int y,int l,int r){ if(r<x || l>y) return; if(constant[id]) return; if(l==r){ a[l]=cnt[a[l]]; tree[id]=a[l]; if(a[l]<=2) constant[id]=true; return; } int mid=(l+r)/2; update(2*id,x,y,l,mid); update(2*id+1,x,y,mid+1,r); tree[id]=tree[2*id]+tree[2*id+1]; constant[id]=constant[2*id] && constant[2*id+1]; } long querry(int id,int x,int y,int l,int r){ if(r<x || l>y) return 0; if(x<=l && r<=y) return tree[id]; int mid=(l+r)/2; return querry(2*id,x,y,l,mid)+querry(2*id+1,x,y,mid+1,r); } long M=(long)1e9+7; InputStream is; PrintWriter pw; String INPUT = ""; void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); pw = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); pw.flush(); if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new Main().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); } }
Java
["7 6\n6 4 1 10 3 2 4\n2 1 7\n2 4 5\n1 3 5\n2 4 4\n1 5 7\n2 1 7"]
2 seconds
["30\n13\n4\n22"]
null
Java 8
standard input
[ "data structures", "dsu", "number theory", "brute force" ]
078cdef32cb5e60dc66c66cae3d4a57a
The first line contains two integers n and m (1 ≀ n, m ≀ 3Β·105) β€” the number of elements in the array and the number of queries to process, respectively. The second line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 106) β€” the elements of the array. Then m lines follow, each containing 3 integers ti, li, ri denoting i-th query. If ti = 1, then i-th query is REPLACE li ri, otherwise it's SUM li ri (1 ≀ ti ≀ 2, 1 ≀ li ≀ ri ≀ n). There is at least one SUM query.
2,000
For each SUM query print the answer to it.
standard output
PASSED
be917294308ea0c7c02d153f4827efc4
train_000.jsonl
1346081400
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.
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); C219 solver = new C219(); solver.solve(1, in, out); out.close(); } static class C219 { int N; int K; int[] stripe; Integer[][] memo; char[] alp = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(); public int fook(int ind, int nono) { int best = N + 2; for (int i = 0; i < K; i++) { if (i == nono) continue; best = Math.min(best, memo[ind][i]); } return best; } public int iterativedp() { for (int i = N - 1; i >= 0; i--) { for (int j = 0; j < K; j++) { if (j == stripe[i]) { memo[i][j] = 1 + fook(i + 1, j); } else { memo[i][j] = memo[i + 1][stripe[i]]; } } } int min = N + 2; for (int i = 0; i < K; i++) min = Math.min(min, memo[0][i]); return min; } public void solve(int testNumber, Scanner s, PrintWriter out) { N = s.nextInt(); K = s.nextInt(); if (N == 1) { out.println(0); out.println(s.next()); return; } stripe = new int[N]; char[] spots = s.next().toCharArray(); for (int i = 0; i < N; i++) stripe[i] = spots[i] - 'A'; memo = new Integer[N + 1][26]; Arrays.fill(memo[N], 0); // memo[N][stripe[N - 1]] = 1; int prev = 0; while (prev == stripe[0] || prev == stripe[1]) prev++; if (K != 26) prev = K; int score = iterativedp(); out.println(score); // for(Integer[] row : memo) // out.println(Arrays.toString(row)); for (int i = 0; i < N - 1; i++) { // if all future scores are equal, don't change int foundlow = -1; for (int j = 0; j < K; j++) { if (j == prev) continue; if (memo[i + 1][j] == score - 1) { foundlow = j; score--; break; } } if (foundlow == -1) { out.print(alp[stripe[i]]); prev = stripe[i]; } else { out.print(alp[foundlow]); prev = foundlow; } } if (score == 0) out.print(alp[stripe[N - 1]]); else { for (int i = 0; i < K; i++) { if (i == prev) continue; if (memo[N - 1][i] == 0) { out.print(alp[i]); break; } } } out.println(); } } }
Java
["6 3\nABBACC", "3 2\nBBB"]
2 seconds
["2\nABCACA", "1\nBAB"]
null
Java 8
standard input
[ "dp", "greedy", "brute force" ]
0ecf60ea733eba71ef1cc1e736296d96
The first input line contains two integers n and k (1 ≀ n ≀ 5Β·105;Β 2 ≀ k ≀ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.
1,600
Print a single integer β€” the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.
standard output
PASSED
3e92aeb44bbca56a76264db0451d1a42
train_000.jsonl
1346081400
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.
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); C219 solver = new C219(); solver.solve(1, in, out); out.close(); } static class C219 { int N; int K; int[] stripe; Integer[][] memo; char[] alp = "ABCDEFGHIJKLMNOPQRSTUVWXYZdab".toCharArray(); public int fook(int ind, int nono) { int best = N + 2; for (int i = 0; i < K; i++) { if (i == nono) continue; best = Math.min(best, memo[ind][i]); } return best; } public int iterativedp() { for (int i = N - 1; i >= 0; i--) { for (int j = 0; j < K; j++) { if (j == stripe[i]) { memo[i][j] = 1 + fook(i + 1, j); } else { memo[i][j] = memo[i + 1][stripe[i]]; } } } int min = N + 2; for (int i = 0; i < K; i++) min = Math.min(min, memo[0][i]); return min; } public void solve(int testNumber, Scanner s, PrintWriter out) { N = s.nextInt(); K = s.nextInt(); if (N == 1) { out.println(0); out.println(s.next()); return; } stripe = new int[N]; char[] spots = s.next().toCharArray(); for (int i = 0; i < N; i++) stripe[i] = spots[i] - 'A'; memo = new Integer[N + 1][26]; Arrays.fill(memo[N], 0); // memo[N][stripe[N - 1]] = 1; int prev = 0; while (prev == stripe[0] || prev == stripe[1]) prev++; if (K != 26) prev = K; int score = iterativedp(); out.println(score); // for(Integer[] row : memo) // out.println(Arrays.toString(row)); for (int i = 0; i < N - 1; i++) { // if all future scores are equal, don't change int foundlow = -1; for (int j = 0; j < K; j++) { if (j == prev) continue; if (memo[i + 1][j] == score - 1) { foundlow = j; score--; break; } } if (foundlow == -1) { out.print(alp[stripe[i]]); prev = stripe[i]; } else { out.print(alp[foundlow]); prev = foundlow; } } if (score == 0) out.println(alp[stripe[N - 1]]); else { for (int i = 0; i < K; i++) { if (i == prev) continue; if (memo[N - 1][i] == 0) { out.println(alp[i]); break; } } } } } }
Java
["6 3\nABBACC", "3 2\nBBB"]
2 seconds
["2\nABCACA", "1\nBAB"]
null
Java 8
standard input
[ "dp", "greedy", "brute force" ]
0ecf60ea733eba71ef1cc1e736296d96
The first input line contains two integers n and k (1 ≀ n ≀ 5Β·105;Β 2 ≀ k ≀ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.
1,600
Print a single integer β€” the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.
standard output
PASSED
0208817c8d7c082f0e035c66056343c3
train_000.jsonl
1346081400
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.
256 megabytes
//package DP; import java.io.*; import java.util.*; import java.util.Map.Entry; import java.text.*; import java.math.*; import java.util.regex.*; import java.awt.Point; /** * * @author prabhat // use stringbuilder,TreeSet, priorityQueue, x+y=(x&y + x|y); */ public class dp6 { public static int a[],n,max1=100005,k,m,cnt,w[],v[],dp[][],we[],ve[]; public static long mod=(long)1e9+7; public static boolean[] isPrime; public static ArrayList<Integer> divisor[],prime,adj[]; public static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static PrintWriter pw; public static void main(String[] args) throws Exception { InputReader in = new InputReader(System.in); pw=new PrintWriter(System.out); n=in.ii(); k=in.ii(); char[] s=in.is().toCharArray(); if(k<=2) { pw.println(solve1(s,n)); pw.println(new String(s)); } else{ pw.println(solve2(s,n)); pw.println(new String(s)); } pw.close(); } static int solve2(char[]s,int n) { int x=0; for(int i=1;i<n;i++) { if(s[i]==s[i-1]) { for(char c='A';c<='C';c++) { if(c!=s[i-1]&&( i==n-1||c!= s[i+1])) { s[i]=c; x++; break; } } } } return x; } static int solve1(char[] s,int n) { int x=0; int y=0; char cx='A',cy='B',temp; for(int i=0;i<n;i++) { if(s[i]!=cx)x++; if(s[i]!=cy)y++; temp=cx; cx=cy; cy=temp; } cx=x<y?'B':'A'; for(int i=0;i<n;i++) { cx=(char)((cx-'A'+1)%2+'A'); s[i]=cx; } return Math.min(x,y); } public static class DSU { int[] parent; int[] rank; int cnt; public DSU(int n){ parent=new int[n]; rank=new int[n]; for(int i=0;i<n;i++){ parent[i]=i; rank[i]=1; } cnt=n; } int find(int i){ while(parent[i] !=i){ parent[i]=parent[parent[i]]; i=parent[i]; } return i; } int Union(int x, int y){ int xset = find(x); int yset = find(y); if(xset!=yset) cnt--; if(rank[xset]<rank[yset]){ parent[xset] = yset; rank[yset]+=rank[xset]; rank[xset]=0; return yset; }else{ parent[yset]=xset; rank[xset]+=rank[yset]; rank[yset]=0; return xset; } } } static int gcd(int a,int b) { while(a!=0) { int temp=a; a=b%a; b=temp; } return b; } static void Seive() { isPrime=new boolean[max1]; Arrays.fill(isPrime,true); prime=new ArrayList<>(); divisor=new ArrayList[max1]; for(int i=1;i<max1;i++)divisor[i]=new ArrayList<Integer>(); isPrime[0]=isPrime[1]=false; for(int i=2;i<(max1);i++) { if(isPrime[i]){ divisor[i].add(i); prime.add(i); for(int j=2*i;j<max1;j+=i) { isPrime[j]=false; divisor[j].add(i); } } } } public static long pow(long n,long p,long m) { long result = 1; if(p==0) return 1; while(p!=0) { if(p%2==1) result *= n; if(result>=m) result%=m; p >>=1; n*=n; if(n>=m) n%=m; } return result; } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private SpaceCharFilter filter; byte inbuffer[] = new byte[1024]; int lenbuffer = 0, ptrbuffer = 0; final int M = (int) 1e9 + 7; int md=(int)(1e7+1); int[] SMP=new int[md]; final double eps = 1e-6; final double pi = Math.PI; PrintWriter out; String check = ""; InputStream obj = check.isEmpty() ? System.in : new ByteArrayInputStream(check.getBytes()); public InputReader(InputStream stream) { this.stream = stream; } int readByte() { if (lenbuffer == -1) throw new InputMismatchException(); if (ptrbuffer >= lenbuffer) { ptrbuffer = 0; try { lenbuffer = obj.read(inbuffer); } catch (IOException e) { throw new InputMismatchException(); } } if (lenbuffer <= 0) return -1; return inbuffer[ptrbuffer++]; } public int read() { 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; } String is() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) // when nextLine, (isSpaceChar(b) && b!=' ') { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public int ii() { 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(); } } public long il() { 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(); } } boolean isSpaceChar(int c) { return (!(c >= 33 && c <= 126)); } int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } float nf() { return Float.parseFloat(is()); } double id() { return Double.parseDouble(is()); } char ic() { return (char) skip(); } int[] iia(int n) { int a[] = new int[n]; for (int i = 0; i<n; i++) a[i] = ii(); return a; } long[] ila(int n) { long a[] = new long[n]; for (int i = 0; i <n; i++) a[i] = il(); return a; } String[] isa(int n) { String a[] = new String[n]; for (int i = 0; i < n; i++) a[i] = is(); return a; } long mul(long a, long b) { return a * b % M; } long div(long a, long b) { return mul(a, pow(b, M - 2,M)); } double[][] idm(int n, int m) { double a[][] = new double[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[i][j] = id(); return a; } int[][] iim(int n, int m) { int a[][] = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j <m; j++) a[i][j] = ii(); return a; } public String readLine() { 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 interface SpaceCharFilter { public boolean isSpaceChar(int ch); } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["6 3\nABBACC", "3 2\nBBB"]
2 seconds
["2\nABCACA", "1\nBAB"]
null
Java 8
standard input
[ "dp", "greedy", "brute force" ]
0ecf60ea733eba71ef1cc1e736296d96
The first input line contains two integers n and k (1 ≀ n ≀ 5Β·105;Β 2 ≀ k ≀ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.
1,600
Print a single integer β€” the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.
standard output
PASSED
2f37dd34c38961c367d4ed06cb62eae9
train_000.jsonl
1346081400
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.
256 megabytes
import java.util.*; import java.io.*; public class lol { public static char r(char a,char b,int k) { for(int h=0;h<k;h++) { if(a-'A'!=h && b-'A'!=h) return (char)(h+'A'); } return 'A'; } public static int calc(int k,char[] str,int changes) { for(int h=0;h<str.length;h+=1) { if(h+2<str.length && str[h]==str[h+1] && str[h+1]==str[h+2]) { str[h+1]=r(str[h],str[h+2],k); changes++; } else if(h+2<str.length && str[h]==str[h+1]) { str[h+1]=r(str[h],str[h+2],k); changes++; } else if(h+1<str.length && str[h]==str[h+1]) { str[h+1]=r(str[h],str[h],k); changes++; } } return changes; } public static void main(String[] args) throws IOException { Scanner s = new Scanner(System.in); int n = s.nextInt(); int k = s.nextInt(); char[] str = s.next().toCharArray(); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); int changes=0; int changes2=0; if(k==2) { for(int h=0;h<n;h++) { if(h%2==0) { if(str[h]!='A') changes++; else changes2++; } else { if(str[h]!='B') changes++; else changes2++; } } changes=Math.min(changes,changes2); out.write(Integer.toString(changes)+"\n"); char st='A'; if(changes==changes2) st='B'; for(int h=0;h<n;h++) { out.write(st); st=st=='A'?'B':'A'; } out.flush(); out.close(); return; } changes = calc(k,str,changes); out.write(Integer.toString(changes)+"\n"); for(int h=0;h<n;h++) out.write(str[h]); out.flush(); out.close(); } }
Java
["6 3\nABBACC", "3 2\nBBB"]
2 seconds
["2\nABCACA", "1\nBAB"]
null
Java 8
standard input
[ "dp", "greedy", "brute force" ]
0ecf60ea733eba71ef1cc1e736296d96
The first input line contains two integers n and k (1 ≀ n ≀ 5Β·105;Β 2 ≀ k ≀ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.
1,600
Print a single integer β€” the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.
standard output
PASSED
d9f8e233a46dab8412db71b16fab374c
train_000.jsonl
1346081400
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.
256 megabytes
/** * DA-IICT * Author : PARTH PATEL */ import java.io.*; import java.math.*; import java.util.*; import static java.util.Arrays.fill; import static java.lang.Math.*; import static java.util.Arrays.sort; import static java.util.Collections.sort; public class C219 { public static int mod = 1000000007; static FasterScanner in = new FasterScanner(); static PrintWriter out = new PrintWriter(System.out); static int maxn = (int) (1e5 + 2); static ArrayList<Integer>[] adjacencylist = new ArrayList[maxn]; static boolean[] visited = new boolean[maxn]; static int[] color = new int[maxn]; public static void main(String[] args) { int n=in.nextInt(); int k=in.nextInt(); int ans=0; StringBuilder sb=new StringBuilder(in.nextLine()); char[] carr=sb.toString().toCharArray(); if(n==1) { System.out.println("0"); System.out.println(sb.toString()); return; } if(k>2) { for(int i=1;i<n-1;i++) { if(carr[i]==carr[i-1]) { for(char c='A';c<='A'+k;c++) { if(carr[i-1]!=c && carr[i+1]!=c) { ans++; carr[i]=c; break; } } } } if(carr[n-1]==carr[n-2]) { for(char c='A';c<='A'+k;c++) { if(carr[n-2]!=c) { ans++; carr[n-1]=c; break; } } } out.println(ans); for(int i=0;i<n;i++) out.print(carr[i]); } else { StringBuilder sb1=new StringBuilder(); StringBuilder sb2=new StringBuilder(); for(int i=0;i<n;i++) { if(i%2==0) { sb1.append("A"); sb2.append("B"); } else { sb1.append("B"); sb2.append("A"); } } int count1=0,count2=0; for(int i=0;i<n;i++) { if(sb1.charAt(i)!=sb.charAt(i)) count1++; if(sb2.charAt(i)!=sb.charAt(i)) count2++; } if(count1<count2) { out.println(count1); out.println(sb1.toString()); } else { out.println(count2); out.println(sb2.toString()); } } out.close(); } public static void dfs(int vertex) { visited[vertex] = true; for (int i : adjacencylist[vertex]) { if (!visited[i]) { dfs(i); } } } /////////////////SEGMENT TREE (BUILD-UPDATE-QUERY)///////////////////////////// /////////////////UPDATE FOLLOWING METHODS AS PER NEED////////////////////////// /* public static void buildsegmenttree(int node,int start,int end) { if(start==end) { // Leaf node will have a single element segmenttree[node]=arr[start]; } else { int mid=start+(end-start)/2; // Recurse on the left child buildsegmenttree(2*node, start, mid); // Recurse on the right child buildsegmenttree(2*node+1, mid+1, end); // Internal node will have the sum of both of its children segmenttree[node]=segmenttree[2*node]+segmenttree[2*node+1]; } } public static void updatesegmenttree(int node,int start,int end,int idx,int val) { if(start==end) { //Leaf Node arr[idx]+=val; segmenttree[node]+=val; } else { int mid=start+(end-start)/2; if(start<=idx && idx<=mid) { // If idx is in the left child, recurse on the left child updatesegmenttree(2*node, start, mid, idx, val); } else { // if idx is in the right child, recurse on the right child updatesegmenttree(2*node+1, mid+1, end, idx, val); } // Internal node will have the sum of both of its children segmenttree[node]=segmenttree[2*node]+segmenttree[2*node+1]; } } public static long querysegmenttree(int node,int start,int end,int l,int r) { if(r<start || end<l) { // range represented by a node is completely outside the given range return 0; } if(l <= start && end <= r) { // range represented by a node is completely inside the given range return segmenttree[node]; } // range represented by a node is partially inside and partially outside the given range int mid=start+(end-start)/2; long leftchild=querysegmenttree(2*node, start, mid, l, r); long rightchild=querysegmenttree(2*node+1, mid+1, end, l, r); return (leftchild+rightchild); } */ public static long pow(long x, long n, long mod) { long res = 1; for (long p = x; n > 0; n >>= 1, p = (p * p) % mod) { if ((n & 1) != 0) { res = (res * p % mod); } } return res; } public static long gcd(long n1, long n2) { long r; while (n2 != 0) { r = n1 % n2; n1 = n2; n2 = r; } return n1; } public static long lcm(long n1, long n2) { long answer = (n1 * n2) / (gcd(n1, n2)); return answer; } static class FasterScanner { private byte[] buf = new byte[1024]; private int curChar; private int snumChars; public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["6 3\nABBACC", "3 2\nBBB"]
2 seconds
["2\nABCACA", "1\nBAB"]
null
Java 8
standard input
[ "dp", "greedy", "brute force" ]
0ecf60ea733eba71ef1cc1e736296d96
The first input line contains two integers n and k (1 ≀ n ≀ 5Β·105;Β 2 ≀ k ≀ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.
1,600
Print a single integer β€” the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.
standard output
PASSED
634a6bcdd4989d06fffaab9cf9807a1a
train_000.jsonl
1346081400
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.
256 megabytes
import java.io.*; import java.util.*; public class CF_219_C_COLOR_STRIPE { static final int INF = (int) 1e9; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); char[] a = sc.next().toCharArray(); int memo[][] = new int[n + 1][k]; int ans = INF; for (int idx = n - 1; idx >= 0; idx--) for (int last = 0; last < k; last++) { int take = INF; int leave = INF; if (last != a[idx] - 'A') leave = memo[idx + 1][a[idx] - 'A']; else if (last == a[idx] - 'A') for (char ch = 'A'; ch < 'A' + k; ch++) { if (last != ch - 'A') take = Math.min(take, 1 + memo[idx + 1][ch - 'A']); } memo[idx][last] = Math.min(take, leave); } for (int i = 0; i < k; i++) ans = Math.min(ans, memo[0][i]); System.out.println(ans); int last = -1; for (char ch = 'A'; ch < 'A' + k; ch++) { if (ch == a[0] && memo[1][a[0] - 'A'] == ans) { last = a[0] - 'A'; break; } else if (ch != a[0] && 1 + memo[1][ch - 'A'] == ans) { last = ch - 'A'; break; } } StringBuilder st = new StringBuilder(); st.append((char) (last + 'A')); for (int idx = 1; idx < n; idx++) { int optimal = memo[idx][last]; if (last != a[idx] - 'A' && optimal == memo[idx + 1][a[idx] - 'A']) st.append((char) ((last = a[idx] - 'A') + 'A')); else if (last == a[idx] - 'A') for (char ch = 'A'; ch < 'A' + k; ch++) if (last != ch - 'A' && 1 + memo[idx + 1][ch - 'A'] == optimal) { st.append((char) ((last = ch - 'A') + 'A')); break; } } System.out.println(st); } 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()); } } }
Java
["6 3\nABBACC", "3 2\nBBB"]
2 seconds
["2\nABCACA", "1\nBAB"]
null
Java 8
standard input
[ "dp", "greedy", "brute force" ]
0ecf60ea733eba71ef1cc1e736296d96
The first input line contains two integers n and k (1 ≀ n ≀ 5Β·105;Β 2 ≀ k ≀ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.
1,600
Print a single integer β€” the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.
standard output
PASSED
6ceb92115ddd0d9222304508301bc125
train_000.jsonl
1346081400
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.
256 megabytes
import java.io.*; import java.util.*; public class CF_219_C_COLOR_STRIPE { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); char[] c = sc.next().toCharArray(); int ans = 0; if (k == 2) { char[] ab = new char[n]; char[] ba = new char[n]; int ch = 0; int ans1 = 0; int ans2 = 0; for (int i = 0; i < n; i++) { ab[i] = (char) (ch + 'A'); ba[i] = (char) ((ch ^ 1) + 'A'); if (ab[i] != c[i]) ans1++; if (ba[i] != c[i]) ans2++; ch ^= 1; } ans = Math.min(ans1, ans2); c = ans1 < ans2 ? ab : ba; } else for (int i = 1; i < n; i++) if (c[i - 1] == c[i]) for (char ch = 'A'; ch < k + 'A'; ch++) if (ch != c[i - 1] && (i == n - 1 || ch != c[i + 1])) { ans++; c[i] = ch; break; } System.out.println(ans); System.out.println(c); } 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 { 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
["6 3\nABBACC", "3 2\nBBB"]
2 seconds
["2\nABCACA", "1\nBAB"]
null
Java 8
standard input
[ "dp", "greedy", "brute force" ]
0ecf60ea733eba71ef1cc1e736296d96
The first input line contains two integers n and k (1 ≀ n ≀ 5Β·105;Β 2 ≀ k ≀ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.
1,600
Print a single integer β€” the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.
standard output
PASSED
25ad7fd2f637af64885ccff86dff32ca
train_000.jsonl
1346081400
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class CF_219_C_COLOR_STRIPE { static int memo[][]; static int n, k; static char[] a; static final int INF = (int) 1e9; static void print(int iidx, int last) { for (int idx = 1; idx < n; idx++) { int optimal = memo[idx][last]; int leave = INF; int take = INF; if (last != a[idx] - 'A') { leave = memo[idx + 1][a[idx] - 'A']; } if (leave == optimal) { st.append((char) (a[idx])); last = a[idx] - 'A'; } else if (last == a[idx] - 'A') for (char ch = 'A'; ch < 'A' + k; ch++) if (last != ch - 'A') { int curr = 1 + memo[idx + 1][ch - 'A']; take = Math.min(take, 1 + memo[idx + 1][ch - 'A']); if (curr == optimal) { st.append((char) (ch)); last = ch - 'A'; break; } } } } static StringBuilder st = new StringBuilder(); public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); n = sc.nextInt(); k = sc.nextInt(); a = sc.next().toCharArray(); memo = new int[n + 1][k]; int ans = INF; for (int idx = n - 1; idx >= 0; idx--) { for (int last = 0; last < k; last++) { int take = INF; int leave = INF; if (last != a[idx] - 'A') leave = memo[idx + 1][a[idx] - 'A']; else if (last == a[idx] - 'A') for (char ch = 'A'; ch < 'A' + k; ch++) { if (last != ch - 'A') take = Math.min(take, 1 + memo[idx + 1][ch - 'A']); } memo[idx][last] = Math.min(take, leave); } } for (int i = 0; i < k; i++) { if (ans >= memo[0][i]) ans = memo[0][i]; } System.out.println(ans); for (char ch = 'A'; ch < 'A' + k; ch++) { if (ch == a[0]) { int curr = memo[1][a[0] - 'A']; if (curr == ans) { st.append((char) (a[0])); print(1, a[0] - 'A'); break; } } else if (ch != a[0]) { int curr = 1 + memo[1][ch - 'A']; if (curr == ans) { st.append(ch); print(1, ch - 'A'); break; } } } System.out.println(st); } 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 { 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
["6 3\nABBACC", "3 2\nBBB"]
2 seconds
["2\nABCACA", "1\nBAB"]
null
Java 8
standard input
[ "dp", "greedy", "brute force" ]
0ecf60ea733eba71ef1cc1e736296d96
The first input line contains two integers n and k (1 ≀ n ≀ 5Β·105;Β 2 ≀ k ≀ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.
1,600
Print a single integer β€” the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.
standard output
PASSED
e45dec65b9c183f98f6e3732f95a5f5f
train_000.jsonl
1346081400
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class CF_219_C_COLOR_STRIPE { static int memo[][]; static int n, k; static char[] a; static final int INF = (int) 1e9; static void trace(int last) { for (int idx = 1; idx < n; idx++) { if (last != a[idx] - 'A' && memo[idx + 1][a[idx] - 'A'] == memo[idx][last]) { last = a[idx] - 'A'; st.append((char) (last + 'A')); } else if (last == a[idx] - 'A') for (char ch = 'A'; ch < 'A' + k; ch++) { if (last != ch - 'A' && 1 + memo[idx + 1][ch - 'A'] == memo[idx][last]) { last = ch - 'A'; st.append((char) (last + 'A')); break; } } } } static StringBuilder st = new StringBuilder(); public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); n = sc.nextInt(); k = sc.nextInt(); a = sc.next().toCharArray(); memo = new int[n + 1][k]; int ans = INF; for (int idx = n - 1; idx >= 0; idx--) { for (int last = 0; last < k; last++) { int take = INF; int leave = INF; if (last != a[idx] - 'A') leave = memo[idx + 1][a[idx] - 'A']; else if (last == a[idx] - 'A') for (char ch = 'A'; ch < 'A' + k; ch++) { if (last != ch - 'A') take = Math.min(take, 1 + memo[idx + 1][ch - 'A']); } memo[idx][last] = Math.min(take, leave); } } for (int i = 0; i < k; i++) { if (ans >= memo[0][i]) ans = memo[0][i]; } int last = 0; for (char ch = 'A'; ch < 'A' + k; ch++) { if (ch == a[0]) { int curr = memo[1][a[0] - 'A']; if (curr == ans) { last = a[0] - 'A'; st.append((char) (last + 'A')); break; } } else if (ch != a[0]) { int curr = 1 + memo[1][ch - 'A']; if (curr == ans) { last = ch - 'A'; st.append((char) (last + 'A')); break; } } } System.out.println(ans); trace(last); System.out.println(st); } 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 { 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
["6 3\nABBACC", "3 2\nBBB"]
2 seconds
["2\nABCACA", "1\nBAB"]
null
Java 8
standard input
[ "dp", "greedy", "brute force" ]
0ecf60ea733eba71ef1cc1e736296d96
The first input line contains two integers n and k (1 ≀ n ≀ 5Β·105;Β 2 ≀ k ≀ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.
1,600
Print a single integer β€” the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.
standard output
PASSED
c6c0cce7688259c8caee6561f3891661
train_000.jsonl
1346081400
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.
256 megabytes
import java.io.*; import java.util.*; public class CF_219_C_COLOR_STRIPE { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); char[] c = sc.next().toCharArray(); int ans = 0; if (k == 2) { char[] ab = new char[n]; char[] ba = new char[n]; char ch = 0; for (int i = 0; i < n; i++) { ab[i] = (char) (ch + 'A'); ba[i] = (char) ((ch ^ 1) + 'A'); ch ^= 1; } int ans1 = 0; int ans2 = 0; for (int i = 0; i < n; i++) if (ab[i] != c[i]) ans1++; for (int i = 0; i < n; i++) if (ba[i] != c[i]) ans2++; ans = Math.min(ans1, ans2); c = ans1 < ans2 ? ab : ba; } else for (int i = 1; i < n; i++) if (c[i - 1] == c[i]) for (char ch = 'A'; ch < k + 'A'; ch++) if (ch != c[i - 1] && (i == n - 1 || ch != c[i + 1])) { ans++; c[i] = ch; break; } System.out.println(ans); System.out.println(new String(c)); } 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 { 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
["6 3\nABBACC", "3 2\nBBB"]
2 seconds
["2\nABCACA", "1\nBAB"]
null
Java 8
standard input
[ "dp", "greedy", "brute force" ]
0ecf60ea733eba71ef1cc1e736296d96
The first input line contains two integers n and k (1 ≀ n ≀ 5Β·105;Β 2 ≀ k ≀ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.
1,600
Print a single integer β€” the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.
standard output
PASSED
2e649d560ed242744d8760f15e38b1be
train_000.jsonl
1346081400
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.
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.lang.reflect.Array; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map.Entry; import java.util.Scanner; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.Vector; public class solve { static int k,n; static int[]a ; static int[][] dp = new int[100000*5+10][27] ; static PrintWriter out = new PrintWriter(System.out); static FastScanner sc =new FastScanner(); static StringBuilder sb = new StringBuilder(); public static void main(String[] args) throws IOException{ n =sc.nextInt(); k = sc.nextInt(); String str = sc.nextToken(); a=new int[n]; for(int i=0;i<n;i++) { a[i]=str.charAt(i)-'A'; } for(int i=0;i<dp.length;i++) for(int j=0;j<dp[i].length;j++) dp[i][j]=-1; System.out.println(solve(0,26)); print(0,26); out.flush(); out.close(); } static int solve(int idx,int pre) { if(idx==n) return 0 ; if( dp[idx][pre]!=-1) return dp[idx][pre]; int c = 10000000; for(int i=0;i<Math.min(3, k);i++) { if(i==pre)continue; if(i==a[idx]) c=Math.min(c, solve(idx+1,i)); else c=Math.min(c, 1+solve(idx+1,i)); } if(a[idx] != pre) c = Math.min(c, solve(idx+1, a[idx]) ); return dp[idx][pre]= c; } static void print(int idx,int pre) { if(idx==n) return ; int c = 10000000; for(int i=0;i<k;i++) { if(i==pre) { continue; } if(i==a[idx] && solve(idx+1,i)==dp[idx][pre]) { out.print((char)('A'+i)); print(idx+1,i); break; } if(1+solve(idx+1,i)==dp[idx][pre] ) { out.print((char)('A'+i)); print(idx+1,i); break; } } return ; } } class pair implements Comparable{ int x ,y,z; pair(int x,int y,int z) { this.x=x; this.y=y; this.z=z; } @Override public int compareTo(Object arg0) { pair u =((pair)arg0); return -this.z+u.z; } } 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) { e.printStackTrace(); } } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } }
Java
["6 3\nABBACC", "3 2\nBBB"]
2 seconds
["2\nABCACA", "1\nBAB"]
null
Java 8
standard input
[ "dp", "greedy", "brute force" ]
0ecf60ea733eba71ef1cc1e736296d96
The first input line contains two integers n and k (1 ≀ n ≀ 5Β·105;Β 2 ≀ k ≀ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.
1,600
Print a single integer β€” the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.
standard output
PASSED
cb02b39081a35bb4a35323e0484c19c9
train_000.jsonl
1346081400
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.
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 Parthiv Mangukiya */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int k = in.nextInt(); char[] s = in.next().trim().toCharArray(); int c[] = new int[n]; for (int i = 0; i < n; i++) { c[i] = s[i] - 'A'; } int ans = 0; if (k != 2) { for (int i = 1; i < n; i++) { if (c[i - 1] == c[i]) { while (c[i] == c[i - 1] || (i + 1 < n && c[i] == c[i + 1])) { c[i]++; c[i] %= k; } ans++; } } } else { int a1 = 0; int cur = 0; for (int i = 0; i < n; i++) { if (c[i] != cur) { a1++; } if (cur == 1) cur = 0; else cur = 1; } int a2 = 0; cur = 1; for (int i = 0; i < n; i++) { if (c[i] != cur) { a2++; } if (cur == 1) cur = 0; else cur = 1; } if (a1 <= a2) { ans = a1; cur = 0; for (int i = 0; i < n; i++) { c[i] = cur; if (cur == 1) cur = 0; else cur = 1; } } else { ans = a2; cur = 1; for (int i = 0; i < n; i++) { c[i] = cur; if (cur == 1) cur = 0; else cur = 1; } } } out.println(ans); for (int i = 0; i < n; i++) { out.print((char) (c[i] + 'A')); } out.println(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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 static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return nextString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void println() { writer.println(); } public void print(char i) { writer.print(i); } public void close() { writer.close(); } public void println(int i) { writer.println(i); } } }
Java
["6 3\nABBACC", "3 2\nBBB"]
2 seconds
["2\nABCACA", "1\nBAB"]
null
Java 8
standard input
[ "dp", "greedy", "brute force" ]
0ecf60ea733eba71ef1cc1e736296d96
The first input line contains two integers n and k (1 ≀ n ≀ 5Β·105;Β 2 ≀ k ≀ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.
1,600
Print a single integer β€” the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.
standard output
PASSED
c62b0d1542e2594ee0e4b4fc250cbd1c
train_000.jsonl
1346081400
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.
256 megabytes
import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; public class ColorStripe { static int[][] memo; static int k; static int n; static char[] arr; static String[][] word; static PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); k = sc.nextInt(); arr = sc.next().toCharArray(); memo = new int[n+1][27]; word = new String[n+1][27]; for (int i = 0; i < memo.length; i++) Arrays.fill(memo[i], -1); System.out.println(solve(0, 26)); print(0, 26); pw.flush(); pw.close(); sc.close(); } private static void print(int ind, int last) { if(ind == n) return; for (int i = 0; i < k; i++) { if(i == last) continue; if(i + 'A' == arr[ind] && solve(ind+1, i) == memo[ind][last]) { pw.print((char)('A' + i)); print(ind+1, i); break; } else if(memo[ind][last] == 1 + solve(ind+1, i)) { pw.print((char)('A' + i)); print(ind+1, i); break; } } } private static int solve(int ind, int last) { if(ind == n) return 0; if(memo[ind][last] != -1) return memo[ind][last]; int ans = (int)1e9; for (int i = 0; i < Math.min(k, 3); i++) { if(i == last) continue; if(i + 'A' == arr[ind]) ans = Math.min(ans, solve(ind+1, i)); else ans = Math.min(ans, 1 + solve(ind+1, i)); } if(arr[ind] - 'A' != last) ans = Math.min(ans, solve(ind+1, arr[ind] - 'A')); return memo[ind][last] = ans; } }
Java
["6 3\nABBACC", "3 2\nBBB"]
2 seconds
["2\nABCACA", "1\nBAB"]
null
Java 8
standard input
[ "dp", "greedy", "brute force" ]
0ecf60ea733eba71ef1cc1e736296d96
The first input line contains two integers n and k (1 ≀ n ≀ 5Β·105;Β 2 ≀ k ≀ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.
1,600
Print a single integer β€” the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.
standard output
PASSED
e42d6bc3ae61e02fac69f6ff6f5d5053
train_000.jsonl
1346081400
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { static InputReader in = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); static int MOD = 1000000007; static int M = 505; static int oo = Integer.MAX_VALUE; static int[] di = {-1, 1, 0, 0}; static int[] dj = {0, 0, -1, 1}; public static void main(String[] args) throws IOException { int n = in.nextInt(); int k = in.nextInt(); char[] a = in.readString().toCharArray(); if(k == 2) { int t = 0; char c; int cnt1 = 0, cnt2 = 0; char[] ans1 = new char[n]; char[] ans2 = new char[n]; for(int i=0; i < n; ++i) { t = 1 - t; c = t == 0 ? 'A' : 'B'; ans1[i] = c; if(a[i] != c) cnt1++; } t = 1; for(int i=0; i < n; ++i) { t = 1 - t; c = t == 0 ? 'A' : 'B'; ans2[i] = c; if(a[i] != c) cnt2++; } int cnt = cnt1 < cnt2 ? cnt1 : cnt2; String ans = cnt1 < cnt2 ? new String(ans1) : new String(ans2); System.out.println(cnt); System.out.println(ans); } else { int cnt = 0; for(int i=1; i < n; ++i) { if(a[i] == a[i-1]) { if(i+1 < n) { char c = '.'; for(c = 'A'; c <= 'Z'; ++c) { if(c != a[i-1] && c != a[i+1] ) { a[i] = c; cnt++; break; } } } else { char c = '.'; for(c = 'A'; c <= 'Z'; ++c) { if(c != a[i-1]) { a[i] = c; cnt++; break; } } } } } System.out.println(cnt); System.out.println(new String(a)); } out.close(); } static void shuffle(int[] a) { Random r = new Random(); for(int i = a.length - 1; i > 0; --i) { int si = r.nextInt(i); int t = a[si]; a[si] = a[i]; a[i] = t; } } static void shuffle(long[] a) { Random r = new Random(); for(int i = a.length - 1; i > 0; --i) { int si = r.nextInt(i); long t = a[si]; a[si] = a[i]; a[i] = t; } } static int lower_bound(int[] a, int n, int k) { int s = 0; int e = n; int m; while (e - s > 0) { m = (s + e) / 2; if (a[m] < k) s = m + 1; else e = m; } return e; } static int lower_bound(long[] a, int n, long k) { int s = 0; int e = n; int m; while (e - s > 0) { m = (s + e) / 2; if (a[m] < k) s = m + 1; else e = m; } return e; } static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static class Pair implements Comparable<Pair> { int first, second; public Pair(int first, int second) { super(); this.first = first; this.second = second; } @Override public int compareTo(Pair o) { return this.first != o.first ? this.first - o.first : this.second - o.second; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + first; result = prime * result + second; 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 (first != other.first) return false; if (second != other.second) return false; return true; } } } class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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 = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } }
Java
["6 3\nABBACC", "3 2\nBBB"]
2 seconds
["2\nABCACA", "1\nBAB"]
null
Java 8
standard input
[ "dp", "greedy", "brute force" ]
0ecf60ea733eba71ef1cc1e736296d96
The first input line contains two integers n and k (1 ≀ n ≀ 5Β·105;Β 2 ≀ k ≀ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.
1,600
Print a single integer β€” the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.
standard output
PASSED
cedf8e09b96b70fc25f9dddd11de4a3d
train_000.jsonl
1346081400
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.
256 megabytes
import java.util.*; import java.io.*; public class A { public static void main(String ar[]) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String s1[]=br.readLine().split(" "); int n=Integer.parseInt(s1[0]); int k=Integer.parseInt(s1[1]); char c[]=br.readLine().toLowerCase().toCharArray(); int a[][]=new int[n+1][k]; int b[][]=new int[n+1][k]; StringBuffer sb=new StringBuffer(); int min=0,min2=0; int u=-1,v=-1; for(int i=0;i<n;i++) { for(int j=0;j<k;j++) { char d=(char)(j+97); if(d!=c[i]) a[i+1][j]=1; if(u==j) { a[i+1][j]+=min2; b[i+1][j]=v; } else { a[i+1][j]+=min; b[i+1][j]=u; } } min=n+1; min2=n+1; for(int j=0;j<k;j++) if(min>a[i+1][j]) { min=a[i+1][j]; u=j; } for(int j=0;j<k;j++) if(min2>a[i+1][j] && j!=u) { min2=a[i+1][j]; v=j; } } /* for(int i=0;i<n;i++) { for(int j=0;j<k;j++) { System.out.print(a[i+1][j]+" "); } System.out.println(); } for(int i=0;i<n;i++) { for(int j=0;j<k;j++) { System.out.print(b[i+1][j]+" "); } System.out.println(); } */ int mm=n+1; for(int j=0;j<k;j++) mm=Math.min(mm,a[n][j]); System.out.println(mm); for(int i=n;i>=1;i--) { sb.append((char)(u+65)); u=b[i][u]; } sb=sb.reverse(); System.out.println(sb); } }
Java
["6 3\nABBACC", "3 2\nBBB"]
2 seconds
["2\nABCACA", "1\nBAB"]
null
Java 8
standard input
[ "dp", "greedy", "brute force" ]
0ecf60ea733eba71ef1cc1e736296d96
The first input line contains two integers n and k (1 ≀ n ≀ 5Β·105;Β 2 ≀ k ≀ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.
1,600
Print a single integer β€” the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.
standard output
PASSED
ea66c815fc56300250fb770c7b32c88a
train_000.jsonl
1346081400
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.
256 megabytes
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; // atharva washimkar // Oct 13, 2019 public class CODEFORCES_219_C { public static void main (String[] t) throws IOException { INPUT in = new INPUT (System.in); PrintWriter out = new PrintWriter (System.out); int N = in.iscan (), K = in.iscan (); char[] arr = in.sscan ().toCharArray (); int moves = 0; StringBuilder str = new StringBuilder (); if (K == 2) { int ans = 1 << 30; int s = 0; for (int i = 0; i < 2; ++i) { // two possible characters to start alternating sequence: A or B int cur_ans = 0; int cur = i; for (int n = 0; n < N; ++n, cur = 1 - cur) if (arr[n] - 'A' != cur) ++cur_ans; if (cur_ans < ans) { ans = cur_ans; s = i; } } moves = ans; for (int n = 0; n < N; ++n, s = 1 - s) str.append ((char) (s + 'A')); } else { for (int n = 0; n < N; ) { int c = arr[n] - 'A'; int num = 1; while (n + 1 < N && arr[n] == arr[n + 1]) { ++num; ++n; } moves += num / 2; int afterc = n == N - 1 ? K + 1 : arr[n + 1] - 'A'; int altc = 0; for (int k = 0; k < K; ++k) { if (k != c && k != afterc) { altc = k; break; } } for (int i = 0; i < num; ++i) str.append ((char) ((i % 2 == 0 ? c : altc) + 'A')); ++n; } } out.println (moves); out.print (str); out.close (); } private static class INPUT { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public INPUT (InputStream stream) { this.stream = stream; } public INPUT (String file) throws IOException { this.stream = new FileInputStream (file); } public int cscan () throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read (buf); } if (numChars == -1) return numChars; return buf[curChar++]; } public int iscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } int res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public String sscan () throws IOException { int c = cscan (); while (space (c)) c = cscan (); StringBuilder res = new StringBuilder (); do { res.appendCodePoint (c); c = cscan (); } while (!space (c)); return res.toString (); } public double dscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } double res = 0; while (!space (c) && c != '.') { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); res *= 10; res += c - '0'; c = cscan (); } if (c == '.') { c = cscan (); double m = 1; while (!space (c)) { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); m /= 10; res += (c - '0') * m; c = cscan (); } } return res * sgn; } public long lscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } long res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public boolean space (int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } public static class UTILITIES { static final double EPS = 10e-6; public static int lower_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) high = mid; else low = mid + 1; } return low; } public static int upper_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > x) high = mid; else low = mid + 1; } return low; } public static int gcd (int a, int b) { return b == 0 ? a : gcd (b, a % b); } public static int lcm (int a, int b) { return a * b / gcd (a, b); } public static int fast_pow_mod (int b, int x, int mod) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod; return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod; } public static int fast_pow (int b, int x) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow (b * b, x / 2); return b * fast_pow (b * b, x / 2); } public static long choose (long n, long k) { k = Math.min (k, n - k); long val = 1; for (int i = 0; i < k; ++i) val = val * (n - i) / (i + 1); return val; } public static long permute (int n, int k) { if (n < k) return 0; long val = 1; for (int i = 0; i < k; ++i) val = (val * (n - i)); return val; } } }
Java
["6 3\nABBACC", "3 2\nBBB"]
2 seconds
["2\nABCACA", "1\nBAB"]
null
Java 8
standard input
[ "dp", "greedy", "brute force" ]
0ecf60ea733eba71ef1cc1e736296d96
The first input line contains two integers n and k (1 ≀ n ≀ 5Β·105;Β 2 ≀ k ≀ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.
1,600
Print a single integer β€” the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.
standard output
PASSED
6e7f4f0aa28ea9ebfdaabbe3e8b76823
train_000.jsonl
1346081400
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.math.*; import java.util.concurrent.*; public class Main { //--------------------------------------------------------------------------- static int n, k; static char[] a; public static void main(String[] args) throws Exception { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); //----------------------------------------------------------------------- n = in.nextInt(); k = in.nextInt(); a = in.nextCharArray(); int c = 0; if (k == 2) { int c1 = 0; int c2 = 0; for (int i = 0; i < n; i++) { if (i % 2 == 0) { if (a[i] == 'A') { c2++; } else { c1++; } } else { if (a[i] == 'B') { c2++; } else { c1++; } } } if (c1 < c2) { c = c1; for (int i = 0; i < n; i++) { if (i % 2 == 0) { a[i] = 'A'; } else { a[i] = 'B'; } } } else { c = c2; for (int i = 0; i < n; i++) { if (i % 2 == 0) { a[i] = 'B'; } else { a[i] = 'A'; } } } } else { for (int i = 1; i < n; i++) { if (a[i] == a[i - 1]) { c++; if (i == n - 1) { if (a[i - 1] == 'A') { a[i] = 'B'; } else { a[i] = 'A'; } } else { for (int j = 0; j < k; j++) { if (a[i - 1] != j + 'A' && a[i + 1] != j + 'A') { a[i] = (char)(j + 'A'); } } } } } } out.println(c); for (int i = 0; i < n; i++) { out.print(a[i]); } out.println(); //----------------------------------------------------------------------- out.close(); } //--------------------------------------------------------------------------- static void shuffleArray(int[] ar) { Random rnd = ThreadLocalRandom.current(); for (int i = ar.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); int a = ar[index]; ar[index] = ar[i]; ar[i] = a; } } static class Pair<F, S> implements Comparable<Pair<F, S>> { F first; S second; public Pair() { } public Pair(F f, S s) { this.first = f; this.second = s; } public int compareTo(Pair<F, S> p) { int ret = ((Comparable<F>) first).compareTo(p.first); return ret; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public char[] nextCharArray() { return next().toCharArray(); } public boolean hasNext() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { String s = reader.readLine(); if (s == null) { return false; } tokenizer = new StringTokenizer(s); } catch (IOException e) { throw new RuntimeException(e); } } return true; } public void skipLine() { try { tokenizer = null; reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } } }
Java
["6 3\nABBACC", "3 2\nBBB"]
2 seconds
["2\nABCACA", "1\nBAB"]
null
Java 8
standard input
[ "dp", "greedy", "brute force" ]
0ecf60ea733eba71ef1cc1e736296d96
The first input line contains two integers n and k (1 ≀ n ≀ 5Β·105;Β 2 ≀ k ≀ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.
1,600
Print a single integer β€” the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.
standard output
PASSED
cd755be710c0f08d0c3f0ad21261d4f1
train_000.jsonl
1346081400
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; /** * * @author Saju * */ public class Main { private static int dx[] = { 1, 0, -1, 0 }; private static int dy[] = { 0, -1, 0, 1 }; private static final long INF = Long.MAX_VALUE; private static final int INT_INF = Integer.MAX_VALUE; private static final long NEG_INF = Long.MIN_VALUE; private static final int NEG_INT_INF = Integer.MIN_VALUE; private static final double EPSILON = 1e-10; private static final int MAX = 2000007; private static final long MOD = 1000000007; private static final int MAXN = 100007; private static final int MAXA = 10000009; private static final int MAXLOG = 22; public static void main(String[] args) throws IOException { InputReader in = new InputReader(System.in); // Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); // InputReader in = new InputReader(new FileInputStream("src/test.in")); // PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("src/test.out"))); /* */ int n = in.nextInt(); int k = in.nextInt(); char[] grid = in.next().toCharArray(); int cnt = 0; if(k == 2) { StringBuilder sb1 = new StringBuilder(); StringBuilder sb2 = new StringBuilder(); for(int i = 0; i < n; i++) { if(i % 2 == 0) { sb1.append("A"); sb2.append("B"); } else { sb1.append("B"); sb2.append("A"); } } int cnt1 = 0; int cnt2 = 0; for(int i = 0; i < n; i++) { if(grid[i] != sb1.charAt(i)) { cnt1++; } if(grid[i] != sb2.charAt(i)) { cnt2++; } } if(cnt1 <= cnt2) { out.println(cnt1); out.println(sb1.toString()); } else{ out.println(cnt2); out.println(sb2.toString()); } out.flush(); return; } for(int i = 1; i < n; i++) { if(grid[i] != grid[i - 1]) { continue; } if(i != n - 1) { grid[i] = get(grid[i - 1], grid[i + 1], k); } else { grid[i] = get(grid[i], grid[i - 1], k); } cnt++; } StringBuilder sb = new StringBuilder(); for(int i = 0; i < n; i++) { sb.append(grid[i]); } out.println(cnt); out.println(sb.toString()); in.close(); out.flush(); out.close(); System.exit(0); } private static char get(char f, char l, int k) { for(char ch = 'A'; ch <= (char) ('A' + k - 1); ch++) { if(ch != f && ch != l) { return ch; } } return 'A'; } private static boolean isPalindrome(String str) { StringBuilder sb = new StringBuilder(); sb.append(str); String str1 = sb.reverse().toString(); return str.equals(str1); } private static String getBinaryStr(int n, int j) { String str = Integer.toBinaryString(n); int k = str.length(); for (int i = 1; i <= j - k; i++) { str = "0" + str; } return str; } private static String getBinaryStr(long n, int j) { String str = Long.toBinaryString(n); int k = str.length(); for (int i = 1; i <= j - k; i++) { str = "0" + str; } return str; } private static long bigMod(long n, long k, long m) { long ans = 1; while (k > 0) { if ((k & 1) == 1) { ans = (ans * n) % m; } n = (n * n) % m; k >>= 1; } return ans; } private static long ceil(long n, long x) { long div = n / x; if(div * x != n) { div++; } return div; } private static int ceil(int n, int x) { int div = n / x; if(div * x != n) { div++; } return div; } private static int abs(int x) { if (x < 0) { return -x; } return x; } private static long abs(long x) { if(x < 0) { return -x; } return x; } private static int lcm(int a, int b) { return (a * b) / gcd(a, b); } private static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } private static int log(long x, int base) { return (int) (Math.log(x) / Math.log(base)); } private static long min(long a, long b) { if (a < b) { return a; } return b; } private static int min(int a, int b) { if (a < b) { return a; } return b; } private static long max(long a, long b) { if (a < b) { return b; } return a; } private static int max(int a, int b) { if (a < b) { return b; } return a; } private static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public String next() { try { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } } catch (IOException e) { return null; } return tokenizer.nextToken(); } public String nextLine() { String line = null; try { tokenizer = null; line = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return line; } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } public boolean hasNext() { try { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } } catch (Exception e) { return false; } return true; } public int[] nextIntArr(int n) { int arr[] = new int[n]; for(int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArr(int n) { long arr[] = new long[n]; for(int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public int[] nextIntArr1(int n) { int arr[] = new int[n + 1]; for(int i = 1; i <= n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArr1(int n) { long arr[] = new long[n + 1]; for(int i = 1; i <= n; i++) { arr[i] = nextLong(); } return arr; } public void close() { try { if(reader != null) { reader.close(); } } catch(Exception e) { } } } }
Java
["6 3\nABBACC", "3 2\nBBB"]
2 seconds
["2\nABCACA", "1\nBAB"]
null
Java 8
standard input
[ "dp", "greedy", "brute force" ]
0ecf60ea733eba71ef1cc1e736296d96
The first input line contains two integers n and k (1 ≀ n ≀ 5Β·105;Β 2 ≀ k ≀ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.
1,600
Print a single integer β€” the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.
standard output
PASSED
63c27de718feb0d5c2ec7d4bcefc7ec5
train_000.jsonl
1346081400
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.
256 megabytes
import java.util.Scanner; public class Main { public static int N, K; public static String str; public static int[] a; public static void main(String[] args) { Scanner s = new Scanner(System.in); N = s.nextInt(); K = s.nextInt(); str = s.next(); a = new int[N + 1]; for (int i = 1; i <= N; i++) { a[i] = str.charAt(i - 1) - 'A' + 1; } if (K == 2) { int[] b = new int[N + 1]; int[] c = new int[N + 1]; int res1 = 0; int res2 = 0; for (int i = 1; i <= N; i++) { if (i % 2 == 0) { b[i] = 1; c[i] = 2; } else { b[i] = 2; c[i] = 1; } if (a[i] != b[i]) res1++; if (a[i] != c[i]) res2++; } if (res1 <= res2) { System.out.println(res1); StringBuilder sb = new StringBuilder(); for (int i : b) { if (i == 0) continue; sb.append(toChar(i)); } System.out.println(sb.toString()); } else { System.out.println(res2); StringBuilder sb = new StringBuilder(); for (int i : c) { if (i == 0) continue; sb.append(toChar(i)); } System.out.println(sb.toString()); } return; } int[][] dp = new int[N + 1][2]; int[][] last = new int[N + 1][2]; for (int i = 0; i <= N; i++) { for (int k = 0; k < 2; k++) { dp[i][k] = 1 << 29; } } dp[0][0] = 0; for (int i = 1; i <= N; i++) { if (a[i] == a[i - 1]) { dp[i][1] = dp[i - 1][0] + 1; last[i][1] = 0; dp[i][0] = dp[i - 1][1]; last[i][0] = 1; } else { if (dp[i - 1][0] <= dp[i - 1][1]) { dp[i][0] = dp[i - 1][0]; last[i][0] = 0; } else { dp[i][0] = dp[i - 1][1]; last[i][0] = 1; } if (dp[i - 1][0] <= dp[i - 1][1]) { dp[i][1] = dp[i - 1][0] + 1; last[i][1] = 0; } else { dp[i][1] = dp[i - 1][1] + 1; last[i][1] = 1; } } } int res = Math.min(dp[N][1], dp[N][0]); System.out.println(res); int curr = 0; if (dp[N][1] < dp[N][0]) { curr = 1; } StringBuilder sb = new StringBuilder(); for (int i = N; i >= 1; i--) { if (curr == 0) { sb.append(toChar(a[i])); } else { if (last[i][curr] == 0) { sb.append(toChar(getColor(a[i - 1], a[i]))); } else { throw new RuntimeException(); } } curr = last[i][curr]; } sb.reverse(); System.out.println(sb.toString()); } public static char toChar(int i) { return (char) (i + 'A' - 1); } public static int getColor(int a, int b) { for (int i = 1; i <= K; i++) { if (i != a && i != b) { return i; } } return -1; } }
Java
["6 3\nABBACC", "3 2\nBBB"]
2 seconds
["2\nABCACA", "1\nBAB"]
null
Java 8
standard input
[ "dp", "greedy", "brute force" ]
0ecf60ea733eba71ef1cc1e736296d96
The first input line contains two integers n and k (1 ≀ n ≀ 5Β·105;Β 2 ≀ k ≀ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.
1,600
Print a single integer β€” the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.
standard output
PASSED
cf96bdc5e78febb85253e1084695de2f
train_000.jsonl
1346081400
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.
256 megabytes
import java.util.Scanner; public class Main { public static int N, K; public static String str; public static int[] a; public static void main(String[] args) { Scanner s = new Scanner(System.in); N = s.nextInt(); K = s.nextInt(); str = s.next(); a = new int[N + 1]; for (int i = 1; i <= N; i++) { a[i] = str.charAt(i - 1) - 'A' + 1; } if (K == 2) { int[] b = new int[N + 1]; int[] c = new int[N + 1]; int res1 = 0; int res2 = 0; for (int i = 1; i <= N; i++) { if (i % 2 == 0) { b[i] = 1; c[i] = 2; } else { b[i] = 2; c[i] = 1; } if (a[i] != b[i]) res1++; if (a[i] != c[i]) res2++; } if (res1 <= res2) { System.out.println(res1); StringBuilder sb = new StringBuilder(); for (int i : b) { if (i == 0) continue; sb.append(toChar(i)); } System.out.println(sb.toString()); } else { System.out.println(res2); StringBuilder sb = new StringBuilder(); for (int i : c) { if (i == 0) continue; sb.append(toChar(i)); } System.out.println(sb.toString()); } return; } int[][] dp = new int[N + 1][2]; int[][] last = new int[N + 1][2]; for (int i = 0; i <= N; i++) { for (int k = 0; k < 2; k++) { dp[i][k] = 1 << 29; } } dp[0][0] = 0; for (int i = 1; i <= N; i++) { if (a[i] == a[i - 1]) { dp[i][1] = dp[i - 1][0] + 1; last[i][1] = 0; dp[i][0] = dp[i - 1][1]; last[i][0] = 1; } else { if (dp[i - 1][0] <= dp[i - 1][1]) { dp[i][0] = dp[i - 1][0]; last[i][0] = 0; } else { dp[i][0] = dp[i - 1][1]; last[i][0] = 1; } dp[i][1] = dp[i - 1][0] + 1; last[i][1] = 0; } } int res = Math.min(dp[N][1], dp[N][0]); System.out.println(res); int curr = 0; if (dp[N][1] < dp[N][0]) { curr = 1; } StringBuilder sb = new StringBuilder(); for (int i = N; i >= 1; i--) { if (curr == 0) { sb.append(toChar(a[i])); } else { sb.append(toChar(getColor(a[i - 1], a[i]))); } curr = last[i][curr]; } sb.reverse(); System.out.println(sb.toString()); } public static char toChar(int i) { return (char) (i + 'A' - 1); } public static int getColor(int a, int b) { for (int i = 1; i <= K; i++) { if (i != a && i != b) { return i; } } return -1; } }
Java
["6 3\nABBACC", "3 2\nBBB"]
2 seconds
["2\nABCACA", "1\nBAB"]
null
Java 8
standard input
[ "dp", "greedy", "brute force" ]
0ecf60ea733eba71ef1cc1e736296d96
The first input line contains two integers n and k (1 ≀ n ≀ 5Β·105;Β 2 ≀ k ≀ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.
1,600
Print a single integer β€” the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.
standard output
PASSED
87042fdf74e8db98cfe1ea853a4d8132
train_000.jsonl
1346081400
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.
256 megabytes
//package codeforces; import java.util.Scanner; public class ColorStripe2 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); in.nextLine(); String s = in.nextLine(); char[] cs = s.toCharArray(); int res = 0; if (k > 2) { for (int i = 1; i < cs.length; i++) { if (cs[i] == cs[i - 1]) { for (int j = 0; j < k; j++) { char x = (char) ('A' + j); if (x != cs[i - 1] && (i == cs.length - 1 || x != cs[i + 1])) { res++; cs[i] = x; break; } } } } System.out.println(res); System.out.println(new String(cs)); } else { char[] a = new char[s.length()]; char[] b = new char[s.length()]; char x = 'A'; char y = 'B'; for (int i = 0; i < a.length; i++) { a[i] = x; b[i] = y; char t = x; x = y; y = t; } int d1 = diff(a, cs); int d2 = diff(b, cs); if (d1 < d2) { System.out.println(d1); System.out.println(new String(a)); } else { System.out.println(d2); System.out.println(new String(b)); } } } private static int diff(char[] x, char[] y) { int diff = 0; for (int i = 0; i < x.length; i++) { if (x[i] != y[i]) { diff++; } } return diff; } }
Java
["6 3\nABBACC", "3 2\nBBB"]
2 seconds
["2\nABCACA", "1\nBAB"]
null
Java 8
standard input
[ "dp", "greedy", "brute force" ]
0ecf60ea733eba71ef1cc1e736296d96
The first input line contains two integers n and k (1 ≀ n ≀ 5Β·105;Β 2 ≀ k ≀ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.
1,600
Print a single integer β€” the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.
standard output
PASSED
285e399417c18450c05e75d75f815779
train_000.jsonl
1346081400
A colored stripe is represented by a horizontal row of n square cells, each cell is pained one of k colors. Your task is to repaint the minimum number of cells so that no two neighbouring cells are of the same color. You can use any color from 1 to k to repaint the cells.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { // your code goes here int n,k; Scanner sc = new Scanner(System.in); n =sc.nextInt(); k = sc.nextInt(); String s = sc.next(); char[] charArray = s.toCharArray(); int count=0; if(k==2){ int distanceFromA =0; char[] charWithAStart = new char[charArray.length]; for(int i=0; i < charArray.length; i++){ if(i%2 == 0){ charWithAStart[i] = 'A'; } else{ charWithAStart[i] = 'B'; } distanceFromA += Math.abs((int)charWithAStart[i] - (int)charArray[i] ); } char[] charWithBStart = new char[charArray.length]; int distanceFromB =0; for(int i=0; i < charArray.length; i++){ if(i%2 == 0){ charWithBStart[i] = 'B'; } else{ charWithBStart[i] = 'A'; } distanceFromB += Math.abs((int)charWithBStart[i] - (int)charArray[i] ); } if(distanceFromA > distanceFromB){ System.out.println(distanceFromB); System.out.println(new String(charWithBStart)); } else{ System.out.println(distanceFromA); System.out.println(new String(charWithAStart)); } return; } for(int i=1; i < charArray.length; i++){ if(charArray[i-1] == charArray[i]){ count++; if(i+1 < charArray.length){ // System.out.println("i: " + i + " " + charArray[i]); charArray[i] = findMostSuitableChar(charArray[i],charArray[i+1],k); } else{ // System.out.println("i: " + i + " " + charArray[i]); charArray[i] = findMostSuitableChar(charArray[i],null,k); } } } System.out.println(count); System.out.println(new String(charArray)); } public static Character findMostSuitableChar(Character cur, Character next,int k){ if(next == null){ for(int k1=0; k1 <k; k1++){ Character temp = (char)((int)'A' + k1); if(temp!= cur){ return temp; } } return null; }else{ for(int k1=0; k1 <k; k1++){ // System.out.println("temp: "); Character temp = (char)((int)'A' + k1); if(temp!= cur && temp!= next){ // System.out.println("temp: "+ temp); return temp; } } return null; } } }
Java
["6 3\nABBACC", "3 2\nBBB"]
2 seconds
["2\nABCACA", "1\nBAB"]
null
Java 8
standard input
[ "dp", "greedy", "brute force" ]
0ecf60ea733eba71ef1cc1e736296d96
The first input line contains two integers n and k (1 ≀ n ≀ 5Β·105;Β 2 ≀ k ≀ 26). The second line contains n uppercase English letters. Letter "A" stands for the first color, letter "B" stands for the second color and so on. The first k English letters may be used. Each letter represents the color of the corresponding cell of the stripe.
1,600
Print a single integer β€” the required minimum number of repaintings. In the second line print any possible variant of the repainted stripe.
standard output
PASSED
4d8a18e07c5ad48e7ef34213bcd83c33
train_000.jsonl
1277391600
Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: the final tournament features n teams (n is always even) the first n / 2 teams (according to the standings) come through to the knockout stage the standings are made on the following principle: for a victory a team gets 3 points, for a draw β€” 1 point, for a defeat β€” 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place β€” in decreasing order of the difference between scored and missed goals; in the third place β€” in the decreasing order of scored goals it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage.
64 megabytes
import java.util.*; public class A { // TreeMap really not necessary since we are sorting by values. A normal hashmap would actually do. static Map<String,Score> teams = new TreeMap<String,Score>(); static class Score { int p; // Points int gf; // Goals for int ga; // Goals against Score(int b, int c, int d){ p=b; gf=c; ga=d; } } static void solve(){ Scanner sc = new Scanner(System.in); int NOC = sc.nextInt(); int no = NOC; int n = (NOC*(NOC-1))/2; while(NOC-->0) teams.put(sc.next(),new Score(0,0,0)); while(n-->0){ String[] t = sc.next().split("-"); String[] g = sc.next().split(":"); Score a = teams.get(t[0]); Score b = teams.get(t[1]); int ga = Integer.parseInt(g[0]); int gb = Integer.parseInt(g[1]); if(ga==gb) { a.p++; b.p++; } else if(ga<gb) b.p+=3; else a.p+=3; a.gf+=ga; b.gf+=gb; a.ga+=gb; b.ga+=ga; teams.put(t[0],a); teams.put(t[1],b); } Set<Map.Entry<String, Score>> set = teams.entrySet(); List<Map.Entry<String, Score>> list = new ArrayList<Map.Entry<String, Score>>(set); Collections.sort(list, new Comparator<Map.Entry<String, Score>>() { public int compare(Map.Entry<String, Score> o1, Map.Entry<String, Score> o2) { int ret = 0; Score a = o1.getValue(); Score b = o2.getValue(); if(a.p==b.p){ if((a.gf-a.ga)==(b.gf-b.ga)){ ret = (a.gf==b.gf) ? 0 : (a.gf>b.gf) ? -1 : 1; } else { ret = ((a.gf-a.ga)>(b.gf-b.ga)) ? -1 : 1; } }else{ ret = (a.p>b.p) ? -1 : 1; } return ret; } }); int count = 0; String[] wins = new String[no/2]; for(Map.Entry<String,Score> a: list){ if(count==no/2) break; wins[count++] = a.getKey(); } Arrays.sort(wins); for(String a: wins) System.out.println(a); sc.close(); } public static void main(String args[]) { solve(); } }
Java
["4\nA\nB\nC\nD\nA-B 1:1\nA-C 2:2\nA-D 1:0\nB-C 1:0\nB-D 0:3\nC-D 0:3", "2\na\nA\na-A 2:1"]
2 seconds
["A\nD", "a"]
null
Java 11
standard input
[ "implementation" ]
472c0cb256c062b9806bf93b13b453a2
The first input line contains the only integer n (1 ≀ n ≀ 50) β€” amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following nΒ·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 β€” names of the teams; num1, num2 (0 ≀ num1, num2 ≀ 100) β€” amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once.
1,400
Output n / 2 lines β€” names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity.
standard output
PASSED
0749a6afc133c918aa19cc05a9eeb7f1
train_000.jsonl
1277391600
Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: the final tournament features n teams (n is always even) the first n / 2 teams (according to the standings) come through to the knockout stage the standings are made on the following principle: for a victory a team gets 3 points, for a draw β€” 1 point, for a defeat β€” 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place β€” in decreasing order of the difference between scored and missed goals; in the third place β€” in the decreasing order of scored goals it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage.
64 megabytes
import java.util.*; public class WorldFootBallCup { // TreeMap really not necessary since we are sorting by values. A normal hashmap would actually do. static Map<String,Score> teams = new TreeMap<String,Score>(); static class Score { int p; // Points int gf; // Goals for int ga; // Goals against Score(int b, int c, int d){ p=b; gf=c; ga=d; } } static void solve(){ Scanner sc = new Scanner(System.in); int NOC = sc.nextInt(); int no = NOC; int n = (NOC*(NOC-1))/2; while(NOC-->0) teams.put(sc.next(),new Score(0,0,0)); while(n-->0){ String[] t = sc.next().split("-"); String[] g = sc.next().split(":"); Score a = teams.get(t[0]); Score b = teams.get(t[1]); int ga = Integer.parseInt(g[0]); int gb = Integer.parseInt(g[1]); if(ga==gb) { a.p++; b.p++; } else if(ga<gb) b.p+=3; else a.p+=3; a.gf+=ga; b.gf+=gb; a.ga+=gb; b.ga+=ga; teams.put(t[0],a); teams.put(t[1],b); } Set<Map.Entry<String, Score>> set = teams.entrySet(); List<Map.Entry<String, Score>> list = new ArrayList<Map.Entry<String, Score>>(set); Collections.sort(list, new Comparator<Map.Entry<String, Score>>() { public int compare(Map.Entry<String, Score> o1, Map.Entry<String, Score> o2) { int ret = 0; Score a = o1.getValue(); Score b = o2.getValue(); if(a.p==b.p){ if((a.gf-a.ga)==(b.gf-b.ga)){ ret = (a.gf==b.gf) ? 0 : (a.gf>b.gf) ? -1 : 1; } else { ret = ((a.gf-a.ga)>(b.gf-b.ga)) ? -1 : 1; } }else{ ret = (a.p>b.p) ? -1 : 1; } return ret; } }); int count = 0; String[] wins = new String[no/2]; for(Map.Entry<String,Score> a: list){ if(count==no/2) break; wins[count++] = a.getKey(); } Arrays.sort(wins); for(String a: wins) System.out.println(a); } public static void main(String args[]) { solve(); } }
Java
["4\nA\nB\nC\nD\nA-B 1:1\nA-C 2:2\nA-D 1:0\nB-C 1:0\nB-D 0:3\nC-D 0:3", "2\na\nA\na-A 2:1"]
2 seconds
["A\nD", "a"]
null
Java 11
standard input
[ "implementation" ]
472c0cb256c062b9806bf93b13b453a2
The first input line contains the only integer n (1 ≀ n ≀ 50) β€” amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following nΒ·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 β€” names of the teams; num1, num2 (0 ≀ num1, num2 ≀ 100) β€” amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once.
1,400
Output n / 2 lines β€” names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity.
standard output
PASSED
3107fbccbdbdf007699b16d416aa7740
train_000.jsonl
1277391600
Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations: the final tournament features n teams (n is always even) the first n / 2 teams (according to the standings) come through to the knockout stage the standings are made on the following principle: for a victory a team gets 3 points, for a draw β€” 1 point, for a defeat β€” 0 points. In the first place, teams are ordered in the standings in decreasing order of their points; in the second place β€” in decreasing order of the difference between scored and missed goals; in the third place β€” in the decreasing order of scored goals it's written in Berland's Constitution that the previous regulation helps to order the teams without ambiguity. You are asked to write a program that, by the given list of the competing teams and the results of all the matches, will find the list of teams that managed to get through to the knockout stage.
64 megabytes
import java.io.*; import java.util.*; import java.util.regex.*; public class MyClass { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String args[]) { FastReader fr = new FastReader(); int n = Integer.parseInt(fr.nextLine()); HashMap<String, Integer> indexes = new HashMap<>(); String[] names = new String[n]; for (int i = 0; i < n; i += 1) { names[i] = fr.nextLine(); indexes.put(names[i], i); } int[] points = new int[n], diff_scores = new int[n], scores = new int[n]; for (int i = 0, total = (n - 1) * n / 2; i < total; i += 1) { String line = fr.nextLine(); Pattern pattern = Pattern.compile("(.*)-(.*) (.*):(.*)"); Matcher matcher = pattern.matcher(line); if(matcher.matches()) { int a = indexes.get(matcher.group(1)), b = indexes.get(matcher.group(2)); int x = Integer.parseInt(matcher.group(3)), y = Integer.parseInt(matcher.group(4)); if (x > y) points[a] += 3; else if (x == y) { points[a] += 1; points[b] += 1; } else points[b] += 3; diff_scores[a] += x - y; diff_scores[b] += y - x; scores[a] += x; scores[b] += y; } } Arrays.sort(names, (e1, e2) -> { int a = indexes.get(e1), b = indexes.get(e2); if (points[a] != points[b]) return -Integer.compare(points[a], points[b]); if (diff_scores[a] != diff_scores[b]) return -Integer.compare(diff_scores[a], diff_scores[b]); if (scores[a] != scores[b]) return -Integer.compare(scores[a], scores[b]); return 0; }); String[] half = Arrays.copyOfRange(names, 0, n / 2); Arrays.sort(half); for (int i = 0; i < n / 2; i += 1) { System.out.println(half[i]); } } }
Java
["4\nA\nB\nC\nD\nA-B 1:1\nA-C 2:2\nA-D 1:0\nB-C 1:0\nB-D 0:3\nC-D 0:3", "2\na\nA\na-A 2:1"]
2 seconds
["A\nD", "a"]
null
Java 11
standard input
[ "implementation" ]
472c0cb256c062b9806bf93b13b453a2
The first input line contains the only integer n (1 ≀ n ≀ 50) β€” amount of the teams, taking part in the final tournament of World Cup. The following n lines contain the names of these teams, a name is a string of lower-case and upper-case Latin letters, its length doesn't exceed 30 characters. The following nΒ·(n - 1) / 2 lines describe the held matches in the format name1-name2 num1:num2, where name1, name2 β€” names of the teams; num1, num2 (0 ≀ num1, num2 ≀ 100) β€” amount of the goals, scored by the corresponding teams. Accuracy of the descriptions is guaranteed: there are no two team names coinciding accurate to the letters' case; there is no match, where a team plays with itself; each match is met in the descriptions only once.
1,400
Output n / 2 lines β€” names of the teams, which managed to get through to the knockout stage in lexicographical order. Output each name in a separate line. No odd characters (including spaces) are allowed. It's guaranteed that the described regulations help to order the teams without ambiguity.
standard output
PASSED
542b395c51b61298c5a52c6a41bb3de3
train_000.jsonl
1558884900
Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.util.NoSuchElementException; public class Main { static PrintWriter out; static InputReader ir; static void solve() { char[] s = ir.next().toCharArray(); int n = s.length; int[] dp = new int[n]; dp[n - 1] = n; long res = 0; for (int i = n - 2; i >= 0; i--) { dp[i] = dp[i + 1]; for (int k = 1; i + 2 * k < Math.min(dp[i + 1], n); k++) { if (s[i] == s[i + k] && s[i + k] == s[i + 2 * k]) { dp[i] = i + 2 * k; break; } } res += n - dp[i]; } out.println(res); } public static void main(String[] args) { ir = new InputReader(System.in); out = new PrintWriter(System.out); solve(); out.flush(); } static class InputReader { private InputStream in; private byte[] buffer = new byte[1024]; private int curbuf; private int lenbuf; public InputReader(InputStream in) { this.in = in; this.curbuf = this.lenbuf = 0; } public boolean hasNextByte() { if (curbuf >= lenbuf) { curbuf = 0; try { lenbuf = in.read(buffer); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return false; } return true; } private int readByte() { if (hasNextByte()) return buffer[curbuf++]; else return -1; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private void skip() { while (hasNextByte() && isSpaceChar(buffer[curbuf])) curbuf++; } public boolean hasNext() { skip(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } public int nextInt() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public long nextLong() { if (!hasNext()) throw new NoSuchElementException(); int c = readByte(); while (isSpaceChar(c)) c = readByte(); boolean minus = false; if (c == '-') { minus = true; c = readByte(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = res * 10 + c - '0'; c = readByte(); } while (!isSpaceChar(c)); return (minus) ? -res : res; } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public char[][] nextCharMap(int n, int m) { char[][] map = new char[n][m]; for (int i = 0; i < n; i++) map[i] = next().toCharArray(); return map; } } static void tr(Object... o) { out.println(Arrays.deepToString(o)); } }
Java
["010101", "11001100"]
4 seconds
["3", "0"]
NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$.
Java 8
standard input
[ "brute force" ]
71bace75df1279ae55a6e755159d4191
The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 300\,000$$$), consisting of zeros and ones.
1,900
Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.
standard output
PASSED
c286256f6c8a055b7146cd8ec0d22032
train_000.jsonl
1558884900
Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.
256 megabytes
import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Scanner; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Andy Phan */ public class p1169d { public static void main(String[] args) { JS in = new JS(); String s = in.next(); int last = -1; long tot = 0; for(int i = 0; i < s.length(); i++) { last = Math.max(last, i-9); for(int j = 1; j <= 5; j++) { if(i-j-j < 0) break; if(s.charAt(i) == s.charAt(i-j) && s.charAt(i) == s.charAt(i-j-j)) { last = Math.max(last, i-j-j); break; } } tot += last+1; } System.out.println(tot); }static class JS { public int BS = 1 << 16; public char NC = (char) 0; byte[] buf = new byte[BS]; int bId = 0, size = 0; char c = NC; double num = 1; BufferedInputStream in; public JS() { in = new BufferedInputStream(System.in, BS); } public JS(String s) throws FileNotFoundException { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } public char nextChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) { return NC; } bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public long nextLong() { num = 1; boolean neg = false; if (c == NC) { c = nextChar(); } for (; (c < '0' || c > '9'); c = nextChar()) { if (c == '-') { neg = true; } } long res = 0; for (; c >= '0' && c <= '9'; c = nextChar()) { res = (res << 3) + (res << 1) + c - '0'; num *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + (cur < 0 ? -1 * nextLong() / num : nextLong() / num); } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) { c = nextChar(); } while (c > 32) { res.append(c); c = nextChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) { c = nextChar(); } while (c != '\n') { res.append(c); c = nextChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) { return true; } while (true) { c = nextChar(); if (c == NC) { return false; } else if (c > 32) { return true; } } } } }
Java
["010101", "11001100"]
4 seconds
["3", "0"]
NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$.
Java 8
standard input
[ "brute force" ]
71bace75df1279ae55a6e755159d4191
The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 300\,000$$$), consisting of zeros and ones.
1,900
Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.
standard output
PASSED
fbf5cce74f0a1adc1fe5fe025115e2e7
train_000.jsonl
1558884900
Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.
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 * * @author __shangu__ */ 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); DGoodTriple solver = new DGoodTriple(); solver.solve(1, in, out); out.close(); } static class DGoodTriple { public void solve(int testNumber, InputReader in, PrintWriter out) { String ln = in.nextLine(); int n = ln.length(); long ans = 0; for (int i = 0; i < n; ++i) { boolean ok = false; int r = n; for (int j = i + 2; j < i + 9 && j < n && !ok; ++j) { for (int k = j - 2; k >= i; k -= 2) if (ln.charAt(j) == ln.charAt(k) && ln.charAt(j) == ln.charAt((j + k) / 2)) { ok = true; r = j; } } ans += n - r; } out.println(ans); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String nextLine() { String str = ""; try { str = reader.readLine(); } catch (IOException e) { return null; } return str; } } }
Java
["010101", "11001100"]
4 seconds
["3", "0"]
NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$.
Java 8
standard input
[ "brute force" ]
71bace75df1279ae55a6e755159d4191
The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 300\,000$$$), consisting of zeros and ones.
1,900
Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.
standard output
PASSED
82b259e6742c5198fe5156d9d8cef9b3
train_000.jsonl
1558884900
Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); char[] s = scanner.next().trim().toCharArray(); long cnt = 0; int mini = s.length; for (int i = s.length - 3; i >= 0; i--) { int k = 1; while (i + 2 * k < s.length) { if (s[i] == s[i + k] && s[i] == s[i + 2 * k]) { break; } k++; } mini = Math.min(mini, i + 2 * k); cnt += s.length - mini; } System.out.println(cnt); } }
Java
["010101", "11001100"]
4 seconds
["3", "0"]
NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$.
Java 8
standard input
[ "brute force" ]
71bace75df1279ae55a6e755159d4191
The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 300\,000$$$), consisting of zeros and ones.
1,900
Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.
standard output
PASSED
ef71a1308dc0b005a8d02ff540f048b3
train_000.jsonl
1558884900
Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.
256 megabytes
import java.lang.reflect.Array; import java.util.Arrays; import java.util.Scanner; public class CompetitiveProgramming { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); String string = scanner.nextLine(); System.out.println(new Solver().goodTriples(string)); scanner.close(); } } class Solver { public long goodTriples(String string) { long tot = 0; int n = string.length(), pre = n, curr; for(int i = n-1;i >= 0;--i) { curr = pre; for(int k = 1;i+2*k < curr;++k) { if(string.charAt(i) == string.charAt(i+k) && string.charAt(i+k) == string.charAt(i+2*k) ) { curr = Math.min(curr, i+2*k); break; } } pre = curr; tot += (n-curr); } return tot; } }
Java
["010101", "11001100"]
4 seconds
["3", "0"]
NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$.
Java 8
standard input
[ "brute force" ]
71bace75df1279ae55a6e755159d4191
The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 300\,000$$$), consisting of zeros and ones.
1,900
Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.
standard output
PASSED
d9bb6dc057d4820c086d962e40097b01
train_000.jsonl
1558884900
Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter(System.out); //Scanner sc = new Scanner(); Reader in = new Reader(); Main solver = new Main(); solver.solve(out, in); out.flush(); out.close(); } static int INF = (int)1e5*4*4+5; static int maxn = (int)1e7+5; static int mod=(int)1e9+7 ; static int n,m,k,t,q,x,a,b,y; void solve(PrintWriter out, Reader in) throws IOException{ String str = in.next(); n = str.length(); long ans=0; int prev=n-1; for(int i=n-3;i>=0;i--){ for(int j=1;j<n&&i+2*j<=n-1;j++){ if(str.charAt(i)==str.charAt(i+j) && str.charAt(i)==str.charAt(i+2*j)){ if(prev<i+2*j) break; ans+=(long)(i+1)*(long)(prev-(i+2*j)+1); prev = i+2*j-1; } } } 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; } } }
Java
["010101", "11001100"]
4 seconds
["3", "0"]
NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$.
Java 8
standard input
[ "brute force" ]
71bace75df1279ae55a6e755159d4191
The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 300\,000$$$), consisting of zeros and ones.
1,900
Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.
standard output
PASSED
cb2250be361387b9b03dcc9a8f813d91
train_000.jsonl
1558884900
Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.
256 megabytes
import java.util.Scanner; public class Main { public static int N; public static String str; public static void main(String[] args) { Scanner s = new Scanner(System.in); str = s.next(); N = str.length(); long res = 0; for (int i = 0; i < N; i++) { for (int c = 3; c <= 9; c++) { int j = (i + c - 1); if (j >= N) break; if (check(i, j)) { res++; } } if (N - 9 - i >= 0) res += N - 9 - i; } System.out.println(res); } public static boolean check(int i, int j) { for (int x = i; x <= j; x++) { for (int k = 1; k <= 4; k++) { if (x + k <= j && x + 2 * k <= j) { if (str.charAt(x) == str.charAt(x + k) && str.charAt(x) == str.charAt(x + 2 * k)) { return true; } } } } return false; } }
Java
["010101", "11001100"]
4 seconds
["3", "0"]
NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$.
Java 8
standard input
[ "brute force" ]
71bace75df1279ae55a6e755159d4191
The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 300\,000$$$), consisting of zeros and ones.
1,900
Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.
standard output
PASSED
5f6f3e6ec29178238ebe188109ce0d63
train_000.jsonl
1558884900
Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top * * @author islammohsen */ 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 { public int solve(String sub) { int ret = 100000000; for (int i = 1; i <= 10; i++) { for (int j = 0; j < sub.length(); j++) { if (j + 2 * i >= sub.length()) break; if (sub.charAt(j) == sub.charAt(j + i) && sub.charAt(j) == sub.charAt(j + 2 * i)) ret = Math.min(ret, j + 2 * i); } } if (ret > 10) return 0; else return sub.length() - ret; } public void solve(int testNumber, Scanner in, PrintWriter out) { String s; s = in.next(); int n = s.length(); long ans = 0; for (int i = 0; i < n; i++) { int lastIdx = i + 8; if (lastIdx < n) ans += n - lastIdx; String sub = s.substring(i, Math.min(lastIdx, n)); ans += solve(sub); } out.print(ans); } } }
Java
["010101", "11001100"]
4 seconds
["3", "0"]
NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$.
Java 8
standard input
[ "brute force" ]
71bace75df1279ae55a6e755159d4191
The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 300\,000$$$), consisting of zeros and ones.
1,900
Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.
standard output
PASSED
4d454df7e298de1e621ed72fa2e7bd7e
train_000.jsonl
1558884900
Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.OutputStream; import java.util.Arrays; import java.util.Iterator; import java.util.Collection; import java.io.IOException; import java.io.InputStreamReader; import java.io.FileNotFoundException; import java.util.StringTokenizer; import java.io.Writer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Asgar Javadov */ 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 { char[] s; long result = 0L; int right; int[] r; public void solve(int testNumber, InputReader in, OutputWriter out) { s = in.next().toCharArray(); boolean allEq = true; for (int i = 1; i < s.length; ++i) { if (s[i] != s[0]) { allEq = false; break; } } if (allEq) { out.println((s.length - 2) * (long) (s.length - 1) / 2); return; } IntList zeros = new IntList(s.length); IntList ones = new IntList(s.length); for (int i = 0; i < s.length; i++) { if (s[i] == '0') zeros.add(i); else ones.add(i); } zeros.sortAndCompressAsUnique(); ones.sortAndCompressAsUnique(); r = new int[s.length]; right = s.length; int zeroIndex = 0; int oneIndex = 0; for (int i = 0; i < s.length; ++i) { if (s[i] == '0') { r[i] = solveBit(zeros, zeroIndex, i, '0'); zeroIndex++; } else { r[i] = solveBit(ones, oneIndex, i, '1'); oneIndex++; } } int leftMost = s.length; for (int i = s.length - 1; i >= 0; --i) { leftMost = Math.min(r[i], leftMost); result += (s.length - leftMost); } out.println(result); } private int solveBit(IntList zeros, int pos, int start, char ch) { for (int i = pos + 1; i < zeros.size(); ++i) { int next = zeros.get(i); int nn = next + (next - start); if (nn < s.length && s[nn] == ch) { return nn; } if (nn >= s.length) break; } return s.length; } } static class OutputWriter extends PrintWriter { public OutputWriter(OutputStream outputStream) { super(outputStream); } public OutputWriter(Writer writer) { super(writer); } public OutputWriter(String filename) throws FileNotFoundException { super(filename); } public void close() { super.close(); } } static class InputReader extends BufferedReader { StringTokenizer tokenizer; public InputReader(InputStream inputStream) { super(new InputStreamReader(inputStream), 32768); } public InputReader(String filename) { super(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(filename))); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(readLine()); } catch (IOException e) { throw new RuntimeException(); } } return tokenizer.nextToken(); } } static class IntList implements Iterable<Integer> { public static final int INITIAL_CAPACITY = 4; private int size; private int[] array; public IntList() { this(INITIAL_CAPACITY); } public IntList(int initialCapacity) { this.array = new int[initialCapacity]; this.size = 0; } public IntList(int[] array) { this.array = Arrays.copyOf(array, array.length); this.size = this.array.length; } public IntList(Collection<Integer> collection) { this.size = collection.size(); this.array = new int[size]; int index = 0; for (int e : collection) { array[index++] = e; } } public void add(int value) { if (size == array.length) { ensureCapacity(); } this.array[this.size++] = value; } public int get(int index) { if (index < 0 || index >= size) throw new IllegalArgumentException("Expected argument in [0, " + size + "), but found " + index); return array[index]; } public void sortAndCompressAsUnique() { if (size <= 1) return; Arrays.sort(array, 0, size); int uniqueSize = 1; for (int i = 1; i < size; i++) { if (array[i] != array[i - 1]) uniqueSize++; } int[] temp = new int[uniqueSize]; temp[0] = array[0]; for (int i = 1, j = 1; i < size; i++) { if (array[i] != array[i - 1]) temp[j++] = array[i]; } array = temp; size = uniqueSize; } public int size() { return this.size; } private void ensureCapacity() { if (size < array.length) return; this.array = Arrays.copyOf(array, array.length << 1); } public IntList clone() { IntList cloned = new IntList(Math.max(1, this.size)); for (int i = 0; i < size; ++i) cloned.add(array[i]); return cloned; } public Iterator<Integer> iterator() { return new IntListIterator(); } private class IntListIterator implements Iterator<Integer> { private int current; public IntListIterator() { this.current = 0; } public boolean hasNext() { return this.current < size; } public Integer next() { return array[current++]; } } } }
Java
["010101", "11001100"]
4 seconds
["3", "0"]
NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$.
Java 8
standard input
[ "brute force" ]
71bace75df1279ae55a6e755159d4191
The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 300\,000$$$), consisting of zeros and ones.
1,900
Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.
standard output
PASSED
74209650b21741dbb4b73a577b743b85
train_000.jsonl
1558884900
Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.
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.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; import java.util.stream.Collectors; public class Main { static class Task { int NN = 200005; int MOD = 1000000007; int INF = 2000000000; long INFINITY = 2000000000000000000L; public void solve(InputReader in, PrintWriter out) { String s = in.next(); int n = s.length(); int prev = -1; long ans = 0; for(int i=n-1;i>=0;--i) { int start = prev - 1; if(start < 0) start = n - 1; for(int k=1;i+2*k<=start;++k) { if(s.charAt(i) == s.charAt(i+k) && s.charAt(i+k) == s.charAt(i+k*2)) { prev = i+2*k; break; } } if(prev != -1) ans += 1L*(n-prev); } out.println(ans); } } static void prepareIO(boolean isFileIO) { //long t1 = System.currentTimeMillis(); Task solver = new Task(); // Standard IO if(!isFileIO) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); solver.solve(in, out); //out.println("time(s): " + (1.0*(System.currentTimeMillis()-t1))/1000.0); out.close(); } // File IO else { String IPfilePath = System.getProperty("user.home") + "/Downloads/ip.in"; String OPfilePath = System.getProperty("user.home") + "/Downloads/op.out"; InputReader fin = new InputReader(IPfilePath); PrintWriter fout = null; try { fout = new PrintWriter(new File(OPfilePath)); } catch (FileNotFoundException e) { e.printStackTrace(); } solver.solve(fin, fout); //fout.println("time(s): " + (1.0*(System.currentTimeMillis()-t1))/1000.0); fout.close(); } } public static void main(String[] args) { prepareIO(false); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public InputReader(String filePath) { File file = new File(filePath); try { reader = new BufferedReader(new FileReader(file)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } tokenizer = null; } public String nextLine() { String str = ""; try { str = reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return str; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["010101", "11001100"]
4 seconds
["3", "0"]
NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$.
Java 8
standard input
[ "brute force" ]
71bace75df1279ae55a6e755159d4191
The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 300\,000$$$), consisting of zeros and ones.
1,900
Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.
standard output
PASSED
fc103d0ebf89a23ed31c094af51c016a
train_000.jsonl
1558884900
Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.
256 megabytes
// https://codeforces.com/blog/entry/67189?#comment-513690 // upsolve with rainboy import java.io.*; public class CF1169D { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); char[] cc = br.readLine().toCharArray(); int n = cc.length; boolean[][] dp = new boolean[n][9]; long cnt = 0; for (int k = 3; k < 9; k++) for (int i = 0; i + k <= n; i++) { boolean good; if (k % 2 == 1 && cc[i] == cc[i + k / 2] && cc[i] == cc[i + k - 1]) good = true; else good = dp[i][k - 1] || dp[i + 1][k - 1]; if ((dp[i][k] = good)) cnt++; } if (n >= 9) cnt += (long) (n - 8) * (n - 7) / 2; System.out.println(cnt); } }
Java
["010101", "11001100"]
4 seconds
["3", "0"]
NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$.
Java 8
standard input
[ "brute force" ]
71bace75df1279ae55a6e755159d4191
The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 300\,000$$$), consisting of zeros and ones.
1,900
Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.
standard output
PASSED
311a906d2fdcdce65411c1ffa36e940f
train_000.jsonl
1558884900
Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.
256 megabytes
import java.util.Scanner; public class D562 { @SuppressWarnings("resource") public static void main(String[] args){ Scanner input = new Scanner(System.in); char[] nums = input.next().toCharArray(); int l = nums.length; int[] close = new int[l]; for (int i = 0; i < l; i++){ close[i] = l; } for (int x = 0; x < l - 1; x++){ for (int k = 1; k <= (l - 1 - x) / 2; k++){ //System.out.println(x + " " + k); if (nums[x] == nums[x + k] && nums[x] == nums[x + k + k]){ close[x] = x + k + k; break; } } } //System.out.println(Arrays.toString(close)); int min = l; for (int i = l - 2; i >= 0; i--){ min = Math.min(min, close[i]); close[i] = min; } //System.out.println(Arrays.toString(close)); long sum = 0; for (int n : close){ sum += l - n; } System.out.println(sum); } }
Java
["010101", "11001100"]
4 seconds
["3", "0"]
NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$.
Java 8
standard input
[ "brute force" ]
71bace75df1279ae55a6e755159d4191
The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 300\,000$$$), consisting of zeros and ones.
1,900
Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.
standard output
PASSED
9eb61f13a3a922dfbecb30ef1383a500
train_000.jsonl
1558884900
Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; public class D { public static void main(String[] args) throws IOException { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); HashSet<String> stringSet = new HashSet<String>(); for (int l = 1; l <= 8; l++) { for (int i = 0; i < 1 << l; i++) { boolean found = false; for (int a = 0; a < l; a++) { for (int k = 1; a + 2 * k < l; k++) { int b = a + k; int c = a + 2 * k; int aBit = (i & (1 << a)) >> a; int bBit = (i & (1 << b)) >> b; int cBit = (i & (1 << c)) >> c; if (aBit == bBit && bBit == cBit) { found = true; } } } if (!found) { StringBuilder sb = new StringBuilder(); for (int j = 0; j < l; j++) { int bit = (i & (1 << j)) >> j; sb.append(bit); } stringSet.add(sb.reverse().toString()); } } } String binaryString = input.readLine(); long totalWays = ((long) binaryString.length()) * (binaryString.length() + 1) / 2; //System.out.println("Ways: " + totalWays); for (int i = 0; i <= binaryString.length(); i++) { for (int j = 2; i - j + 1 >= 0 && j <= 9; j++) { String substring = binaryString.substring(i - j + 1, i); //System.out.println(substring); if (stringSet.contains(substring)) { totalWays--; } } //System.out.println("Ways: " + totalWays); } System.out.println(totalWays); } }
Java
["010101", "11001100"]
4 seconds
["3", "0"]
NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$.
Java 8
standard input
[ "brute force" ]
71bace75df1279ae55a6e755159d4191
The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 300\,000$$$), consisting of zeros and ones.
1,900
Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.
standard output
PASSED
482f7e766c2a35a2f3619656d00f7c5f
train_000.jsonl
1558884900
Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.reflect.Array; public class D { static final int MOD = 1000000007; // 1e9 + 7 static final boolean AUTO_FLUSH = false; // slow if true // int = num(); // long = ll(); // string = next(); // a string line = line(); // ---------------------------------- \ void main() throws Exception { char[] chr = line().toCharArray(); int n = chr.length; long ans = 0; for (int l = 0; l < n-2; l++) { boolean found = false; int r = l+2; for (; r < n && !found; r++) { for (int al = 0; l+al <= r && !found; al++) { for (int add = 1; l+al+2*add <= r && !found; add++) { int i = l+al; if (chr[i] == chr[i+add] && chr[i] == chr[i+2*add]) found = true; } } } if (found) ans += n-(--r); } outln(ans); } // ---------------------------------- \ //#region public static void main(String[] args) throws Exception { new Thread(null, () -> { try { startTime(); new D().main(); boolean endsWithEnter = TO_BE_PRINTED.length() == 0 || TO_BE_PRINTED.charAt(TO_BE_PRINTED.length() - 1) == '\n'; flush(); if (!endsWithEnter) log('\n'); logTime(); logMem(); } catch (Exception e) { e.printStackTrace(); } }, "Main", 1<<26).start(); } static Random RAND = new Random(); static int random(int from, int to) { return RAND.nextInt(to-from+1)+from; } static void logTime() { log("Time: " + getTime() + "ms"); } static void logMem() { log("Memory (End): " + (int) (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 + " KB"); } static long ll() { return Long.parseLong(next()); } static int num() { return Integer.parseInt(next()); } static void generateInputMode() throws Exception { System.setOut(new PrintStream(new FileOutputStream("F://PROGRAMMING/input.txt"))); } static String line() { if (!tokenize()) return null; INPUT_STREAM.setLength(0); if (STRING_TOKENIZER.hasMoreTokens()) INPUT_STREAM.append(STRING_TOKENIZER.nextToken()); while (STRING_TOKENIZER.hasMoreTokens()) INPUT_STREAM.append(' ').append(STRING_TOKENIZER.nextToken()); return INPUT_STREAM.length() == 0 ? null : INPUT_STREAM.toString(); } static void startTime() { TIME_COMPLEXITY = System.currentTimeMillis(); } static long getTime() { return System.currentTimeMillis() - TIME_COMPLEXITY; } static void flush() { System.out.print(TO_BE_PRINTED.toString()); TO_BE_PRINTED.setLength(0); } static void out(Object o) { TO_BE_PRINTED.append(o.toString()); if (AUTO_FLUSH) flush(); } static void _log(String s) { System.err.print(s); } static void _logln(String s) { System.err.println(s); } static void _logln() { System.err.println(); } static void outln(Object o) { out(o); outln(); } static void outln() { out("\n"); } static class Pair implements Comparable<Pair> { public int a, b; public Pair(int a, int b) { this.a = a; this.b = b; } public static Pair of(int a, int b) { return new Pair(a, b); } public int compareTo(Pair p) { if (a == p.a) return Integer.compare(b, p.b); return Integer.compare(a, p.a); } public String toString() { return "[" + a + "," + b + "]"; } public boolean equals(Pair p) { return p.a == a && p.b == b; } } static void logArr(Object val) { Class<?> valKlass = val.getClass(); Object[] outputArray = null; for(Class<?> arrKlass : new Class<?>[] { int[].class, float[].class, double[].class, boolean[].class, byte[].class, short[].class, long[].class, char[].class }) { if (valKlass.isAssignableFrom(arrKlass)) { int arrlength = Array.getLength(val); outputArray = new Object[arrlength]; for(int i = 0; i < arrlength; ++i) outputArray[i] = Array.get(val, i); break; } } if(outputArray == null) outputArray = (Object[])val; logArr0(outputArray); } static void logArr0(Object[] objs) { _log("* " + objs[0]); for (int i = 1; i < objs.length; i++) _log(objs[i].toString().equals("\n") ? "\n>" : (" " + objs[i])); _logln(); } static void log(Object... objs) { logArr0(objs); } static String next() { return tokenize() ? STRING_TOKENIZER.nextToken() : null; } static boolean tokenize() { if (STRING_TOKENIZER == null || !STRING_TOKENIZER.hasMoreTokens()) { try { STRING_TOKENIZER = new StringTokenizer(STREAM_READER.readLine()); } catch (Exception e) { return false; } } return true; } static long TIME_COMPLEXITY; static BufferedReader STREAM_READER = new BufferedReader(new InputStreamReader(System.in), 32768); static StringTokenizer STRING_TOKENIZER; static StringBuilder INPUT_STREAM = new StringBuilder(), TO_BE_PRINTED = new StringBuilder(); //#endregion }
Java
["010101", "11001100"]
4 seconds
["3", "0"]
NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$.
Java 8
standard input
[ "brute force" ]
71bace75df1279ae55a6e755159d4191
The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 300\,000$$$), consisting of zeros and ones.
1,900
Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.
standard output
PASSED
014120520ffdcda107c07506e520b562
train_000.jsonl
1558884900
Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.
256 megabytes
//JDope import java.util.*; import java.io.*; import java.math.*; public class D{ public static void main(String[] omkar) throws Exception { Set<Integer> a1 = new HashSet<Integer>(); a1.add(0); a1.add(1); Set<Integer> a2 = new HashSet<Integer>(); a2.add(0); a2.add(1); a2.add(2); a2.add(3); Set<Integer> a3 = new HashSet<Integer>(); Set<Integer> a4 = new HashSet<Integer>(); Set<Integer> a5 = new HashSet<Integer>(); Set<Integer> a6 = new HashSet<Integer>(); Set<Integer> a7 = new HashSet<Integer>(); Set<Integer> a8 = new HashSet<Integer>(); for(int i = 1; i <= 6; i++) { a3.add(i); if(i > 1) { a4.add(i); } } for(int i = 9; i <= 13; i++) { a4.add(i); } a5.add(4); a5.add(5); a5.add(6); a5.add(9); a5.add(11); a5.add(12); a5.add(13); a5.add(18); a5.add(19); a5.add(20); a5.add(22); a5.add(25); a5.add(26); a5.add(27); a6.add(9); a6.add(11); a6.add(12); a6.add(13); a6.add(18); a6.add(19); a6.add(22); a6.add(25); a6.add(26); a6.add(27); a6.add(36); a6.add(37); a6.add(38); a6.add(41); a6.add(44); a6.add(45); a6.add(50); a6.add(51); a6.add(52); a6.add(54); a7.add(19); a7.add(25); a7.add(26); a7.add(27); a7.add(37); a7.add(44); a7.add(45); a7.add(51); a7.add(76); a7.add(82); a7.add(83); a7.add(90); a7.add(100); a7.add(101); a7.add(102); a7.add(108); a8.add(51); a8.add(90); a8.add(102); a8.add(153); a8.add(165); a8.add(204); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(in.readLine()); StringBuilder sb = new StringBuilder(); String s = st.nextToken(); int[] ones, twos, threes, fours, fives, sixs, sevens, eights, maxR; ones = new int[s.length()]; twos = new int[s.length()]; threes = new int[s.length()]; fours = new int[s.length()]; fives = new int[s.length()]; sixs = new int[s.length()]; sevens = new int[s.length()]; eights = new int[s.length()]; for(int i = 0; i < s.length(); i++) { ones[i] = s.charAt(i)-48; } populate(ones, twos, 2); populate(ones, threes, 3); populate(ones, fours, 4); populate(ones, fives, 5); populate(ones, sixs, 6); populate(ones, sevens, 7); populate(ones, eights, 8); maxR = new int[s.length()]; for(int i = 0; i < ones.length; i++) { if(i < eights.length-7 && a8.contains(eights[i])) { maxR[i] = i+7; } else if(i < sevens.length-6 && a7.contains(sevens[i])) { maxR[i] = i+6; } else if(i < sixs.length-5 && a6.contains(sixs[i])) { maxR[i] = i+5; } else if(i < fives.length-4 && a5.contains(fives[i])) { maxR[i] = i+4; } else if(i < fours.length-3 && a4.contains(fours[i])) { maxR[i] = i+3; } else if(i < threes.length-2 && a3.contains(threes[i])) { maxR[i] = i+2; } else if(i < twos.length-1) { maxR[i] = i+1; } else { maxR[i] = i; } } long total = 0; for(int i = 0; i < maxR.length; i++) { total += (maxR.length-1) - maxR[i]; } System.out.println(total); } public static int[] readArr(int N, BufferedReader in, StringTokenizer st) throws Exception { int[] arr = new int[N]; st = new StringTokenizer(in.readLine()); for(int i=0; i < N; i++) arr[i] = Integer.parseInt(st.nextToken()); return arr; } public static void populate(int[] arr, int[] arr2, int n) { if(n > arr.length) { return; } for(int i = 0; i < n; i++) { arr2[0] += arr[i]*(1<<i); } for(int i = 1; i <= arr.length-n; i++) { arr2[i] = (arr2[i-1]>>1) + arr[i+n-1]*(1<<(n-1)); } } }
Java
["010101", "11001100"]
4 seconds
["3", "0"]
NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$.
Java 8
standard input
[ "brute force" ]
71bace75df1279ae55a6e755159d4191
The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 300\,000$$$), consisting of zeros and ones.
1,900
Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.
standard output
PASSED
2c0175ecc4a87264a511ca10fb29df92
train_000.jsonl
1558884900
Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.
256 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.lang.invoke.MethodHandles; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.PriorityQueue; import java.util.Random; import java.util.TreeSet; public final class CF_562_D2_D { static boolean verb=true; static void log(Object X){if (verb) System.err.println(X);} static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}} static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}} static void logWln(Object X){if (verb) System.err.print(X);} static void info(Object o){ System.out.println(o);} static void output(Object o){outputWln(""+o+"\n"); } static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}} static long mod=1000000007; // Global vars static BufferedWriter out; static InputReader reader; static long powerMod(long b,long e,long m){ long x=1; while (e>0) { if (e%2==1) x=(b*x)%m; b=(b*b)%m; e=e/2; } return x; } static long pgcd(long a,long b){ if (b>a) return pgcd(b,a); while (b>0){ long c=b; b=a%b; a=c; } return a; } static void test() { log("testing"); log("done"); } static boolean ok(String s,int e,int f) { loop:for (int i=e;i<f;i++) { for (int k=1;i+2*k<f;k++) { if (s.charAt(i)==s.charAt(i+k) && s.charAt(i)==s.charAt(i+2*k)) { return true; } } } return false; } static void explore(int L) { int MX=1<<L; int[] found=new int[MX]; Arrays.fill(found, -1); int cnt=0; for (int u=0;u<MX;u++) { String s=Integer.toBinaryString(u); while (s.length()<L) s="0"+s; if (ok(s,0,s.length())) cnt++; else { log("not working with s:"+s); } } log("MX:"+MX+" cnt:"+cnt); } static int GOOD=9; static int[][] cache; static void process() throws Exception { out = new BufferedWriter(new OutputStreamWriter(System.out)); reader = new InputReader(System.in); //cache=new int[GOOD][GOOD]; String s=reader.readString(); long res=0; int L=s.length(); for (int i=0;i<L;i++) { int j=i+GOOD; if (j<L) { res+=L-j; } for (int u=1;u<=GOOD && u+i<=L;u++) { j=i+u; if (ok(s,i,j)) res++; } } output(res); try { out.close(); } catch (Exception e) { } } public static void main(String[] args) throws Exception { process(); } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) { return -1; } } return buf[curChar++]; } public final String readString() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.append((char) c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public final int readInt() throws IOException { int c = read(); boolean neg = false; while (isSpaceChar(c)) { c = read(); } char d = (char) c; // log("d:"+d); if (d == '-') { neg = true; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); // log("res:"+res); if (neg) return -res; return res; } public final long readLong() throws IOException { int c = read(); boolean neg = false; while (isSpaceChar(c)) { c = read(); } char d = (char) c; // log("d:"+d); if (d == '-') { neg = true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); // log("res:"+res); if (neg) return -res; return res; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["010101", "11001100"]
4 seconds
["3", "0"]
NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$.
Java 8
standard input
[ "brute force" ]
71bace75df1279ae55a6e755159d4191
The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 300\,000$$$), consisting of zeros and ones.
1,900
Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.
standard output
PASSED
0d0dab6804a97a8b282b87cd71e72d39
train_000.jsonl
1558884900
Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.
256 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.lang.invoke.MethodHandles; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.PriorityQueue; import java.util.Random; import java.util.TreeSet; public final class CF_562_D2_D { static boolean verb=true; static void log(Object X){if (verb) System.err.println(X);} static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}} static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}} static void logWln(Object X){if (verb) System.err.print(X);} static void info(Object o){ System.out.println(o);} static void output(Object o){outputWln(""+o+"\n"); } static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}} static long mod=1000000007; // Global vars static BufferedWriter out; static InputReader reader; static long powerMod(long b,long e,long m){ long x=1; while (e>0) { if (e%2==1) x=(b*x)%m; b=(b*b)%m; e=e/2; } return x; } static long pgcd(long a,long b){ if (b>a) return pgcd(b,a); while (b>0){ long c=b; b=a%b; a=c; } return a; } static void test() { log("testing"); log("done"); } static boolean ok(String s,int e,int f) { /* int L=f-e; int x=Integer.parseInt(s.substring(e,f),2); if (cache[L][x]!=0) return cache[L][x]==1; */ loop:for (int i=e;i<f;i++) { for (int k=1;i+2*k<f;k++) { if (s.charAt(i)==s.charAt(i+k) && s.charAt(i)==s.charAt(i+2*k)) { //cache[L][x]=1; return true; } } } //cache[L][x]=-1; return false; } static void explore(int L) { int MX=1<<L; int[] found=new int[MX]; Arrays.fill(found, -1); int cnt=0; for (int u=0;u<MX;u++) { String s=Integer.toBinaryString(u); while (s.length()<L) s="0"+s; if (ok(s,0,s.length())) cnt++; else { log("not working with s:"+s); } } log("MX:"+MX+" cnt:"+cnt); } static int GOOD=9; static int[][] cache; static void process() throws Exception { out = new BufferedWriter(new OutputStreamWriter(System.out)); reader = new InputReader(System.in); //cache=new int[GOOD][1<<(GOOD)]; String s=reader.readString(); long res=0; int L=s.length(); for (int i=0;i<L;i++) { iter:for (int u=1;u<=GOOD && u+i<=L;u++) { int j=i+u; if (ok(s,i,j)) { res+=L-j+1; break; } } } output(res); try { out.close(); } catch (Exception e) { } } public static void main(String[] args) throws Exception { process(); } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) { return -1; } } return buf[curChar++]; } public final String readString() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.append((char) c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public final int readInt() throws IOException { int c = read(); boolean neg = false; while (isSpaceChar(c)) { c = read(); } char d = (char) c; // log("d:"+d); if (d == '-') { neg = true; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); // log("res:"+res); if (neg) return -res; return res; } public final long readLong() throws IOException { int c = read(); boolean neg = false; while (isSpaceChar(c)) { c = read(); } char d = (char) c; // log("d:"+d); if (d == '-') { neg = true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); // log("res:"+res); if (neg) return -res; return res; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["010101", "11001100"]
4 seconds
["3", "0"]
NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$.
Java 8
standard input
[ "brute force" ]
71bace75df1279ae55a6e755159d4191
The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 300\,000$$$), consisting of zeros and ones.
1,900
Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.
standard output
PASSED
3227f67175a914ffb85d562c13b1bb5a
train_000.jsonl
1558884900
Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.
256 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.lang.invoke.MethodHandles; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.PriorityQueue; import java.util.Random; import java.util.TreeSet; public final class CF_562_D2_D { static boolean verb=true; static void log(Object X){if (verb) System.err.println(X);} static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}} static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}} static void logWln(Object X){if (verb) System.err.print(X);} static void info(Object o){ System.out.println(o);} static void output(Object o){outputWln(""+o+"\n"); } static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}} static long mod=1000000007; // Global vars static BufferedWriter out; static InputReader reader; static long powerMod(long b,long e,long m){ long x=1; while (e>0) { if (e%2==1) x=(b*x)%m; b=(b*b)%m; e=e/2; } return x; } static long pgcd(long a,long b){ if (b>a) return pgcd(b,a); while (b>0){ long c=b; b=a%b; a=c; } return a; } static void test() { log("testing"); log("done"); } static boolean ok(String s,int e,int f) { /* int L=f-e; int x=Integer.parseInt(s.substring(e,f),2); if (cache[L][x]!=0) return cache[L][x]==1; */ loop:for (int i=e;i<f;i++) { for (int k=1;i+2*k<f;k++) { if (s.charAt(i)==s.charAt(i+k) && s.charAt(i)==s.charAt(i+2*k)) { //cache[L][x]=1; return true; } } } //cache[L][x]=-1; return false; } static void explore(int L) { int MX=1<<L; int[] found=new int[MX]; Arrays.fill(found, -1); int cnt=0; for (int u=0;u<MX;u++) { String s=Integer.toBinaryString(u); while (s.length()<L) s="0"+s; if (ok(s,0,s.length())) cnt++; else { log("not working with s:"+s); } } log("MX:"+MX+" cnt:"+cnt); } static int GOOD=9; static int[][] cache; static void process() throws Exception { out = new BufferedWriter(new OutputStreamWriter(System.out)); reader = new InputReader(System.in); //cache=new int[GOOD][1<<(GOOD)]; String s=reader.readString(); long res=0; int L=s.length(); for (int i=0;i<L;i++) { int j=i+GOOD-1; if (j<L) { res+=L-j; } for (int u=1;u<GOOD && u+i<=L;u++) { j=i+u; if (ok(s,i,j)) res++; } } output(res); try { out.close(); } catch (Exception e) { } } public static void main(String[] args) throws Exception { process(); } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) { return -1; } } return buf[curChar++]; } public final String readString() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.append((char) c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public final int readInt() throws IOException { int c = read(); boolean neg = false; while (isSpaceChar(c)) { c = read(); } char d = (char) c; // log("d:"+d); if (d == '-') { neg = true; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); // log("res:"+res); if (neg) return -res; return res; } public final long readLong() throws IOException { int c = read(); boolean neg = false; while (isSpaceChar(c)) { c = read(); } char d = (char) c; // log("d:"+d); if (d == '-') { neg = true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); // log("res:"+res); if (neg) return -res; return res; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["010101", "11001100"]
4 seconds
["3", "0"]
NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$.
Java 8
standard input
[ "brute force" ]
71bace75df1279ae55a6e755159d4191
The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 300\,000$$$), consisting of zeros and ones.
1,900
Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.
standard output
PASSED
c7215f921d7603d57b788f28ae595cde
train_000.jsonl
1558884900
Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.
256 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.lang.invoke.MethodHandles; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.PriorityQueue; import java.util.Random; import java.util.TreeSet; public final class CF_562_D2_D { static boolean verb=true; static void log(Object X){if (verb) System.err.println(X);} static void log(Object[] X){if (verb) {for (Object U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X){if (verb) {for (int U:X) System.err.print(U+" ");System.err.println("");}} static void log(int[] X,int L){if (verb) {for (int i=0;i<L;i++) System.err.print(X[i]+" ");System.err.println("");}} static void log(long[] X){if (verb) {for (long U:X) System.err.print(U+" ");System.err.println("");}} static void logWln(Object X){if (verb) System.err.print(X);} static void info(Object o){ System.out.println(o);} static void output(Object o){outputWln(""+o+"\n"); } static void outputWln(Object o){try {out.write(""+ o);} catch (Exception e) {}} static long mod=1000000007; // Global vars static BufferedWriter out; static InputReader reader; static long powerMod(long b,long e,long m){ long x=1; while (e>0) { if (e%2==1) x=(b*x)%m; b=(b*b)%m; e=e/2; } return x; } static long pgcd(long a,long b){ if (b>a) return pgcd(b,a); while (b>0){ long c=b; b=a%b; a=c; } return a; } static void test() { log("testing"); log("done"); } static boolean ok(String s,int e,int f) { int L=f-e; int x=Integer.parseInt(s.substring(e,f),2); if (cache[L][x]!=0) return cache[L][x]==1; loop:for (int i=e;i<f;i++) { for (int k=1;i+2*k<f;k++) { if (s.charAt(i)==s.charAt(i+k) && s.charAt(i)==s.charAt(i+2*k)) { cache[L][x]=1; return true; } } } cache[L][x]=-1; return false; } static void explore(int L) { int MX=1<<L; int[] found=new int[MX]; Arrays.fill(found, -1); int cnt=0; for (int u=0;u<MX;u++) { String s=Integer.toBinaryString(u); while (s.length()<L) s="0"+s; if (ok(s,0,s.length())) cnt++; else { log("not working with s:"+s); } } log("MX:"+MX+" cnt:"+cnt); } static int GOOD=9; static int[][] cache; static void process() throws Exception { out = new BufferedWriter(new OutputStreamWriter(System.out)); reader = new InputReader(System.in); cache=new int[GOOD][1<<(GOOD)]; String s=reader.readString(); long res=0; int L=s.length(); for (int i=0;i<L;i++) { int j=i+GOOD-1; if (j<L) { res+=L-j; } for (int u=1;u<GOOD && u+i<=L;u++) { j=i+u; if (ok(s,i,j)) res++; } } output(res); try { out.close(); } catch (Exception e) { } } public static void main(String[] args) throws Exception { process(); } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) { return -1; } } return buf[curChar++]; } public final String readString() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.append((char) c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public final int readInt() throws IOException { int c = read(); boolean neg = false; while (isSpaceChar(c)) { c = read(); } char d = (char) c; // log("d:"+d); if (d == '-') { neg = true; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); // log("res:"+res); if (neg) return -res; return res; } public final long readLong() throws IOException { int c = read(); boolean neg = false; while (isSpaceChar(c)) { c = read(); } char d = (char) c; // log("d:"+d); if (d == '-') { neg = true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); // log("res:"+res); if (neg) return -res; return res; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["010101", "11001100"]
4 seconds
["3", "0"]
NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$.
Java 8
standard input
[ "brute force" ]
71bace75df1279ae55a6e755159d4191
The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 300\,000$$$), consisting of zeros and ones.
1,900
Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.
standard output
PASSED
e1789fc66e43225f10894eac62c2f227
train_000.jsonl
1558884900
Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; 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 { public void solve(int testNumber, Scanner in, PrintWriter out) { String s = in.next(); long count = 0; long x = s.length(); for (int i = s.length() - 3; i >= 0; i--) { int k = 1; while (i + 2 * k < s.length()) { if (s.charAt(i) == s.charAt(i + k) && s.charAt(i) == s.charAt(i + 2 * k)) break; k++; } x = Math.min(x, i + 2 * k); count += s.length() - x; } out.print(count); } } }
Java
["010101", "11001100"]
4 seconds
["3", "0"]
NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$.
Java 8
standard input
[ "brute force" ]
71bace75df1279ae55a6e755159d4191
The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 300\,000$$$), consisting of zeros and ones.
1,900
Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.
standard output
PASSED
4438cbdcd9a837b47a830c21916c3392
train_000.jsonl
1558884900
Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; /** * @author madi.sagimbekov */ public class C1169D { private static BufferedReader in; private static BufferedWriter out; private static List<Integer>[] list; private static int[] arr; private static int[][] dir = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; private static boolean[] used; public static void main(String[] args) throws IOException { open(); char[] c = readString().toCharArray(); int n = c.length; long ans = 0; for (int i = 0; i < n; i++) { for (int j = i; j < i + 20 && j < n; j++) { if (!checkAll(c, n, i, j)) { ans += n - j; break; } } } out.write(ans + "\n"); close(); } private static boolean checkAll(char[] c, int n, int left, int right) { for (int i = left; i < right; i++) { for (int j = 1; j < n; j++) { int l = i - j; int r = i + j; if (l < left || r > right) { break; } if (c[l] == c[i] && c[r] == c[i]) { return false; } } } return true; } private static int[] readInts() throws IOException { return Stream.of(in.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); } private static int readInt() throws IOException { return Integer.parseInt(in.readLine()); } private static long[] readLongs() throws IOException { return Stream.of(in.readLine().split(" ")).mapToLong(Long::parseLong).toArray(); } private static long readLong() throws IOException { return Long.parseLong(in.readLine()); } private static double[] readDoubles() throws IOException { return Stream.of(in.readLine().split(" ")).mapToDouble(Double::parseDouble).toArray(); } private static double readDouble() throws IOException { return Double.parseDouble(in.readLine()); } private static String readString() throws IOException { return in.readLine(); } private static List<Integer>[] buildAdjacencyList(int n, int m) throws IOException { List<Integer>[] list = new ArrayList[n + 1]; for (int i = 0; i <= n; i++) { list[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { int[] e = readInts(); list[e[0]].add(e[1]); list[e[1]].add(e[0]); } return list; } private static void open() { in = new BufferedReader(new InputStreamReader(System.in)); out = new BufferedWriter(new OutputStreamWriter((System.out))); } private static void close() throws IOException { out.flush(); out.close(); in.close(); } }
Java
["010101", "11001100"]
4 seconds
["3", "0"]
NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$.
Java 8
standard input
[ "brute force" ]
71bace75df1279ae55a6e755159d4191
The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 300\,000$$$), consisting of zeros and ones.
1,900
Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.
standard output
PASSED
143a7fdb62d4d2bfb03d3a1fa6c0a7f2
train_000.jsonl
1558884900
Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.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); DGoodTriple solver = new DGoodTriple(); solver.solve(1, in, out); out.close(); } static class DGoodTriple { public void solve(int testNumber, InputReader in, PrintWriter out) { String S = in.next(); int N = S.length(); int[] x = new int[N]; Arrays.fill(x, -1); long ans = 0; for (int i = 0; i < N; i++) { for (int k = 1; i + k < N && i + 2 * k < N; k++) { if (S.charAt(i) == S.charAt(i + k) && S.charAt(i + k) == S.charAt(i + 2 * k)) { x[i] = i + 2 * k; break; } } } x[N - 1] = N; for (int i = N - 2; i >= 0; i--) { x[i] = (x[i] != -1) ? Math.min(x[i], x[i + 1]) : x[i + 1]; ans += (N - x[i]); } out.println(ans); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["010101", "11001100"]
4 seconds
["3", "0"]
NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$.
Java 8
standard input
[ "brute force" ]
71bace75df1279ae55a6e755159d4191
The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 300\,000$$$), consisting of zeros and ones.
1,900
Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.
standard output
PASSED
e1a9c9372eac0289132720e5cd4d9652
train_000.jsonl
1558884900
Toad Rash has a binary string $$$s$$$. A binary string consists only of zeros and ones.Let $$$n$$$ be the length of $$$s$$$.Rash needs to find the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.Find this number of pairs for Rash.
256 megabytes
import java.util.*; public class triple { public static void main(String[] args) { Scanner scan=new Scanner(System.in); // int n=9; // T:for(int i=0;i<1<<n;i++) { // String x=Integer.toBinaryString(i); // while(x.length()<n) x="0"+x; // for(int j=0;j<n;j++) { // for(int k=1;k<n;k++) { // if(j+2*k>=n) continue; // if(x.charAt(j)==x.charAt(j+k)&&x.charAt(j+k)==x.charAt(j+2*k)) { // continue T; // } // } // } // System.out.println("NO PATTERN "+x); // } long good=0L; // StringBuilder x=new StringBuilder(); // for(int i=0;i<300000;i++) x.append("0"); char[] a=scan.next().toCharArray(); // char[] a=x.toString().toCharArray(); int n=a.length; for(int i=0;i<n;i++) { for(int j=i;j<n&&j<i+8;j++) { if(pat(a,i,j)) { // System.out.println(i+" "+j); good++; } } } if(n>=9) { long dif=n-8; good+=dif*(dif+1)/2; } System.out.println(good); } public static boolean pat(char[] a, int l, int r) { for(int j=l;j<r;j++) { for(int k=1;k<=r-l;k++) { if(j+2*k>r) continue; if(a[j]==a[j+k]&&a[j+k]==a[j+2*k]) { return true; } } } return false; } } /* 1100110011 */
Java
["010101", "11001100"]
4 seconds
["3", "0"]
NoteIn the first example, there are three $$$l$$$, $$$r$$$ pairs we need to count: $$$1$$$, $$$6$$$; $$$2$$$, $$$6$$$; and $$$1$$$, $$$5$$$.In the second example, there are no values $$$x$$$, $$$k$$$ for the initial string, so the answer is $$$0$$$.
Java 8
standard input
[ "brute force" ]
71bace75df1279ae55a6e755159d4191
The first line contains the string $$$s$$$ ($$$1 \leq |s| \leq 300\,000$$$), consisting of zeros and ones.
1,900
Output one integer: the number of such pairs of integers $$$l$$$, $$$r$$$ that $$$1 \leq l \leq r \leq n$$$ and there is at least one pair of integers $$$x$$$, $$$k$$$ such that $$$1 \leq x, k \leq n$$$, $$$l \leq x &lt; x + 2k \leq r$$$, and $$$s_x = s_{x+k} = s_{x+2k}$$$.
standard output
PASSED
c48c474d0d62e4d0a6bad6d85bbc5dcd
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import java.io.IOException; import java.io.InputStream; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { File file = new File("in.txt"); InputStream inputStream = null; // try {inputStream= new FileInputStream(file);} catch (FileNotFoundException ex){return;}; inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) { Integer numOfOp = in.nextInt(); Map<BigInteger,BigInteger> costs = new HashMap<>(); for(int i=0; i<numOfOp; i++){ Integer opType = in.nextInt(); BigInteger source = new BigInteger(in.next()); BigInteger target = new BigInteger(in.next()); Set<BigInteger> path = visitedVertices(source,target); if(opType.equals(1)){ BigInteger cost = BigInteger.valueOf(in.nextInt()); for(BigInteger elem : path){ if(costs.containsKey(elem)){ BigInteger oldCost = costs.get(elem); costs.put(elem,oldCost.add(cost)); } else{ costs.put(elem,cost); } } } else{ BigInteger sum = BigInteger.valueOf(0); for(BigInteger elem : path){ sum = sum.add(costs.getOrDefault(elem,BigInteger.ZERO)); } out.println(sum.toString()); } } } public Set<BigInteger> visitedVertices(BigInteger u, BigInteger v){ Integer levelU = u.bitLength(); Integer levelV = v.bitLength(); Set<BigInteger> path = new HashSet<>(); BigInteger parentU = u; BigInteger parentV = v; if(parentU.equals(parentV)){ return path; } while(!parentU.equals(parentV)){ if(levelU > levelV){ path.add(parentU); parentU = parentU.divide(BigInteger.valueOf(2)); levelU-=1; } else{ path.add(parentV); parentV = parentV.divide(BigInteger.valueOf(2)); levelV-=1; } } return path; } } 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 String nextLine(){ try { return reader.readLine(); } catch (IOException e){ throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } class Pair<F, S> { public final F first; public final S second; public Pair(F first, S second) { this.first = first; this.second = second; } @Override public boolean equals(Object o) { if (!(o instanceof Pair)) { return false; } Pair<?, ?> p = (Pair<?, ?>) o; return Objects.equals(p.first, first) && Objects.equals(p.second, second); } @Override public int hashCode() { return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode()); } @Override public String toString() { return "(" + first + ", " + second + ')'; } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
9894081326f504f600b7ea44c16c055b
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeMap; public class CF_C { static BufferedReader in; static PrintWriter out; static StringTokenizer tok; public static void main(String[] args) throws IOException { try { in = new BufferedReader(new FileReader("diameter.in")); out = new PrintWriter(new File("diameter.out")); } catch (Exception e) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); } tok = new StringTokenizer(""); new CF_C().solve(); out.flush(); out.close(); } String nextTok() throws IOException { if (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextTok()); } long nextLong() throws IOException { return Long.parseLong(nextTok()); } double nextDouble() throws IOException { return Double.parseDouble(nextTok()); } static class Pair implements Comparable<Pair> { long x; long y; Pair (long x, long y) { this.x = x; this.y = y; } @Override public int compareTo(Pair o) { if (x < o.x) return -1; if (x > o.x) return 1; if (y < o.y) return -1; if (y > o.y) return 1; return 0; } } void solve() throws IOException { int n = nextInt(); Map<Pair,Long> map = new TreeMap<>(); for (int i = 0; i < n; i++) { int t = nextInt(); long from = nextLong(); long to = nextLong(); // System.out.println(t); if (t == 1) { long w = nextLong(); // System.out.println(from+" "+to); while (from != to) { // System.out.println(from+" "+to); if (from < to) { long tmp = from; from = to; to = tmp; } long fromO = from; from /= 2; Pair p = new Pair(fromO,from); if (map.containsKey(p)) { map.put(p, map.get(p) + w); } else { map.put(p,w); } } } else { long ans = 0; while (from != to) { if (from < to) { long tmp = from; from = to; to = tmp; } long fromO = from; from /= 2; // System.out.println(fromO+" "+from+" !"); Pair p = new Pair(fromO,from); if (map.containsKey(p)) { ans += map.get(p); } } System.out.println(ans); } // System.out.println(map.size()); // for (Map.Entry<Pair,Long> e: map.entrySet()) { // System.out.println(e.getKey().x+" "+e.getKey().y+" "+e.getValue()); // } } } private BigInteger catalan (int i) { return factorial(2 * i).divide((factorial(i + 1).multiply(factorial(i)))); } private BigInteger factorial (int i) { BigInteger n = BigInteger.valueOf(i); if (i == 0) { return new BigInteger("1"); } while (--i > 0) { n = n.multiply(BigInteger.valueOf(i)); } return n; } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
55c3c9bce0f2d3ead24ca56d71b27655
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.StringTokenizer; public class C{ public static void main(String args[]) { FastScanner scan = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n = scan.nextInt(); HashMap<Long, Long> map = new HashMap<Long, Long>(); for(int q = 0; q < n; q++) { int t = scan.nextInt(); if(t == 1){ long u = scan.nextLong(), v = scan.nextLong(), w = scan.nextLong(); while(u != v){ if(u > v){ map.put(u, map.getOrDefault(u, 0L)+w); u /= 2; } else { map.put(v, map.getOrDefault(v, 0L)+w); v /= 2; } } } else { long u = scan.nextLong(), v = scan.nextLong(), res = 0; while(u != v){ if(u > v){ res += map.getOrDefault(u, 0L); u /= 2; } else { res += map.getOrDefault(v, 0L); v /= 2; } } out.println(res); } } out.close(); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(br.readLine()); } catch (Exception e){e.printStackTrace();} } public String next() { if (st.hasMoreTokens()) return st.nextToken(); try {st = new StringTokenizer(br.readLine());} catch (Exception e) {e.printStackTrace();} return st.nextToken(); } public int nextInt() {return Integer.parseInt(next());} public long nextLong() {return Long.parseLong(next());} public double nextDouble() {return Double.parseDouble(next());} public String nextLine() { String line = ""; if(st.hasMoreTokens()) line = st.nextToken(); else try {return br.readLine();}catch(IOException e){e.printStackTrace();} while(st.hasMoreTokens()) line += " "+st.nextToken(); return line; } public int[] nextIntArray(int n) { int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n){ long[] a = new long[n]; for(int i = 0; i < n; i++) a[i] = nextLong(); return a; } public double[] nextDoubleArray(int n){ double[] a = new double[n]; for(int i = 0; i < n; i++) a[i] = nextDouble(); return a; } public char[][] nextGrid(int n, int m){ char[][] grid = new char[n][m]; for(int i = 0; i < n; i++) grid[i] = next().toCharArray(); return grid; } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
033101206f98810300017043620c5ceb
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.BufferedReader; 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.StringTokenizer; import java.util.TreeMap; public class Lorenzo { static ArrayList<Tri> inc; static TreeMap<Long, Long> costToParent; public static void main(String[] args) throws NumberFormatException, IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); inc = new ArrayList<Tri>(); costToParent = new TreeMap<Long,Long>(); int q = sc.nextInt(); for(int i=0; i<q; i++) { int t = sc.nextInt(); if(t == 1) { addCostToParent(sc.nextLong(), sc.nextLong(), sc.nextInt()); // inc.add(new Tri(sc.nextLong(), sc.nextLong(), sc.nextInt())); } else { long u = sc.nextLong(); long v = sc.nextLong(); long cost = 0; int level1 = 0; int level2 = 0; long tmpU = u; long tmpV = v; while(tmpU > 1) { level1++; tmpU/=2; } while(tmpV > 1) { level2++; tmpV/=2; } while(level1 > level2) { Long costToP = costToParent.get(u); if(costToP != null) cost += costToP; u /= 2; level1--; } while(level2 > level1) { Long costToP = costToParent.get(v); if(costToP != null) cost += costToP; v /= 2; level2--; } while(u != v) { Long costToP = costToParent.get(u); if(costToP != null) cost += costToP; costToP = costToParent.get(v); if(costToP != null) cost += costToP; u/=2; v/=2; } out.println(cost); } } out.close(); } private static void addCostToParent(long u, long v, int w) { int level1 = 0; int level2 = 0; long tmpU = u; long tmpV = v; while(tmpU > 1) { level1++; tmpU/=2; } while(tmpV > 1) { level2++; tmpV/=2; } while(level1 > level2) { Long costToP = costToParent.get(u); if(costToP == null) costToParent.put(u, (long) w); else costToParent.put(u, (long)w + costToP); u /= 2; level1--; } while(level2 > level1) { Long costToP = costToParent.get(v); if(costToP == null) costToParent.put(v, (long) w); else costToParent.put(v, (long)w + costToP); v /= 2; level2--; } while(u != v) { Long costToP = costToParent.get(u); if(costToP == null) costToParent.put(u, (long) w); else costToParent.put(u, (long)w + costToP); costToP = costToParent.get(v); if(costToP == null) costToParent.put(v, (long) w); else costToParent.put(v, (long)w + costToP); u/=2; v/=2; } } static class Scanner { BufferedReader br; StringTokenizer st; Scanner(FileReader f) { br = new BufferedReader(f); } public boolean ready() throws IOException { return br.ready(); } Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } } // static long getCost(long u) // { // long cost = 0; // // for(Tri t : inc) // { // int level1 = 0; // int level2 = 0; // long tmpU = t.u; // long tmpV = t.v; // // while(tmpU > 1) // { // level1++; // tmpU /=2; // } // while(tmpV > 1) // { // level2++; // tmpV /= 2; // } // // tmpU = t.u; // tmpV = t.v; // while(level1 > level2) // { // if(tmpU == u) // cost += t.w; // level1--; // tmpU /= 2; // } // while(level2 > level1) // { // if(tmpV == u) // cost += t.w; // level2--; // tmpV /= 2; // } // // while(tmpU != tmpV) // { // if(tmpU == u || tmpV == u) // cost += t.w; // tmpU/=2; // tmpV/=2; // } // // } // return cost; // } static class Tri{ long u,v; int w; public Tri(long u, long v, int w) { this.u = u; this.v = v; this.w = w; } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
9224a9ff33d41919e61583b6b256ff83
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.util.*; import java.io.* ; public class Main { public static void main(String[] args) throws Exception { // Scanner input = new Scanner(new BufferedReader(new InputStreamReader(System.in), 16000)); InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream), 64000)); int q = in.nextInt() ; HashMap<Long , Long > map = new HashMap<>() ; for(int i = 0 ; i < q ; ++i){ int op = in.nextInt() ; long v = in.nextLong() ; long u = in.nextLong(); if(op == 1){ long w = in.nextLong(); while(v != u){ if(v > u){ if(!map.containsKey(v)) map.put(v, 0l) ; map.put(v, map.get(v) + w) ; v /= 2 ; }else{ if(!map.containsKey(u)) map.put(u, 0l) ; map.put(u, map.get(u) + w) ; u /= 2 ; } } }else{ long ans = 0 ; while(v != u){ if(v > u){ if(!map.containsKey(v)) map.put(v, 0l) ; ans += map.get(v) ; v /= 2 ; }else{ if(!map.containsKey(u)) map.put(u, 0l) ; ans += map.get(u) ; u /= 2 ; } } System.out.println(ans) ; } } out.close(); } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 64000); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
1f3170d7c27795c2e2ccb2d2e78bb776
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.*; import java.util.*; public class CF_676_C_Lorenzo_Von_Matterhorn { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); StringBuilder st = new StringBuilder(); int q = sc.nextInt(); Tree t = new Tree(); while(q -->0 ) if(sc.nextInt() == 1) t.add(sc.nextLong(), sc.nextLong(), sc.nextLong()); else st.append(t.get(sc.nextLong(), sc.nextLong())).append("\n"); System.out.println(st); } static class Tree { TreeMap<Long, Long> child = new TreeMap<>(); Tree() { } void add(long u, long v, long w) { while (u != v) { if (u < v) { long temp = u; u = v; v = temp; } child.put(u, child.getOrDefault(u, 0L) + w); u = u >> 1l; } } long get(long u, long v) { long ans = 0; while (u != v) { if (u < v) { long temp = u; u = v; v = temp; } ans += child.getOrDefault(u, 0L); u = u >> 1l; } return ans; } } 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 void waitHere() throws InterruptedException { Thread.sleep(3000); } 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 Exception { return br.ready(); } public boolean ready(boolean wait) throws Exception { if (wait) Thread.sleep(3000); return br.ready(); } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
6925e46269f1cdc27c9bf2df3f8d6ce8
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.*; import java.util.*; /** * * @author Sourav Kumar Paul */ public class SolveC { public static HashMap<Long,Long> map; public static void main(String[] args) throws IOException{ Reader in = new Reader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int q = in.nextInt(); map = new HashMap<>(); while(q-->0) { int x = in.nextInt(); if(x==1) { long u = in.nextLong(); long v = in.nextLong(); long w = in.nextLong(); sum(u,v,w); } else { long u = in.nextLong(); long v = in.nextLong(); out.println(find(u,v)); } } out.flush(); out.close(); } private static void sum(long u, long v, long w) { long a = Math.min(u,v); long b = Math.max(u,v); while(a!=b) { while(b>a) { long x = map.containsKey(b)? map.get(b)+w:w; map.put(b, x); b/=2; } while(a>b) { long x = map.containsKey(a)? map.get(a)+w:w; map.put(a, x); a/=2; } u = a; v = b; a = Math.min(u,v); b = Math.max(u,v); } } private static long find(long u, long v) { long sum =0; long a = Math.min(u,v); long b = Math.max(u,v); while(a!=b) { while(b>a) { long x = map.containsKey(b)? map.get(b):0; sum+=x; b/=2; } while(a>b) { long x = map.containsKey(a)? map.get(a):0; sum+=x; a/=2; } u = a; v = b; a = Math.min(u,v); b = Math.max(u,v); } return sum; } public static class Reader { public BufferedReader reader; public StringTokenizer st; public Reader(InputStreamReader stream) { reader = new BufferedReader(stream); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public String nextLine() throws IOException{ return reader.readLine(); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble(){ return Double.parseDouble(next()); } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
05cc3667a2269011cec959fd27549e58
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.FileNotFoundException; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class ProblemC { Map<Long, Long> road2cost = new HashMap<Long, Long>(); public static Scanner sc; public static void main(String[] args) throws FileNotFoundException { sc = new Scanner(System.in); // sc = new Scanner(new File("input-c.txt")); new ProblemC().doTest(); } private void doTest() { int q = sc.nextInt(); for (int i = 0; i < q; i++) { int type = sc.nextInt(); long u = sc.nextLong(); long v = sc.nextLong(); if (type == 1) { long cost = sc.nextLong(); while (u != v) { if (u < v) { long temp = u; u = v; v = temp; } // u > v long sumCost = cost; Long got = road2cost.get(u); if (got != null) { sumCost += got; } road2cost.put(u, sumCost); u /= 2; } } else { // type = 2 long res = 0; while (u != v) { if (u < v) { long temp = u; u = v; v = temp; } // u > v // find road u Long got = road2cost.get(u); if (got != null) { res += got; } u /= 2; } System.out.println(res); } } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
975aa8946c8b26e34c7975b8b6d4d83c
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
//package codeforces.contest697; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; public class C { public static void main(String... args) { FastScanner s = new FastScanner(); // for (long i = 0; i < 100; i++) { // for (long j = 0; j < 100; j++) { // if (isAncestor(i, j) != isAncestorBit(i, j)) { // System.out.println(i + " " + j + " " + isAncestor(i, j)); // } // } // } costs = new HashMap<>(); final int Q = s.nextInt(); long u, v, w; for (int q = 0; q < Q; q++) { if (s.nextInt() == 1) { u = s.nextLong(); v = s.nextLong(); w = s.nextLong(); updateCosts(u, v, w); } else { u = s.nextLong(); v = s.nextLong(); solve(u, v); } } } static Map<Long, Long> costs; static void solve(long u, long v) { long c = commonAncestor(u, v), cost = 0; while (u != c) { cost += costs.containsKey(u) ? costs.get(u) : 0; u /= 2; } while (v != c) { cost += costs.containsKey(v) ? costs.get(v) : 0; v /= 2; } System.out.println(cost); } static void updateCosts(long u, long v, long w) { long c = commonAncestor(u, v); while (u != c) { if (costs.containsKey(u)) { costs.put(u, costs.get(u) + w); } else { costs.put(u, w); } u /= 2; } while (v != c) { if (costs.containsKey(v)) { costs.put(v, costs.get(v) + w); } else { costs.put(v, w); } v /= 2; } } static class Tax { long u, v, w, a; Tax(long u, long v, long w) { this.u = u; this.v = v; this.w = w; this.a = commonAncestor(u, v); } } static long commonAncestor(long a, long b) { while (a != b) { while (a > b) { a /= 2; } while (b > a) { b /= 2; } } return a; } // static boolean isAncestor(long a, long b) { // long c = commonAncestor(a, b); // return c == a; // } static boolean isAncestor(long a, long b) { while (b > a) b >>= 1; return a == b; } 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 nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
9250356eb2b8bcbeacefe40e414a615b
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.TreeMap; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); TreeMap<Long, Long> cost = new TreeMap<>(); int q = sc.nextInt(); while(q-->0) { int t = sc.nextInt(); long u = sc.nextLong(), v = sc.nextLong(); if(t == 1) { int w = sc.nextInt(); while(u != v) { if(u < v) { u ^= v; v ^= u; u ^= v; } Long curCost = cost.get(u); if(curCost == null) curCost = 0l; cost.put(u, curCost + w); u >>= 1; } } else { long ans = 0; while(u != v) { if(u < v) { u ^= v; v ^= u; u ^= v; } Long curCost = cost.get(u); if(curCost != null) ans += curCost; u >>= 1; } out.println(ans); } } out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException {return br.ready();} } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
4309d36fc776bdbbe5d15c784424c7ed
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.*; import java.util.*; public class Task { public static void main(String[] args) throws IOException { new Task().solve(); } int mod = 1000000007; PrintWriter out; int n; int m; int inf = 2000000000; void solve() throws IOException { Reader in; try { in = new Reader("input.txt"); out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) ); } catch (Exception e) { in = new Reader(); out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) ); } //BufferedReader br = new BufferedReader( new FileReader("in.txt") ); //BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) ); int n = in.nextInt(); HashMap<Long, Long> map = new HashMap<Long, Long>(); for (int i = 0; i < n; i++) { int t = in.nextInt(); long v = in.nextLong(); long u = in.nextLong(); int lev1 = 0; int lev2 = 0; long a = v; long b = u; while (a > 1) { a /= 2; lev1++; } while (b > 1) { b /= 2; lev2++; } if (t == 1) { int w = in.nextInt(); while (v != u) { if (lev1 >= lev2) { if (map.containsKey(v)) map.put(v, map.get(v)+w); else map.put(v, 1l*w); v /= 2; lev1--; } else { if (map.containsKey(u)) map.put(u, map.get(u)+w); else map.put(u, 1l*w); u /= 2; lev2--; } } } else { long ans = 0; while (v != u) { if (lev1 >= lev2) { if (map.containsKey(v)) ans += map.get(v); v /= 2; lev1--; } else { if (map.containsKey(u)) ans += map.get(u); u /= 2; lev2--; } } out.println(ans); } } out.flush(); out.close(); } //class Edge { int v, u; int w, c; Edge(int v, int u, int w, int c) { this.v = v; this.u = u; this.w = w; this.c = c; } } class Pair implements Comparable<Pair>{ int a; int b; Pair(int a, int b) { this.a = a; this.b = b; } public int compareTo(Pair p) { if (a < p.a) return -1; if (a > p.a) return 1; return 0; } } class Item { int a; int b; int c; Item(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } } class Reader { BufferedReader br; StringTokenizer tok; Reader(String file) throws IOException { br = new BufferedReader( new FileReader(file) ); } Reader() throws IOException { br = new BufferedReader( new InputStreamReader(System.in) ); } String next() throws IOException { while (tok == null || !tok.hasMoreElements()) tok = new StringTokenizer(br.readLine()); return tok.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.valueOf(next()); } long nextLong() throws NumberFormatException, IOException { return Long.valueOf(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.valueOf(next()); } String nextLine() throws IOException { return br.readLine(); } } class Parser { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Parser(InputStream in) { din = new DataInputStream(in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String nextString(int maxSize) { byte[] ch = new byte[maxSize]; int point = 0; try { byte c = read(); while (c == ' ' || c == '\n' || c=='\r') c = read(); while (c != ' ' && c != '\n' && c!='\r') { ch[point++] = c; c = read(); } } catch (Exception e) {} return new String(ch, 0,point); } public int nextInt() { int ret = 0; boolean neg; try { byte c = read(); while (c <= ' ') c = read(); neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; } catch (Exception e) {} return ret; } public long nextLong() { long ret = 0; boolean neg; try { byte c = read(); while (c <= ' ') c = read(); neg = c == '-'; if (neg) c = read(); do { ret = ret * 10 + c - '0'; c = read(); } while (c > ' '); if (neg) return -ret; } catch (Exception e) {} return ret; } private void fillBuffer() { try { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); } catch (Exception e) {} if (bytesRead == -1) buffer[ 0] = -1; } private byte read() { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
dfffd62a3cf8739a3c8717e7ee6f6780
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashMap; import java.util.NoSuchElementException; public class C { int Q; HashMap<Long,HashMap<Long,Long>> map; public void add(long u,long v,long w){ if(u > v){ long tmp = u; u = v; v = tmp; } //u < v int uDepth = 0; while((u >> uDepth) > 0){ uDepth++; } int vDepth = 0; while((v >> vDepth) > 0){ vDepth++; } for(int i = 0;i < vDepth - uDepth;i++){ long nv = (v >> 1); if(map.containsKey(nv)){ if(map.get(nv).containsKey(v)){ map.get(nv).put(v, map.get(nv).get(v) + w); }else{ map.get(nv).put(v, w); } }else{ map.put(nv, new HashMap<Long,Long>()); map.get(nv).put(v, w); } //out.print(v+ " -> " + nv + " "); v = nv; } //out.println(); while(u != v){ long nv = (v >> 1); long nu = (u >> 1); if(nv == 0 || nu == 0)break; if(map.containsKey(nv)){ if(map.get(nv).containsKey(v)){ map.get(nv).put(v, map.get(nv).get(v) + w); }else{ map.get(nv).put(v, w); } }else{ map.put(nv, new HashMap<Long,Long>()); map.get(nv).put(v, w); } if(map.containsKey(nu)){ if(map.get(nu).containsKey(u)){ map.get(nu).put(u, map.get(nu).get(u) + w); }else{ map.get(nu).put(u, w); } }else{ map.put(nu, new HashMap<Long,Long>()); map.get(nu).put(u, w); } //out.println(v+ " -> " + nv + " "); //out.println(u+ " -> " + nu + " "); u = nu; v = nv; } } public long get(long u,long v){ if(u > v){ long tmp = u; u = v; v = tmp; } //u < v int uDepth = 0; while((u >> uDepth) > 0){ uDepth++; } int vDepth = 0; while((v >> vDepth) > 0){ vDepth++; } long uCost = 0; long vCost = 0; for(int i = 0;i < vDepth - uDepth;i++){ long nv = (v >> 1); if(map.containsKey(nv)){ if(map.get(nv).containsKey(v)){ vCost += map.get(nv).get(v); } } v = nv; } while(u != v){ long nv = (v >> 1); long nu = (u >> 1); if(nu == 0 || nv == 0)break; if(map.containsKey(nv)){ if(map.get(nv).containsKey(v)){ vCost += map.get(nv).get(v); } } if(map.containsKey(nu)){ if(map.get(nu).containsKey(u)){ uCost += map.get(nu).get(u); } } u = nu; v = nv; } return vCost + uCost; } public void solve() { Q = nextInt(); map = new HashMap<Long,HashMap<Long,Long>>(); for(int i = 0;i < Q;i++){ int t = nextInt(); if(t == 1){ long v = nextLong(); long u = nextLong(); long w = nextLong(); add(v,u,w); }else{ long v = nextLong(); long u = nextLong(); long ans = get(v,u); out.println(ans); } } /*for(long m : map.keySet()){ for(long n : map.get(m).keySet()){ out.println(m + " " + n + " " + map.get(m).get(n)); } }*/ } public static void main(String[] args) { out.flush(); new C().solve(); out.close(); } /* Input */ private static final InputStream in = System.in; private static final PrintWriter out = new PrintWriter(System.out); private final byte[] buffer = new byte[2048]; private int p = 0; private int buflen = 0; private boolean hasNextByte() { if (p < buflen) return true; p = 0; try { buflen = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (buflen <= 0) return false; return true; } public boolean hasNext() { while (hasNextByte() && !isPrint(buffer[p])) { p++; } return hasNextByte(); } private boolean isPrint(int ch) { if (ch >= '!' && ch <= '~') return true; return false; } private int nextByte() { if (!hasNextByte()) return -1; return buffer[p++]; } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = -1; while (isPrint((b = nextByte()))) { sb.appendCodePoint(b); } return sb.toString(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
85a12f290df84f7d2fee9d59da5493e7
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class TestClass { private static InputStream stream; private static byte[] buf = new byte[1024]; private static int curChar; private static int numChars; private static SpaceCharFilter filter; private static PrintWriter pw; public static class Queue{ private class node{ int val; node next; node(int a){ val = a; next = null; } } node head,tail; Queue(){ head = null; tail = null; } public void EnQueue(int a){ if(head==null){ node p = new node(a); head = p; tail = p; } else{ node p = new node(a); tail.next = p; tail = p; } } public int DeQueue(){ int a = head.val; head = head.next; return a; } public boolean isEmpty(){ return head==null; } } public static long pow(long x,long y,long m){ if(y==0) return 1; long k = pow(x,y/2,m); if(y%2==0) return (k*k)%m; else return (((k*k)%m)*x)%m; } static long Inversex = 0,Inversey = 0; public static void InverseModulo(long a,long m){ if(m==0){ Inversex = 1; Inversey = 0; } else{ InverseModulo(m,a%m); long temp = Inversex; Inversex = Inversey; Inversey = temp+ - (a/m)*Inversey; } } static long mod1 = 1000000007; static long mod2 = 1000000009; public static long gcd(long a,long b){ if(a%b==0) return b; return gcd(b,a%b); } public static boolean isPrime(long a){ if(a==1) return false; else if(a==2||a==3) return true; for(long i=2;i<=Math.sqrt(a);i++) if(a%i==0) return false; return true; } public static double distance(int a,int b,int x,int y){ return Math.sqrt(((long)(a-x)*(long)(a-x))+((long)(b-y)*(long)(b-y))); } public static class Pair implements Comparable<Pair> { long u; long v; BigInteger bi; public Pair(long u, long v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return u == other.u && v == other.v; } public int compareTo(Pair other) { return Long.compare(u, other.u) != 0 ? Long.compare(u, other.u) : Long.compare(v, other.v); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } public static int seive(int a[],boolean b[],TreeSet<Integer> c){ int count = 0; for(int i=2;i<a.length;i++){ if(!b[i]){ for(int j=i*i;j<a.length&&j>0;j=j+i) b[j] = true; c.add(i); a[count++] = i; } } return count; } public static void MatrixMultiplication(int a[][],int b[][],int c[][]){ for(int i=0;i<a.length;i++){ for(int j=0;j<b[0].length;j++){ c[i][j] = 0; for(int k=0;k<b.length;k++) c[i][j]=(int)((c[i][j]+((a[i][k]*(long)b[k][j])%mod1))%mod1); } } } public static void Equal(int arr[][],int temp[][]){ for(int i=0;i<arr.length;i++){ for(int j=0;j<arr.length;j++) temp[i][j] = arr[i][j]; } } public static class Trie { Node head; private class Node{ Node a[] = new Node[2]; boolean val; Node(){ a[0] = null; a[1] = null; val = false; } } Trie(){ head = new Node(); } public void insert(Stack<Integer> s){ Node temp = head; while(!s.isEmpty()){ int q = s.pop(); if(temp.a[q]==null) temp.a[q] = new Node(); temp = temp.a[q]; } temp.val = true; } public Node delete(Stack<Integer> s,Node temp){ if(s.isEmpty()) return null; int q = s.pop(); temp.a[q] = delete(s,temp.a[q]); if(temp.a[q]==null&&temp.a[q^1]==null) return null; else return temp; } public void get(Stack<Integer> s,Stack<Integer> p){ Node temp = head; while(!p.isEmpty()){ int q = p.pop(); if(temp.a[q]!=null){ s.push(q); temp = temp.a[q]; } else{ s.push(q^1); temp = temp.a[q^1]; } } } } public static void Merge(long a[][],int p,int r){ if(p<r){ int q = (p+r)/2; Merge(a,p,q); Merge(a,q+1,r); Merge_Array(a,p,q,r); } } public static void get(long a[][],long b[][],int i,int j){ for(int k=0;k<a[i].length;k++) a[i][k] = b[j][k]; } public static void Merge_Array(long a[][],int p,int q,int r){ long b[][] = new long[q-p+1][a[0].length]; long c[][] = new long[r-q][a[0].length]; for(int i=0;i<b.length;i++){ get(b,a,i,p+i); } for(int i=0;i<c.length;i++){ get(c,a,i,q+i+1); } int i = 0,j = 0; for(int k=p;k<=r;k++){ if(i==b.length){ get(a,c,k,j); j++; } else if(j==c.length){ get(a,b,k,i); i++; } else if(b[i][0]<c[j][0]){ get(a,b,k,i); i++; } else{ get(a,c,k,j); j++; } } } private static void soln(){ int q = nI(); HashMap<Pair,Long> m = new HashMap<Pair,Long>(); while(q-->0){ int t = nI(); if(t==1){ long x = nL(); long y = nL(); long z = nL(); long max = Math.max(x, y); long min = Math.min(x, y); while(max!=min){ if(max>min){ Pair nm = new Pair(max,max/2); if(m.containsKey(nm)) m.put(nm, m.get(nm)+z); else m.put(nm, z); max/=2; } else{ Pair nm = new Pair(min,min/2); if(m.containsKey(nm)) m.put(nm, m.get(nm)+z); else m.put(nm, z); min/=2; } } } else{ long x = nL(); long y = nL(); long count = 0; long max = Math.max(x, y); long min = Math.min(x, y); while(max!=min){ if(max>min){ Pair nm = new Pair(max,max/2); if(m.containsKey(nm)) count+=m.get(nm); max/=2; } else{ Pair nm = new Pair(min,min/2); if(m.containsKey(nm)) count+=m.get(nm); min/=2; } } pw.println(count); } } } public static void main(String[] args) { InputReader(System.in); pw = new PrintWriter(System.out); soln(); pw.close(); } // To Get Input // Some Buffer Methods public static void InputReader(InputStream stream1) { stream = stream1; } private static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private static boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } private static int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } private static int nI() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private static long nL() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private static String nextToken() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private static String nLi() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } private static int[] nIA(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nI(); return arr; } private static long[] nLA(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nL(); return arr; } private static void pArray(int[] arr) { for (int i = 0; i < arr.length; i++) pw.print(arr[i] + " "); pw.println(); return; } private static void pArray(long[] arr) { for (int i = 0; i < arr.length; i++) pw.print(arr[i] + " "); pw.println(); return; } private static boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
38960bbba53df74c150ed034c8eb51da
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; public class Main { static HashMap<Long, Long> dict; public static void main(String arg[]){ InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); int q = in.readInt(); dict = new HashMap<Long, Long>(); for(int i = 0; i < q; i++){ int type = in.readInt(); if(type == 1){ long v = Long.parseLong(in.readString()); long u = Long.parseLong(in.readString()); long lca = getLCA(u,v); int w = in.readInt(); while(v!=lca){ addToDict(v,w); v = v/2; } while(u != lca){ addToDict(u,w); u = u/2; } } else{ long v = Long.parseLong(in.readString()); long u = Long.parseLong(in.readString()); //System.out.println(u+" "+v); long lca = getLCA(u,v); long sum = 0; while(v != lca){ if(dict.containsKey(v)){ sum+=dict.get(v); } v = v/2; } while(u != lca){ if(dict.containsKey(u)){ sum+=dict.get(u); } u = u / 2; } out.printLine(sum); } } out.flush(); } static long getLCA(long u, long v){ List<Long> a= new ArrayList<Long>(); List<Long> b = new ArrayList<Long>(); while(v > 0){ a.add(v); v = v/2; } while(u > 0){ b.add(u); u = u/2; } Collections.reverse(a); Collections.reverse(b); long res = -1; for(int i = 0; i < a.size() && i < b.size(); i++){ if(a.get(i).equals(b.get(i))){ res = a.get(i); } } return res; } static void addToDict(long v, long w){ if(dict.containsKey(v)){ dict.put(v,dict.get(v)+w); } else{ dict.put(v, w); } } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
1be8d094d831d6b51dbecc734f14def7
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.PriorityQueue; import java.util.StringTokenizer; import java.util.concurrent.LinkedBlockingQueue; public class Problem3 { static int sizeCov1 = 0, sizeCov2 = 0; static ArrayList<Integer> cov1; static ArrayList<Integer> cov2; public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); int q = in.nextInt(); HashMap<Long, Long> weights = new HashMap<>(); long u, v, w; int op; long lca; // out.println(lca(2,3)); // out.println(lca(7, 6)); //out.flush(); while(q != 0) { op = in.nextInt(); u = in.nextLong(); v = in.nextLong(); lca = lca(u, v); if(op == 1) { w = in.nextLong(); long n = u; while(n != lca) { updateWeights(weights, n, w ); n /= 2; } n = v; while( n != lca) { updateWeights(weights, n, w ); n /= 2; } } else { long ans = 0; long n = u; while(n != lca) { if(weights.containsKey(n)) { ans += weights.get(n); } n /= 2; } n = v; while(n != lca) { if(weights.containsKey(n)) { ans += weights.get(n); } n /= 2; } out.println(ans); } q--; } out.close(); } static void updateWeights(HashMap<Long, Long> hm, long n, long w) { if(hm.containsKey(n)) { hm.put(n, hm.get(n) + w); } else { hm.put(n, w); } } static long lca(long u, long v) { List<Long> pathU = new ArrayList<Long>(); List<Long> pathV = new ArrayList<Long>(); while(u > 0) { pathU.add(u); u = u / 2; } while(v > 0) { pathV.add(v); v = v / 2; } Collections.reverse(pathU); Collections.reverse(pathV); long lca = -1; for(int i = 0; i < pathU.size() && i < pathV.size(); i++) { if(pathV.get(i).equals(pathU.get(i))) { lca = pathV.get(i); } } return lca; } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
896cbf27c4a00393adca7f4dcea8af5c
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.StringTokenizer; public class C { static HashMap<Long, Edge> map; public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int q = in.nextInt(); map = new HashMap<>(); for(int i=0;i<q;i++){ int type = in.nextInt(); if(type == 1){ long v = in.nextLong(); long u = in.nextLong(); int w = in.nextInt(); add(u, w, i+1); add(v, w, i+1); } else { long v = in.nextLong(); long u = in.nextLong(); out.println(sum(v,i+1) + sum(u,i+1)); } // System.out.println(map); } out.flush(); } static void add(long v, int w, int q){ while(v>1){ if(!map.containsKey(v)) map.put(v, new Edge()); Edge e = map.get(v); if(e.visit != q){ e.val += (long)e.pending; e.pending = 0; e.visit = q; e.pending = w; }else{ e.pending = 0; } v /= 2; } } static long sum(long v, int q){ long res = 0; while(v>1){ if(!map.containsKey(v)) map.put(v, new Edge()); Edge e = map.get(v); if(e.visit!=q){ e.val += (long)e.pending; e.pending = 0; e.visit = q; res += e.val; } else { res -= e.val; } v /= 2; } return res; } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } } } class Edge{ long val; int pending; int visit; public Edge() { this.val = 0; this.pending = 0; this.visit = 0; } @Override public String toString() { return "[v: " + this.val + ", p: " + this.pending + ", visit: " + this.visit; } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
e6ed510d5f27bf54c8783b2b38c04a3c
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.*; import java.math.BigDecimal; import java.util.*; public class Codeforces { static MyScanner sc = new MyScanner(); static long min (long a, long b) { if (a>b) { return b; } return a; } static void newrule (Map<Long,Long> map, long v, long u, long w) { long len1 = 0; long len2 = 0; for (long i=v ; i!=0 ; i=i/2) { len1++; } for (long i=u ; i!=0 ; i=i/2) { len2++; } long [] arr1 = new long[(int) len1]; long [] arr2 = new long[(int) len2]; for (long i=len1-1 ; i>-1 ; i--) { arr1[(int) i] = v; v /= 2; } for (long i=len2-1 ; i>-1 ; i--) { arr2[(int) i] = u; u /= 2; } long rootind = 0; for (long i=0 ; i<min(len1,len2) ; i++) { //System.out.println("arr1" + arr1[(int) i] + "arr2" + arr2[(int) i]); rootind = i; if (arr1[(int) i] != arr2[(int) i]) { break; } } if (arr1[(int) rootind] == arr2[(int) rootind]) { //System.out.println("here: " + arr1[(int) rootind]); rootind++; } for (long i=rootind ; i<len1 ; i++) { if (map.get(arr1[(int) i]) == null) { map.put(arr1[(int) i], w); } else { Long x = w + map.get(arr1[(int) i]); map.put(arr1[(int) i], x); } } //System.out.println("arr1..." + map.toString()); for (long i=rootind ; i<len2 ; i++) { if (map.get(arr2[(int) i]) == null) { map.put(arr2[(int) i], w); } else { Long x = w + map.get(arr2[(int) i]); map.put(arr2[(int) i], x); } } //System.out.println("arr2..." + map.toString()); } static long hug (Map<Long,Long> map, long v, long u) { long len1 = 0; long len2 = 0; for (long i=v ; i!=0 ; i=i/2) { len1++; } for (long i=u ; i!=0 ; i=i/2) { len2++; } long [] arr1 = new long [(int) len1]; long [] arr2 = new long [(int) len2]; for (long i=len1-1 ; i>-1 ; i--) { arr1[(int) i] = v; v /= 2; } for (long i=len2-1 ; i>-1 ; i--) { arr2[(int) i] = u; u /= 2; } long rootind = 0; for (long i=0 ; i<min(len1,len2) ; i++) { rootind = i; if (arr1[(int) i] != arr2[(int) i]) { break; } } if (arr1[(int) rootind] == arr2[(int) rootind]) { rootind++; } long total = 0; for (long i=rootind ; i<len1 ; i++) { if (map.get(arr1[(int) i]) == null) { map.put(arr1[(int) i], (long) 0); } total += map.get(arr1[(int) i]); //System.out.println(arr1[(int) i]); } for (long i=rootind ; i<len2 ; i++) { if (map.get(arr2[(int) i]) == null) { map.put(arr2[(int) i], (long) 0); } total += map.get(arr2[(int) i]); //System.out.println(arr2[(int) i]); } return total; } public static void main(String[] args) { long n = sc.nextLong(); long a,v,u,w = 0; Map <Long, Long> map = new HashMap<Long, Long>(); LinkedList<Long> hugged = new LinkedList<Long>(); for (long i=0 ; i<n ; i++) { a = sc.nextLong(); v = sc.nextLong(); u = sc.nextLong(); if (a==1) { w = sc.nextLong(); newrule(map, v, u, w); //System.out.println(map.toString()); } else { hugged.add(hug(map,v,u)); } } // Use iterator to display contents of al Iterator itr = hugged.iterator(); while(itr.hasNext()) { Object element = itr.next(); System.out.print(element + " "); } } // 1 3 3 1 //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
9be9115d78bc19c9efb7cd9cac1a8f37
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
/* * Author- Priyam Vora * BTech 2nd Year DAIICT */ import java.io.*; import java.math.*; import java.util.*; import javax.print.attribute.SetOfIntegerSyntax; public class Graph1 { private static InputStream stream; private static byte[] buf = new byte[1024]; private static int curChar; private static int numChars; private static SpaceCharFilter filter; private static PrintWriter pw; private static long count = 0,mod=1000000007; private static TreeSet<Integer>ts[]=new TreeSet[200000]; private static HashSet hs=new HashSet(); public static void main(String args[]) throws Exception { InputReader(System.in); pw = new PrintWriter(System.out); //ans(); soln(); pw.close(); } public static long gcd(long x, long y) { if (x == 0) return y; else return gcd( y % x,x); } private static int BinarySearch(int a[], int low, int high, int target) { if (low > high) return -1; int mid = low + (high - low) / 2; if (a[mid] == target) return mid; if (a[mid] > target) high = mid - 1; if (a[mid] < target) low = mid + 1; return BinarySearch(a, low, high, target); } public static String reverseString(String s) { StringBuilder sb = new StringBuilder(s); sb.reverse(); return (sb.toString()); } public static long pow(long n, long p) { if(p==0) return 1; if(p==1) return n%mod; if(p%2==0){ long temp=pow(n, p/2); return (temp*temp)%mod; }else{ long temp=pow(n,p/2); temp=(temp*temp)%mod; return(temp*n)%mod; } } public static int[] radixSort(int[] f) { int[] to = new int[f.length]; { int[] b = new int[65537]; for (int i = 0; i < f.length; i++) b[1 + (f[i] & 0xffff)]++; for (int i = 1; i <= 65536; i++) b[i] += b[i - 1]; for (int i = 0; i < f.length; i++) to[b[f[i] & 0xffff]++] = f[i]; int[] d = f; f = to; to = d; } { int[] b = new int[65537]; for (int i = 0; i < f.length; i++) b[1 + (f[i] >>> 16)]++; for (int i = 1; i <= 65536; i++) b[i] += b[i - 1]; for (int i = 0; i < f.length; i++) to[b[f[i] >>> 16]++] = f[i]; int[] d = f; f = to; to = d; } return f; } public static int nextPowerOf2(final int a) { int b = 1; while (b < a) { b = b << 1; } return b; } public static boolean PointInTriangle(int p1, int p2, int p3, int p4, int p5, int p6, int p7, int p8) { int s = p2 * p5 - p1 * p6 + (p6 - p2) * p7 + (p1 - p5) * p8; int t = p1 * p4 - p2 * p3 + (p2 - p4) * p7 + (p3 - p1) * p8; if ((s < 0) != (t < 0)) return false; int A = -p4 * p5 + p2 * (p5 - p3) + p1 * (p4 - p6) + p3 * p6; if (A < 0.0) { s = -s; t = -t; A = -A; } return s > 0 && t > 0 && (s + t) <= A; } public static float area(int x1, int y1, int x2, int y2, int x3, int y3) { return (float) Math.abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0); } public static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } //merge Sort static long sort(int a[]) { int n=a.length; int b[]=new int[n]; return mergeSort(a,b,0,n-1);} static long mergeSort(int a[],int b[],long left,long right) { long c=0;if(left<right) { long mid=left+(right-left)/2; c= mergeSort(a,b,left,mid); c+=mergeSort(a,b,mid+1,right); c+=merge(a,b,left,mid+1,right); } return c; } static long merge(int a[],int b[],long left,long mid,long right) {long c=0;int i=(int)left;int j=(int)mid; int k=(int)left; while(i<=(int)mid-1&&j<=(int)right) { if(a[i]>a[j]) {b[k++]=a[i++]; } else { b[k++]=a[j++];c+=mid-i;}} while (i <= (int)mid - 1) b[k++] = a[i++]; while (j <= (int)right) b[k++] = a[j++]; for (i=(int)left; i <= (int)right; i++) a[i] = b[i]; return c; } public static boolean isSubSequence(String large, String small, int largeLen, int smallLen) { //base cases if (largeLen == 0) return false; if (smallLen == 0) return true; // If last characters of two strings are matching if (large.charAt(largeLen - 1) == small.charAt(smallLen - 1)) isSubSequence(large, small, largeLen - 1, smallLen - 1); // If last characters are not matching return isSubSequence(large, small, largeLen - 1, smallLen); } // To Get Input // Some Buffer Methods public static void InputReader(InputStream stream1) { stream = stream1; } private static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private static boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } private static int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } private static int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private static long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } private static String nextToken() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private static String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } private static int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } private static int[][] next2dArray(int n, int m) { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = nextInt(); } } return arr; } private static char[][] nextCharArray(int n,int m){ char [][]c=new char[n][m]; for(int i=0;i<n;i++){ String s=nextLine(); for(int j=0;j<s.length();j++){ c[i][j]=s.charAt(j); } } return c; } private static long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private static void pArray(int[] arr) { for (int i = 0; i < arr.length; i++) { pw.print(arr[i] + " "); } pw.println(); return; } private static void pArray(long[] arr) { for (int i = 0; i < arr.length; i++) { pw.print(arr[i] + " "); } pw.println(); return; } private static void pArray(boolean[] arr) { for (int i = 0; i < arr.length; i++) { pw.print(arr[i] + " "); } pw.println(); return; } private static boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } //----------------------------------------My Code------------------------------------------------// private static void soln() { HashMap<String,Long> hm=new HashMap<>(); int q=nextInt(); while(q-->0){ int op=nextInt(); if(op==1){ long u=nextLong(); long v=nextLong(); long w=nextLong(); while(u!=v){ if(u>v){ String temp=""; temp+=Long.toString(u); temp+=" "; temp+=Long.toString(u/2); if(!hm.containsKey(temp)){ hm.put(temp, w); }else{ hm.replace(temp, hm.get(temp)+w); } u=u/2; }else{ String temp=""; temp+=Long.toString(v); temp+=" "; temp+=Long.toString(v/2); if(!hm.containsKey(temp)){ hm.put(temp, w); }else{ hm.replace(temp, hm.get(temp)+w); } v=v/2; } } } else{ long u=nextLong(); long v=nextLong(); long cost=0; while(u!=v){ if(u>v){ String temp=""; temp+=Long.toString(u); temp+=" "; temp+=Long.toString(u/2); if(hm.containsKey(temp)) cost+=hm.get(temp); u=u/2; }else { String temp=""; temp+=Long.toString(v); temp+=" "; temp+=Long.toString(v/2); if(hm.containsKey(temp)) cost+=hm.get(temp); v=v/2; } } pw.println(cost); } //-----------------------------------------The End--------------------------------------------------------------------------// } } } class Pair implements Comparable<Pair>{ String idx; int val; Pair(String idx,int val){ this.idx=idx; this.val=val; } @Override public int compareTo(Pair o) { // TODO Auto-generated method stub // Sort in increasing order if(o.val>val) return 1; return -1; } } class Graph{ private int V,level[][],count=-1,lev_dfs[],degree=0,no_vert_conn_comp=0; private Stack <Integer>st=new Stack(); private LinkedList<Integer > adj[]; private boolean[][] Visite; private boolean [] Visited; private static TreeSet<Integer> ts=new TreeSet(); Graph(int V){ V++; this.V=(V); adj=new LinkedList[V]; Visite=new boolean[100][100]; Visited=new boolean[V]; level=new int[100][100]; lev_dfs=new int[V]; for(int i=0;i<V;i++) adj[i]=new LinkedList<Integer>(); } void addEdge(int v,int w){ if(adj[v]==null){ adj[v]=new LinkedList(); } adj[v].add(w); } public int getEd(){ return degree/2; } public void get(int from,int to){ int h=lev_dfs[from]-lev_dfs[to]; if(h<=0){ System.out.println(-1); }else{ System.out.println(h-1); } } private static boolean check(int x,int y,char c[][]){ if((x>=0 && y>=0) && (x<c.length && y<c[0].length) && c[x][y]!='#'){ return true; } return false; } public int BFS(int x,int y,int k,char[][] c) { LinkedList<Pair> queue = new LinkedList<Pair>(); //Visited[s]=true; // queue.add(new Pair(x,y)); int count=0; level[x][y]=-1; c[x][y]='M'; while (!queue.isEmpty()) { Pair temp = queue.poll(); //x=temp.idx; //y=temp.val; c[x][y]='M'; // System.out.println(x+" "+y+" ---"+count); count++; if(count==k) { for(int i=0;i<c.length;i++){ for(int j=0;j<c[0].length;j++){ if(c[i][j]=='M'){ System.out.print("."); } else if(c[i][j]=='.') System.out.print("X"); else System.out.print(c[i][j]); } System.out.println(); } System.exit(0); } // System.out.println(x+" "+y); // V--; } return V; } private void getAns(int startVertex){ for(int i=0;i<adj[startVertex].size();i++){ int ch=adj[startVertex].get(i); for(int j=0;j<adj[ch].size();j++){ int ch2=adj[ch].get(j); if(adj[ch2].contains(startVertex)){ System.out.println(startVertex+" "+ch+" "+ch2); System.exit(0); } } } } public long dfs(int startVertex){ // getAns(startVertex); if(!Visited[startVertex]) { return dfsUtil(startVertex,Visited); //return getAns(); } return 0; } private int dfsUtil(int startVertex, boolean[] Visited) {//0-Blue 1-Pink int c=1; degree=0; Visited[startVertex]=true; lev_dfs[startVertex]=1; st.push(startVertex); while(!st.isEmpty()){ int top=st.pop(); ts.add(top); Iterator<Integer> i=adj[top].listIterator(); degree+=adj[top].size(); while(i.hasNext()){ // System.out.println(top); int n=i.next(); if( !Visited[n]){ Visited[n]=true; st.push(n); c++; lev_dfs[n]=lev_dfs[top]+1; } } } // System.out.println("NO"); return c; } } class Dsu{ private int rank[], parent[] ,n; Dsu(int size){ this.n=size+1; rank=new int[n]; parent=new int[n]; makeSet(); } void makeSet(){ for(int i=0;i<n;i++){ parent[i]=i; } } int find(int x){ if(parent[x]!=x){ parent[x]=find(parent[x]); } return parent[x]; } void union(int x,int y){ int xRoot=find(x); int yRoot=find(y); if(xRoot==yRoot) return; if(rank[xRoot]<rank[yRoot]){ parent[xRoot]=yRoot; }else if(rank[yRoot]<rank[xRoot]){ parent[yRoot]=xRoot; }else{ parent[yRoot]=xRoot; rank[xRoot]++; } } } class Heap{ public static void build_max_heap(long []a,int size){ for(int i=size/2;i>0;i--){ max_heapify(a, i,size); } } private static void max_heapify(long[] a,int i,int size){ int left_child=2*i; int right_child=(2*i+1); int largest=0; if(left_child<size && a[left_child]>a[i]){ largest=left_child; }else{ largest=i; } if(right_child<size && a[right_child]>a[largest]){ largest=right_child; } if(largest!=i){ long temp=a[largest]; a[largest]=a[i]; a[i]=temp; max_heapify(a, largest,size); } } private static void min_heapify(int[] a,int i){ int left_child=2*i; int right_child=(2*i+1); int largest=0; if(left_child<a.length && a[left_child]<a[i]){ largest=left_child; }else{ largest=i; } if(right_child<a.length && a[right_child]<a[largest]){ largest=right_child; } if(largest!=i){ int temp=a[largest]; a[largest]=a[i]; a[i]=temp; min_heapify(a, largest); } } public static void extract_max(int size,long a[]){ if(a.length>1){ long max=a[1]; a[1]=a[a.length-1]; size--; max_heapify(a, 1,a.length-1); } } } class MyComp implements Comparator<Long>{ @Override public int compare(Long o1, Long o2) { if(o1<o2){ return 1; }else if(o1>o2){ return -1; } return 0; } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
0d8201677d1a0bf37f40969581c6d9e4
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.lang.*; import java.util.*; public class Main { static HashMap<Long, Node> graph = new HashMap<>(); public static void main(String[] args) { Scanner sc = new Scanner(System.in); long q = Long.parseLong(sc.nextLine()); for(long i=0;i<q;i++){ String[] line = sc.nextLine().split(" "); if(line[0].equals("1")){ addMoney(line); } else if(line[0].equals("2")){ prlongPrice(line); } } } private static void prlongPrice(String[] line) { long from = Long.parseLong(line[1]); long to = Long.parseLong(line[2]); long price = calcPrice(from, to); System.out.println(price); } private static long calcPrice(long from, long to) { long min = Math.min(from, to); long max = Math.max(from, to); long res = 0; while (min!=max){ long parent = max/2; boolean isLeft = max==parent*2; res += addRes(parent, isLeft); max = Math.max(min, parent); min = Math.min(min, parent); } return res; } private static long addRes(long parent, boolean isLeft) { if(graph.containsKey(parent)){ Node node = graph.get(parent); return isLeft?node.left:node.rigt; } return 0; } private static void addMoney(String[] line) { long from = Long.parseLong(line[1]); long to = Long.parseLong(line[2]); long money = Long.parseLong(line[3]); addMoney(from, to, money); } private static void addMoney(long from, long to, long money) { long min = Math.min(from, to); long max = Math.max(from, to); while (min!=max){ long parent = max/2; boolean isLeft = max==parent*2; addVal(parent, isLeft, money); max = Math.max(min, parent); min = Math.min(min, parent); } } private static void addVal(long parent, boolean isLeft, long money) { if(!graph.containsKey(parent)){ graph.put(parent, new Node()); } if(isLeft) graph.get(parent).left += money; else graph.get(parent).rigt += money; } static class Node{ public long left = 0; public long rigt = 0; } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
416dc38f3d5f9d0a30afddfdd87ced8c
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
//package CF; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.TreeMap; public class A { static int INF = (int) 1e9 + 7; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int q = sc.nextInt(); mp = new TreeMap<>(); mp.put(1L, 0); idx = 1; Query[] que = new Query[q]; for (int i = 0; i < que.length; i++) { int t = sc.nextInt(); long u = sc.nextLong(), v = sc.nextLong(); int w = 0; if (t == 1) { w = sc.nextInt(); } addPar(u); addPar(v); que[i] = new Query(t, u, v, w); } adj = new TreeMap[idx]; for (int i = 0; i < adj.length; i++) { adj[i] = new TreeMap<Integer, Long>(); } for (int i = 0; i < que.length; i++) { long t = trav(que[i].u, que[i].v, que[i].w, que[i].t); if (que[i].t == 2) out.println(t); } out.flush(); out.close(); } static int idx; static TreeMap[] adj; static TreeMap<Long, Integer> mp; static void addPar(long u) { while (u > 1) { if (!mp.containsKey(u)) mp.put(u, idx++); else break; u >>= 1; } } static long trav(long u, long v, long w, int t) { long ans = 0; int lenU = 0, lenV = 0; long tmp = u; while(tmp > 0) { tmp >>=1; lenU++; } tmp = v; while(tmp > 0) { tmp >>=1; lenV++; } while (u > 1 && lenU > lenV) { int a = mp.get(u >> 1), b = mp.get(u); long wt = (long)adj[a].getOrDefault(b, 0L); if (t == 1) { adj[a].put(b, wt+w); } else { ans += wt; } u >>= 1; lenU--; } while (v > 1 && lenV > lenU) { int a = mp.get(v >> 1), b = mp.get(v); long wt = (long)adj[a].getOrDefault(b, 0L); if (t == 1) { adj[a].put(b, wt+w); } else { ans += wt; } v >>= 1; lenV--; } while (u > 1 && v > 1 && u != v) { int a = mp.get(u>>1), b = mp.get(u); long wt = (long)adj[a].getOrDefault(b, 0L); if (t == 1) { adj[a].put(b, wt+w); } else { ans += wt; } a = mp.get(v>>1); b = mp.get(v); wt = (long)adj[a].getOrDefault(b, 0L); if (t == 1) { adj[a].put(b, wt+w); } else { ans += wt; } u >>= 1; v >>= 1; } return ans; } static class Query { int t, w; long u, v; public Query(int t, long u, long v, int w) { this.t = t; this.u = u; this.v = v; this.w = w; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader fileReader) { br = new BufferedReader(fileReader); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
7e87288202d16a6f4c0ed6cb24192b36
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
//package round362; import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub BufferedReader sc = new BufferedReader(new InputStreamReader(System.in)); long two[] = new long[100]; two[0]=1; for(int i=1;i<100;i++) { two[i] = two[i-1]*2; } PrintWriter w = new PrintWriter(System.out); String s = sc.readLine(); int q = Integer.parseInt(s); HashMap<Long,Long> hm = new HashMap(); for(int i=0;i<q;i++) { String ss[] = sc.readLine().split(" "); if(ss.length==3) { long x = Long.parseLong(ss[1]); long y = Long.parseLong(ss[2]); long xx = 0,yy=0; long right = two[0],left = 0; boolean flag1=true,flag2=true; for(int j=0;j<100;j++) { if(flag1==true && x>=left && x<=right) { xx = j; flag1=false; } if(flag2==true && y>=left && y<=right) { yy=j; flag2=false; } if(!flag1 && !flag2) { break; } left = right; right+=two[j+1]; } long ans = 0; while(xx>yy) { if(hm.containsKey(x)) ans+=hm.get(x); x/=2; xx--; } while(yy>xx) { if(hm.containsKey(y)) ans+=(hm.get(y)); y/=2; yy--; } while(x!=y) { if(hm.containsKey(x)) ans+=(hm.get(x)); x/=2; if(hm.containsKey(y)) ans+=(hm.get(y)); y/=2; } w.println(ans); } else { long x= Long.parseLong(ss[1]); long y = Long.parseLong(ss[2]); long co = Long.parseLong(ss[3]); long xx = 0,yy=0; long right = two[0],left = 0; boolean flag1=true,flag2=true; for(int j=0;j<100;j++) { if(flag1==true && x>=left && x<=right) { xx = j; flag1=false; } if(flag2==true && y>=left && y<=right) { yy=j; flag2=false; } if(!flag1 && !flag2) { break; } left = right; right+=two[j+1]; } while(xx>yy) { if(hm.containsKey(x)) { hm.put(x, hm.get(x)+co); } else { hm.put(x,co); } xx--; x/=2; } while(yy>xx) { if(hm.containsKey(y)) { hm.put(y,hm.get(y)+co); } else { hm.put(y,co); } y/=2; yy--; } while(x!=y) { if(hm.containsKey(x)) { hm.put(x,hm.get(x)+co); } else { hm.put(x,co); } x/=2; if(hm.containsKey(y)) { hm.put(y, hm.get(y)+co); } else { hm.put(y, co); } y/=2; } } } w.close(); } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
db2f0d6defd48f6866f300eb6fa61ce9
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.NoSuchElementException; import java.util.TreeSet; public class C { private static class Task { long[] LCA(long v, long u) { TreeSet<Long> set = new TreeSet<>(); set.add(v); set.add(u); while (v > 0 || u > 0) { if (v < u) { u /= 2; if (set.contains(u)) break; set.add(u); } else { v /= 2; if (set.contains(v)) break; set.add(v); } } if (set.contains(0L)) set.remove(0L); long[] ret = new long[set.size()]; int k = 0; for (long s : set) ret[k++] = s; return ret; } void solve(FastScanner in, PrintWriter out) { int Q = in.nextInt(); ArrayList<long[]> lcaList = new ArrayList<>(); ArrayList<Integer> w = new ArrayList<>(); for (; Q > 0; Q--) { int t = in.nextInt(); if (t == 1) { lcaList.add(LCA(in.nextLong(), in.nextLong())); w.add(in.nextInt()); } else { long ans = 0L; long u = in.nextLong(); long v = in.nextLong(); long[] path = LCA(v, u); int i = 0; for (long[] lca : lcaList) { long cnt = 0; int p = 0, l = 0; while (p < path.length && l < lca.length) { if (path[p] == lca[l]) { cnt++; p++; l++; } else { if (path[p] > lca[l]) l++; else if (path[p] < lca[l]) p++; } } if (cnt > 0) ans += (cnt - 1) * w.get(i); i++; } out.println(ans); } } } } // Template public static void main(String[] args) { OutputStream outputStream = System.out; FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } private static class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int bufferLength = 0; private boolean hasNextByte() { if (ptr < bufferLength) { return true; } else { ptr = 0; try { bufferLength = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (bufferLength <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } private void skipUnprintable() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; } boolean hasNext() { skipUnprintable(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } double nextDouble() { return Double.parseDouble(next()); } double[] nextDoubleArray(int n) { double[] array = new double[n]; for (int i = 0; i < n; i++) { array[i] = nextDouble(); } return array; } double[][] nextDoubleMap(int n, int m) { double[][] map = new double[n][]; for (int i = 0; i < n; i++) { map[i] = nextDoubleArray(m); } return map; } public int nextInt() { return (int) nextLong(); } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) { array[i] = nextInt(); } return array; } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
c444e189e9c4a115ec78ed71d49ec28a
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.NoSuchElementException; import java.util.TreeMap; /* _ooOoo_ o8888888o 88" . "88 (| -_- |) O\ = /O ____/`---'\____ .' \\| |// `. / \\||| : |||// \ / _||||| -:- |||||- \ | | \\\ - /// | | | \_| ''\---/'' | | \ .-\__ `-` ___/-. / ___`. .' /--.--\ `. . __ ."" '< `.___\_<|>_/___.' >'"". | | : `- \`.;`\ _ /`;.`/ - ` : | | \ \ `-. \_ __\ /__ _/ .-` / / ======`-.____`-.___\_____/___.-`____.-'====== `=---=' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ pass System Test! */ public class C { private static class Task { class Pair implements Comparable<Pair> { long from, to; Pair(long from, long to) { this.from = from; this.to = to; } @Override public int compareTo(Pair o) { if (this.from == o.from) return Long.signum(this.to - o.to); return Long.signum(this.from - o.from); } } void solve(FastScanner in, PrintWriter out) { TreeMap<Pair, Long> weights = new TreeMap<>(); int Q = in.nextInt(); for (; Q > 0; Q--) { int type = in.nextInt(); if (type == 1) { long u = in.nextLong(); long v = in.nextLong(); long w = in.nextLong(); while (u != v) { Pair pair; if (u > v) { long p = u / 2; pair = new Pair(p, u); u = p; } else { long p = v / 2; pair = new Pair(p, v); v = p; } Long cost = weights.get(pair); if (cost == null) weights.put(pair, w); else weights.put(pair, w + cost); } } else { long u = in.nextLong(); long v = in.nextLong(); long ans = 0; while (u != v) { Pair pair; if (u > v) { long p = u / 2; pair = new Pair(p, u); u = p; } else { long p = v / 2; pair = new Pair(p, v); v = p; } Long cost = weights.get(pair); if (cost != null) ans += cost; } out.println(ans); } } } } /** * γ“γ“γ‹γ‚‰δΈ‹γ―γƒ†γƒ³γƒ—γƒ¬γƒΌγƒˆγ§γ™γ€‚ */ public static void main(String[] args) { OutputStream outputStream = System.out; FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } private static class FastScanner { private final InputStream in = System.in; private final byte[] buffer = new byte[1024]; private int ptr = 0; private int bufferLength = 0; private boolean hasNextByte() { if (ptr < bufferLength) { return true; } else { ptr = 0; try { bufferLength = in.read(buffer); } catch (IOException e) { e.printStackTrace(); } if (bufferLength <= 0) { return false; } } return true; } private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1; } private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126; } private void skipUnprintable() { while (hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; } boolean hasNext() { skipUnprintable(); return hasNextByte(); } public String next() { if (!hasNext()) throw new NoSuchElementException(); StringBuilder sb = new StringBuilder(); int b = readByte(); while (isPrintableChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } long nextLong() { if (!hasNext()) throw new NoSuchElementException(); long n = 0; boolean minus = false; int b = readByte(); if (b == '-') { minus = true; b = readByte(); } if (b < '0' || '9' < b) { throw new NumberFormatException(); } while (true) { if ('0' <= b && b <= '9') { n *= 10; n += b - '0'; } else if (b == -1 || !isPrintableChar(b)) { return minus ? -n : n; } else { throw new NumberFormatException(); } b = readByte(); } } double nextDouble() { return Double.parseDouble(next()); } double[] nextDoubleArray(int n) { double[] array = new double[n]; for (int i = 0; i < n; i++) { array[i] = nextDouble(); } return array; } double[][] nextDoubleMap(int n, int m) { double[][] map = new double[n][]; for (int i = 0; i < n; i++) { map[i] = nextDoubleArray(m); } return map; } public int nextInt() { return (int) nextLong(); } public int[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; i++) array[i] = nextInt(); return array; } public long[] nextLongArray(int n) { long[] array = new long[n]; for (int i = 0; i < n; i++) array[i] = nextLong(); return array; } public String[] nextStringArray(int n) { String[] array = new String[n]; for (int i = 0; i < n; i++) array[i] = next(); return array; } public char[][] nextCharMap(int n) { char[][] array = new char[n][]; for (int i = 0; i < n; i++) array[i] = next().toCharArray(); return array; } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
2bce7869b17aed6d60fe33c0824d46c0
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.*; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Double.parseDouble; import static java.lang.String.*; public class Main { static Map<Long,Long> cost; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //(new FileReader("input.in")); StringBuilder out = new StringBuilder(); StringTokenizer tk; cost = new HashMap<>(); int q = parseInt(in.readLine()); while(q-- > 0) { tk = new StringTokenizer(in.readLine()); long t = parseLong(tk.nextToken()),a = parseLong(tk.nextToken()),b = parseLong(tk.nextToken()); if(t==1) { long c = parseLong(tk.nextToken()); long l = LCA(a,b); while(a != l) { if(cost.containsKey(a)) cost.put(a, cost.get(a)+c); else cost.put(a, c); a /= 2; } while(b != l) { if(cost.containsKey(b)) cost.put(b, cost.get(b)+c); else cost.put(b, c); b /= 2; } } else { long ans = 0; long l = LCA(a,b); while(a != l) { if(cost.containsKey(a)) ans += cost.get(a); a /= 2; } while(b != l) { if(cost.containsKey(b)) ans += cost.get(b); b /= 2; } out.append(ans).append("\n"); } } System.out.print(out); } static long LCA(long a,long b) { while(log2(a)!=log2(b)) { long na = a/2l,nb = b/2l,la = log2(na),lb = log2(nb); if(la > lb) a = na; else b = nb; } while(a!=b) { if(a!=1) a /= 2; if(b!=1) b /= 2; } return a; } static long log2(long x) { return (long)(log(x)/log(2)); } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
adc916402f567d858bcd23b4e42031bd
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; /** * @author Don Li */ public class LorenzoVonMatterhorn { void solve() { int q = in.nextInt(); Map<Long, Long> map = new HashMap<>(); while (q-- > 0) { int t = in.nextInt(); long u = in.nextLong(), v = in.nextLong(); long p = lca(u, v); if (t == 1) { long w = in.nextLong(); while (u != p) { map.put(u, map.getOrDefault(u, 0L) + w); u /= 2; } while (v != p) { map.put(v, map.getOrDefault(v, 0L) + w); v /= 2; } } else { long res = 0; while (u != p) { res += map.getOrDefault(u, 0L); u /= 2; } while (v != p) { res += map.getOrDefault(v, 0L); v /= 2; } out.println(res); } } } long lca(long u, long v) { int du = depth(u), dv = depth(v); if (du > dv) { for (int i = 0; i < du - dv; i++) u /= 2; } else if (du < dv) { for (int i = 0; i < dv - du; i++) v /= 2; } while (u != v) { u /= 2; v /= 2; } return u; } int depth(long n) { int x = 1; while (n >= (1L << x)) x++; return x; } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new LorenzoVonMatterhorn().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
c85c55c2a2386c8e2ad343e0ae8c51f1
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.util.HashMap; public class Main { static HashMap<Long ,Long> weights = new HashMap(); static long findLCA(long v, long u){ int du,dv; while(u!=v){ //System.out.println("u "+u+" v "+v); du = (int)(Math.log(u)/Math.log(2)); dv = (int)(Math.log(v)/Math.log(2)); //System.out.println(du+" "+dv); if(dv<du){ long t = v; v = u; u = t; } v = v/2; } return u; } public static void main(String args[]) throws IOException{ InputReader ir = new InputReader(); int q = ir.readInt(); long u,v,w,l,t; long ans; while(q-->0){ if(ir.readInt()==1){ v = ir.readLong(); u = ir.readLong(); w = ir.readLong(); l = findLCA(v,u); //System.out.println("LCA is "+l); while(v!=l){ //System.out.println("V "+v); if(!weights.containsKey(v)){ weights.put(v,0l); } weights.put(v, weights.get(v)+w); v/=2; } while(u!=l){ if(!weights.containsKey(u)){ weights.put(u,0l); } weights.put(u, weights.get(u)+w); u/=2; } } else{ v = ir.readLong(); u = ir.readLong(); l = findLCA(v,u); ans = 0; while(v!=l){ if(!weights.containsKey(v)){ weights.put(v,0l); } ans = ans+weights.get(v); v/=2; } while(u!=l){ if(!weights.containsKey(u)){ weights.put(u,0l); } ans = ans+weights.get(u); u/=2; } System.out.println(ans); } } } final static class InputReader { byte[] buffer = new byte[8192]; int offset = 0; int bufferSize = 0; final InputStream in = System.in; public int readInt() throws IOException { int number = 0; int s = 1; if (offset == bufferSize) { offset = 0; bufferSize = in.read(buffer); } if (bufferSize == -1) throw new IOException("No new bytes"); for (; buffer[offset] < 0x30 || buffer[offset] == '-'; ++offset) { if (buffer[offset] == '-') s = -1; if (offset == bufferSize - 1) { offset = -1; bufferSize = in.read(buffer); } } for (; offset < bufferSize && buffer[offset] > 0x2f; ++offset) { number = (number << 3) + (number << 1) + buffer[offset] - 0x30; if (offset == bufferSize - 1) { offset = -1; bufferSize = in.read(buffer); } } ++offset; return number * s; } public int[] readIntArray(int n) throws IOException { int[] ar = new int[n]; for (int i = 0; i < n; i++) ar[i] = readInt(); return ar; } public long readLong() throws IOException { long res = 0; int s = 1; if (offset == bufferSize) { offset = 0; bufferSize = in.read(buffer); } for (; buffer[offset] < 0x30 || buffer[offset] == '-'; ++offset) { if (buffer[offset] == '-') s = -1; if (offset == bufferSize - 1) { offset = -1; bufferSize = in.read(buffer); } } for (; offset < bufferSize && buffer[offset] > 0x2f; ++offset) { res = (res << 3) + (res << 1) + buffer[offset] - 0x30; if (offset == bufferSize - 1) { offset = -1; bufferSize = in.read(buffer); } } ++offset; if (s == -1) res = -res; return res; } public long[] readLongArray(int n) throws IOException { long[] ar = new long[n]; for (int i = 0; i < n; i++) ar[i] = readLong(); return ar; } public String read() throws IOException { StringBuilder sb = new StringBuilder(); if (offset == bufferSize) { offset = 0; bufferSize = in.read(buffer); } if (bufferSize == -1 || bufferSize == 0) throw new IOException("No new bytes"); for (; buffer[offset] == ' ' || buffer[offset] == '\t' || buffer[offset] == '\n' || buffer[offset] == '\r'; ++offset) { if (offset == bufferSize - 1) { offset = -1; bufferSize = in.read(buffer); } } for (; offset < bufferSize; ++offset) { if (buffer[offset] == ' ' || buffer[offset] == '\t' || buffer[offset] == '\n' || buffer[offset] == '\r') break; if (Character.isValidCodePoint(buffer[offset])) { sb.appendCodePoint(buffer[offset]); } if (offset == bufferSize - 1) { offset = -1; bufferSize = in.read(buffer); } } return sb.toString(); } public String read(int n) throws IOException { StringBuilder sb = new StringBuilder(n); if (offset == bufferSize) { offset = 0; bufferSize = in.read(buffer); } if (bufferSize == -1 || bufferSize == 0) throw new IOException("No new bytes"); for (; buffer[offset] == ' ' || buffer[offset] == '\t' || buffer[offset] == '\n' || buffer[offset] == '\r'; ++offset) { if (offset == bufferSize - 1) { offset = -1; bufferSize = in.read(buffer); } } for (int i = 0; offset < bufferSize && i < n; ++offset) { if (buffer[offset] == ' ' || buffer[offset] == '\t' || buffer[offset] == '\n' || buffer[offset] == '\r') break; if (Character.isValidCodePoint(buffer[offset])) { sb.appendCodePoint(buffer[offset]); } if (offset == bufferSize - 1) { offset = -1; bufferSize = in.read(buffer); } } return sb.toString(); } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
cedd5376a34efe43533a3e93cd8d9763
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
/** * * @author meashish */ import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.Serializable; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.InputMismatchException; import java.util.Set; public class Main { InputReader in; Printer out; long MOD = 1000000007; private void start() throws Exception { int t = in.nextInt(); HashMap<Long, HashMap<Long, Long>> map = new HashMap<>(); while (t-- > 0) { int tmp = in.nextInt(); if (tmp == 1) { long u = in.nextLong(); long v = in.nextLong(); long w = in.nextLong(); long levelu = getLevel(u); long levelv = getLevel(v); long curu = u; while (levelu > levelv) { increment(curu, curu / 2, w, map); curu /= 2; levelu--; } long curv = v; while (levelv > levelu) { increment(curv, curv / 2, w, map); curv /= 2; levelv--; } while (curu != curv) { increment(curu, curu / 2, w, map); increment(curv, curv / 2, w, map); curu /= 2; curv /= 2; } } else { long u = in.nextLong(); long v = in.nextLong(); long levelu = getLevel(u); long levelv = getLevel(v); long curu = u; long res = 0; while (levelu > levelv) { res += getVal(curu, curu / 2, map); curu /= 2; levelu--; } long curv = v; while (levelv > levelu) { res += getVal(curv, curv / 2, map); curv /= 2; levelv--; } while (curu != curv) { res += getVal(curu, curu / 2, map); res += getVal(curv, curv / 2, map); curu /= 2; curv /= 2; } out.println(res); } } } long getLevel(long val) { return 63L - Long.numberOfLeadingZeros(val); } long getVal(long start, long end, HashMap<Long, HashMap<Long, Long>> map) { if (map.containsKey(start) && map.get(start).containsKey(end)) { return map.get(start).get(end); } return 0; } void increment(long start, long end, long w, HashMap<Long, HashMap<Long, Long>> map) { increment2(start, end, w, map); increment2(end, start, w, map); } void increment2(long start, long end, long w, HashMap<Long, HashMap<Long, Long>> map) { if (!map.containsKey(start)) { map.put(start, new HashMap<>()); } long ini = map.get(start).getOrDefault(end, 0L); map.get(start).put(end, ini + w); } class Bipartite { int m, n; boolean[][] graph; boolean seen[]; int matchL[]; //What left vertex i is matched to (or -1 if unmatched) int matchR[]; //What right vertex j is matched to (or -1 if unmatched) public Bipartite(boolean[][] graph) { this.graph = graph; n = graph.length; m = graph[0].length; matchL = new int[m]; matchR = new int[n]; seen = new boolean[n]; } int maximumMatching() { //Read input and populate graph[][] //Set m to be the size of L, n to be the size of R Arrays.fill(matchL, -1); Arrays.fill(matchR, -1); int count = 0; for (int i = 0; i < m; i++) { Arrays.fill(seen, false); if (bpm(i)) { count++; } } return count; } boolean bpm(int u) { //try to match with all vertices on right side for (int v = 0; v < n; v++) { if (!graph[u][v] || seen[v]) { continue; } seen[v] = true; //match u and v, if v is unassigned, or if v's match on the left side can be reassigned to another right vertex if (matchR[v] == -1 || bpm(matchR[v])) { matchL[u] = v; matchR[v] = u; return true; } } return false; } } long power(long x, long n) { if (n <= 0) { return 1; } long y = power(x, n / 2); if ((n & 1) == 1) { return (((y * y) % MOD) * x) % MOD; } return (y * y) % MOD; } public long gcd(long a, long b) { a = Math.abs(a); b = Math.abs(b); return BigInteger.valueOf(a).gcd(BigInteger.valueOf(b)).longValue(); } public Integer[] input(int n) { Integer a[] = new Integer[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } return a; } public static void main(String[] args) throws Exception { InputReader in; PrintStream out; in = new InputReader(System.in); out = System.out; Main main = new Main(); main.in = in; main.out = new Printer(out); // main.out.autoFlush = true; main.start(); main.out.flush(); } private static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int 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 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 double nextDouble() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') { return res * Math.pow(10, nextInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public 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 boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return nextString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } private static class Printer { PrintStream out; StringBuilder buffer = new StringBuilder(); boolean autoFlush; public Printer(PrintStream out) { this.out = out; } public Printer(PrintStream out, boolean autoFlush) { this.out = out; this.autoFlush = autoFlush; } public void println() { buffer.append("\n"); if (autoFlush) { flush(); } } public void println(int n) { println(Integer.toString(n)); } public void println(long n) { println(Long.toString(n)); } public void println(double n) { println(Double.toString(n)); } public void println(float n) { println(Float.toString(n)); } public void println(boolean n) { println(Boolean.toString(n)); } public void println(char n) { println(Character.toString(n)); } public void println(byte n) { println(Byte.toString(n)); } public void println(short n) { println(Short.toString(n)); } public void println(Object o) { println(o.toString()); } public void println(Object[] o) { println(Arrays.deepToString(o)); } public void println(String s) { buffer.append(s).append("\n"); if (autoFlush) { flush(); } } public void print(char s) { buffer.append(s); if (autoFlush) { flush(); } } public void print(String s) { buffer.append(s); if (autoFlush) { flush(); } } public void flush() { try { BufferedWriter log = new BufferedWriter(new OutputStreamWriter(out)); log.write(buffer.toString()); log.flush(); buffer = new StringBuilder(); } catch (Exception e) { e.printStackTrace(); } } } private class Pair<T, U> implements Serializable { int indexOfSec; private T key; public T getKey() { return key; } private U value; public U getValue() { return value; } public Pair(T key, U value) { this.key = key; this.value = value; } @Override public String toString() { return key + "=" + value; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Pair other = (Pair) obj; if (!this.key.equals(other.key)) { return false; } return this.value.equals(other.value); } @Override public int hashCode() { return key.hashCode() + 13 * value.hashCode(); } } private class PairSet<T, S> { HashMap<T, HashSet<S>> map = new HashMap<>(); public void add(T a, S b) { if (map.containsKey(a)) { map.get(a).add(b); } HashSet<S> set = new HashSet<>(); set.add(b); map.put(a, set); } public boolean contains(T a, S b) { if (map.containsKey(a)) { return map.get(a).contains(b); } return false; } } private class Bit { int N; long ft1[], ft2[]; Bit(int n) { N = n; ft1 = new long[N + 1]; ft2 = new long[N + 1]; } void update(long ft[], int p, long v) { for (; p <= N; p += p & (-p)) { ft[p] += v; // ft[p] %= MOD; } } void update(int a, int b, long v) { update(ft1, a, v); update(ft1, b + 1, -v); update(ft2, a, v * (a - 1)); update(ft2, b + 1, -v * b); } long query(long ft[], int b) { long sum = 0; for (; b > 0; b -= b & (-b)) { sum += ft[b]; // sum %= MOD; } return sum; } long query(int b) { return query(ft1, b) * b - query(ft2, b); } long query(int a, int b) { return query(b) - query(a - 1); } } public static Set<Integer[]> getPermutationsRecursive(Integer[] num) { if (num == null) { return null; } Set<Integer[]> perms = new HashSet<>(); //base case if (num.length == 0) { perms.add(new Integer[0]); return perms; } //shave off first int then get sub perms on remaining ints. //...then insert the first into each position of each sub perm..recurse int first = num[0]; Integer[] remainder = Arrays.copyOfRange(num, 1, num.length); Set<Integer[]> subPerms = getPermutationsRecursive(remainder); for (Integer[] subPerm : subPerms) { for (int i = 0; i <= subPerm.length; ++i) { // '<=' IMPORTANT !!! Integer[] newPerm = Arrays.copyOf(subPerm, subPerm.length + 1); for (int j = newPerm.length - 1; j > i; --j) { newPerm[j] = newPerm[j - 1]; } newPerm[i] = first; perms.add(newPerm); } } return perms; } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
89562bedb81cb853f3112a622b558025
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
//package com.codeforces.competitions.year2016.julytoseptember.round362div2; import java.io.*; import java.util.*; public final class TaskC { public static void main(String[] args) { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); Solver solver = new Solver(in, out); solver.solve(1); out.flush(); in.close(); out.close(); } static class Solver { int q; Map<Edge, Long> map; InputReader in; OutputWriter out; public Solver(InputReader in, OutputWriter out) { this.in = in; this.out = out; } void solve(int testNumber) { q = in.nextInt(); map = new HashMap<>(); /* Edge[] edges = new Edge[10]; for (int i = 0; i < 10; i++) edges[i] = new Edge(i + 1, (i + 1) * 10, (i + 1) * 100); System.out.println("hashCodes : "); for (int i = 0; i < 10; i++) System.out.println("i : " + (i + 1) + ", hC[i] : " + edges[i].hashCode());*/ for (int i = 0; i < q; i++) { int type; long from, to; type = in.nextInt(); from = in.nextLong(); to = in.nextLong(); if (type == 1) { long weight = in.nextLong(); int count = 0; while (true) { while (from > to) { long temp = from >> 1; Edge e = new Edge(from, temp); Long prevWeight = map.get(e); if (prevWeight == null) { map.put(e, weight); // System.out.println("putting new edge : (" + from + ", " + temp + "), wt. : " + weight); } else { map.put(e, prevWeight + weight); // System.out.println("updating edge : (" + from + ", " + temp + "), wt. : " + // prevWeight + weight); } count++; from = temp; } if (from == to) { break; } while (to > from) { long temp = to >> 1; Edge e = new Edge(to, temp); Long prevWeight = map.get(e); if (prevWeight == null) { map.put(e, weight); // System.out.println("**putting new edge : (" + to + ", " + temp + "), wt. : " + weight); } else { map.put(e, prevWeight + weight); // System.out.println("**updating edge : (" + to + ", " + temp + "), wt. : " + // prevWeight + weight); } // count++; to = temp; } if (from == to) break; } // System.out.println("\t\t&&&& total edges : " + count); } else { long answer = 0; int count = 0; while (true) { while (from > to) { long temp = from >> 1; Edge e = new Edge(from, temp); Long weight = map.get(e); if (weight != null) { answer += weight; // System.out.println("\t^^^^ adding " + weight); } // else // System.out.println("\t\t\t$$$$ edge not found : (" + from + ", " + temp + ")"); count++; from = temp; } if (from == to) break; while (to > from) { long temp = to >> 1; Edge e = new Edge(to, temp); Long weight = map.get(e); if (weight != null) { answer += weight; // System.out.println("\t%%%% adding " + weight); } // else // System.out.println("\t\t\t!!!! edge not found : (" + to + ", " + temp + ")"); // count++; to = temp; } if (from == to) break; } // System.out.println("\t\t@@@@ total edges in answer : " + count); out.println(answer); } } } class Edge { long from, to; public Edge(long from, long to) { this.from = from; this.to = to; } @Override public int hashCode() { return Objects.hash(from, to); } @Override public boolean equals(Object obj) { Edge temp = (Edge) obj; return from == temp.from && to == temp.to; } /* @Override public int compareTo(Edge o) { if (from == o.from && to == o.to) return 0; return Long.compare(to, o.to); }*/ } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c & 15; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int arraySize) { int array[] = new int[arraySize]; for (int i = 0; i < arraySize; i++) array[i] = nextInt(); return array; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sign = 1; if (c == '-') { sign = -1; c = read(); } long result = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); result *= 10; result += c & 15; c = read(); } while (!isSpaceChar(c)); return result * sign; } public long[] nextLongArray(int arraySize) { long array[] = new long[arraySize]; for (int i = 0; i < arraySize; i++) array[i] = nextLong(); return array; } public float nextFloat() // problematic { float result, div; byte c; result = 0; div = 1; c = (byte) read(); while (c <= ' ') c = (byte) read(); boolean isNegative = (c == '-'); if (isNegative) c = (byte) read(); do { result = result * 10 + c - '0'; } while ((c = (byte) read()) >= '0' && c <= '9'); if (c == '.') while ((c = (byte) read()) >= '0' && c <= '9') result += (c - '0') / (div *= 10); if (isNegative) return -result; return result; } public double nextDouble() // not completely accurate { double ret = 0, div = 1; byte c = (byte) read(); while (c <= ' ') c = (byte) read(); boolean neg = (c == '-'); if (neg) c = (byte) read(); do { ret = ret * 10 + c - '0'; } while ((c = (byte) read()) >= '0' && c <= '9'); if (c == '.') while ((c = (byte) read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } 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 boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String nextLine() { int c = read(); StringBuilder result = new StringBuilder(); do { result.appendCodePoint(c); c = read(); } while (!isNewLine(c)); return result.toString(); } public boolean isNewLine(int c) { return c == '\n'; } public void close() { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } } static class OutputWriter { private PrintWriter writer; public OutputWriter(OutputStream stream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter( stream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void println(int x) { writer.println(x); } public void print(int x) { writer.print(x); } public void println(char x) { writer.println(x); } public void print(char x) { writer.print(x); } public void println(int array[], int size) { for (int i = 0; i < size; i++) println(array[i]); } public void print(int array[], int size) { for (int i = 0; i < size; i++) print(array[i] + " "); } public void println(long x) { writer.println(x); } public void print(long x) { writer.print(x); } public void println(long array[], int size) { for (int i = 0; i < size; i++) println(array[i]); } public void print(long array[], int size) { for (int i = 0; i < size; i++) print(array[i]); } public void println(float num) { writer.println(num); } public void print(float num) { writer.print(num); } public void println(double num) { writer.println(num); } public void print(double num) { writer.print(num); } public void println(String s) { writer.println(s); } public void print(String s) { writer.print(s); } public void println() { writer.println(); } public void printSpace() { writer.print(" "); } public void flush() { writer.flush(); } public void close() { writer.close(); } } static class CMath { static long power(long number, long power) { if (number == 1 || number == 0 || power == 0) return 1; if (power == 1) return number; if (power % 2 == 0) return power(number * number, power / 2); else return power(number * number, power / 2) * number; } static long modPower(long number, long power, long mod) { if (number == 1 || number == 0 || power == 0) return 1; number = mod(number, mod); if (power == 1) return number; long square = mod(number * number, mod); if (power % 2 == 0) return modPower(square, power / 2, mod); else return mod(modPower(square, power / 2, mod) * number, mod); } static long moduloInverse(long number, long mod) { return modPower(number, mod - 2, mod); } static long mod(long number, long mod) { return number - (number / mod) * mod; } static int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
b3138b66d5d039eeffee260b5b43174f
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
//package com.codeforces.competitions.year2016.julytoseptember.round362div2; import java.io.*; import java.util.*; public final class TaskC { public static void main(String[] args) { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); Solver solver = new Solver(in, out); solver.solve(1); out.flush(); in.close(); out.close(); } static class Solver { int q; Map<Edge, Long> map; InputReader in; OutputWriter out; public Solver(InputReader in, OutputWriter out) { this.in = in; this.out = out; } void solve(int testNumber) { q = in.nextInt(); map = new HashMap<>(); /* Edge[] edges = new Edge[10]; for (int i = 0; i < 10; i++) edges[i] = new Edge(i + 1, (i + 1) * 10, (i + 1) * 100); System.out.println("hashCodes : "); for (int i = 0; i < 10; i++) System.out.println("i : " + (i + 1) + ", hC[i] : " + edges[i].hashCode());*/ for (int i = 0; i < q; i++) { int type; long from, to; type = in.nextInt(); from = in.nextLong(); to = in.nextLong(); if (type == 1) { long weight = in.nextLong(); int count = 0; while (true) { while (from > to) { long temp = from >> 1; Edge e = new Edge(from, temp); Long prevWeight = map.get(e); if (prevWeight == null) { map.put(e, weight); // System.out.println("putting new edge : (" + from + ", " + temp + "), wt. : " + weight); } else { map.put(e, prevWeight + weight); // System.out.println("updating edge : (" + from + ", " + temp + "), wt. : " + // prevWeight + weight); } count++; from = temp; } if (from == to) { break; } while (to > from) { long temp = to >> 1; Edge e = new Edge(to, temp); Long prevWeight = map.get(e); if (prevWeight == null) { map.put(e, weight); // System.out.println("**putting new edge : (" + to + ", " + temp + "), wt. : " + weight); } else { map.put(e, prevWeight + weight); // System.out.println("**updating edge : (" + to + ", " + temp + "), wt. : " + // prevWeight + weight); } // count++; to = temp; } if (from == to) break; } // System.out.println("\t\t&&&& total edges : " + count); } else { long answer = 0; int count = 0; while (true) { while (from > to) { long temp = from >> 1; Edge e = new Edge(from, temp); Long weight = map.get(e); if (weight != null) { answer += weight; // System.out.println("\t^^^^ adding " + weight); } // else // System.out.println("\t\t\t$$$$ edge not found : (" + from + ", " + temp + ")"); count++; from = temp; } if (from == to) break; while (to > from) { long temp = to >> 1; Edge e = new Edge(to, temp); Long weight = map.get(e); if (weight != null) { answer += weight; // System.out.println("\t%%%% adding " + weight); } // else // System.out.println("\t\t\t!!!! edge not found : (" + to + ", " + temp + ")"); // count++; to = temp; } if (from == to) break; } // System.out.println("\t\t@@@@ total edges in answer : " + count); out.println(answer); } } } class Edge implements Comparable<Edge> { long from, to; public Edge(long from, long to) { this.from = from; this.to = to; } @Override public int hashCode() { return Objects.hash(from, to); } @Override public boolean equals(Object obj) { Edge temp = (Edge) obj; return from == temp.from && to == temp.to; } @Override public int compareTo(Edge o) { if (from == o.from && to == o.to) return 0; return Long.compare(to, o.to); } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c & 15; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int arraySize) { int array[] = new int[arraySize]; for (int i = 0; i < arraySize; i++) array[i] = nextInt(); return array; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sign = 1; if (c == '-') { sign = -1; c = read(); } long result = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); result *= 10; result += c & 15; c = read(); } while (!isSpaceChar(c)); return result * sign; } public long[] nextLongArray(int arraySize) { long array[] = new long[arraySize]; for (int i = 0; i < arraySize; i++) array[i] = nextLong(); return array; } public float nextFloat() // problematic { float result, div; byte c; result = 0; div = 1; c = (byte) read(); while (c <= ' ') c = (byte) read(); boolean isNegative = (c == '-'); if (isNegative) c = (byte) read(); do { result = result * 10 + c - '0'; } while ((c = (byte) read()) >= '0' && c <= '9'); if (c == '.') while ((c = (byte) read()) >= '0' && c <= '9') result += (c - '0') / (div *= 10); if (isNegative) return -result; return result; } public double nextDouble() // not completely accurate { double ret = 0, div = 1; byte c = (byte) read(); while (c <= ' ') c = (byte) read(); boolean neg = (c == '-'); if (neg) c = (byte) read(); do { ret = ret * 10 + c - '0'; } while ((c = (byte) read()) >= '0' && c <= '9'); if (c == '.') while ((c = (byte) read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10); if (neg) return -ret; return ret; } 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 boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String nextLine() { int c = read(); StringBuilder result = new StringBuilder(); do { result.appendCodePoint(c); c = read(); } while (!isNewLine(c)); return result.toString(); } public boolean isNewLine(int c) { return c == '\n'; } public void close() { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } } static class OutputWriter { private PrintWriter writer; public OutputWriter(OutputStream stream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter( stream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void println(int x) { writer.println(x); } public void print(int x) { writer.print(x); } public void println(char x) { writer.println(x); } public void print(char x) { writer.print(x); } public void println(int array[], int size) { for (int i = 0; i < size; i++) println(array[i]); } public void print(int array[], int size) { for (int i = 0; i < size; i++) print(array[i] + " "); } public void println(long x) { writer.println(x); } public void print(long x) { writer.print(x); } public void println(long array[], int size) { for (int i = 0; i < size; i++) println(array[i]); } public void print(long array[], int size) { for (int i = 0; i < size; i++) print(array[i]); } public void println(float num) { writer.println(num); } public void print(float num) { writer.print(num); } public void println(double num) { writer.println(num); } public void print(double num) { writer.print(num); } public void println(String s) { writer.println(s); } public void print(String s) { writer.print(s); } public void println() { writer.println(); } public void printSpace() { writer.print(" "); } public void flush() { writer.flush(); } public void close() { writer.close(); } } static class CMath { static long power(long number, long power) { if (number == 1 || number == 0 || power == 0) return 1; if (power == 1) return number; if (power % 2 == 0) return power(number * number, power / 2); else return power(number * number, power / 2) * number; } static long modPower(long number, long power, long mod) { if (number == 1 || number == 0 || power == 0) return 1; number = mod(number, mod); if (power == 1) return number; long square = mod(number * number, mod); if (power % 2 == 0) return modPower(square, power / 2, mod); else return mod(modPower(square, power / 2, mod) * number, mod); } static long moduloInverse(long number, long mod) { return modPower(number, mod - 2, mod); } static long mod(long number, long mod) { return number - (number / mod) * mod; } static int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
72ee2530b0ba82c3d23bf275a805dc42
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
/** * @author derrick20 */ import java.io.*; import java.util.*; public class LorenzoVonMatterhorn { public static void main(String[] args) throws Exception { FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int Q = sc.nextInt(); HashMap<Long, Long> nodeCosts = new HashMap<>(); while (Q-->0) { int type = sc.nextInt(); long u = sc.nextLong(); long v = sc.nextLong(); if (u < v) { long temp = u; u = v; v = temp; } long u2 = u; long v2 = v; while (Long.highestOneBit(u2) > Long.highestOneBit(v2)) { u2 >>= 1; } while (u2 != v2) { u2 >>= 1; v2 >>= 1; } long lca = u2; if (type == 1) { long cost = sc.nextLong(); long up = u; long vp = v; while (up != lca) { nodeCosts.merge(up, cost, Long::sum); up >>= 1; } while (vp != lca) { nodeCosts.merge(vp, cost, Long::sum); vp >>= 1; } // nodeCosts.merge(lca, cost, Long::sum); } else if (type == 2) { long up = u; long vp = v; long ans = 0; while (up != lca) { ans += nodeCosts.getOrDefault(up, 0L); up >>= 1; } while (vp != lca) { ans += nodeCosts.getOrDefault(vp, 0L); vp >>= 1; } // ans += nodeCosts.get(lca); out.println(ans); } } out.close(); } static class FastScanner { private int BS = 1<<16; private char NC = (char)0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar(){ while(bId==size) { try { size = in.read(buf); }catch(Exception e) { return NC; } if(size==-1)return NC; bId=0; } return (char)buf[bId++]; } public int nextInt() { return (int)nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt=1; boolean neg = false; if(c==NC)c=getChar(); for(;(c<'0' || c>'9'); c = getChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=getChar()) { res = (res<<3)+(res<<1)+c-'0'; cnt*=10; } return neg?-res:res; } public double nextDouble() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/cnt; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=getChar(); while(c>32) { res.append(c); c=getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=getChar(); while(c!='\n') { res.append(c); c=getChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=getChar(); if(c==NC)return false; else if(c>32)return true; } } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
5091fb082a85dbafe7ecfd7846cc56ea
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
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. */ /** * * @author sarthak */ import java.util.*; import java.math.*; import java.io.*; public class rnd362_C { static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public String nextLine() { st = null; try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); return ""; } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } static class P implements Comparable { private long x, y; public P(long x, long y) { this.x = x; this.y = y; } public int hashCode() { return ((int) x * 31) ^ (int) y; } public boolean equals(Object o) { if (o instanceof P) { P other = (P) o; return (x == other.x && y == other.y); } return false; } public int compareTo(Object obj) { P l = (P) obj; if (this.x == l.x) { if (this.y == l.y) { return 0; } return (this.y < l.y) ? -1 : 1; } return (this.x < l.x) ? -1 : 1; } } public static long l(long v) { int cl = 1; while (v != 1) { v=v/2; cl++; } return cl; } public static void main(String[] args) { FastScanner s = new FastScanner(System.in); StringBuilder op = new StringBuilder(); int q = s.nextInt(); HashMap<P,Long>hs=new HashMap<>(); for (int i = 0; i < q; i++) { int t = s.nextInt(); if (t == 1) { long u = s.nextLong(); long v = s.nextLong(); long w=s.nextLong(); long su=u; long sv=v; long lu = l(u); long lv = l(v); ArrayList<Long> U=new ArrayList<>();U.add(u); ArrayList<Long> V=new ArrayList<>();V.add(v); while(lv!=lu){ if(lv>lu){ v=v/2;lv--;V.add(v); }else{ u=u/2;lu--;U.add(u); } } while(u!=v){ u=u/2;U.add(u); v=v/2;V.add(v); } int szu=U.size()-1;int szv=V.size()-1; for(int j=szu;j>0;j--){ if(!hs.containsKey(new P(Math.min(U.get(j), U.get(j-1)),Math.max(U.get(j), U.get(j-1))))){ hs.put(new P(Math.min(U.get(j), U.get(j-1)),Math.max(U.get(j), U.get(j-1))),0L); } long cw=hs.get(new P(Math.min(U.get(j), U.get(j-1)),Math.max(U.get(j), U.get(j-1)))); cw+=w; hs.put(new P(Math.min(U.get(j), U.get(j-1)),Math.max(U.get(j), U.get(j-1))),cw); } for(int j=szv;j>0;j--){ if(!hs.containsKey(new P(Math.min(V.get(j), V.get(j-1)),Math.max(V.get(j), V.get(j-1))))){ hs.put(new P(Math.min(V.get(j), V.get(j-1)),Math.max(V.get(j), V.get(j-1))),0L); } long cw=hs.get(new P(Math.min(V.get(j), V.get(j-1)),Math.max(V.get(j), V.get(j-1)))); cw+=w; hs.put(new P(Math.min(V.get(j), V.get(j-1)),Math.max(V.get(j), V.get(j-1))),cw); } } if (t == 2) { long u = s.nextLong(); long v = s.nextLong(); long su=u; long sv=v; long lu = l(u); long lv = l(v); ArrayList<Long> U=new ArrayList<>();U.add(u); ArrayList<Long> V=new ArrayList<>();V.add(v); while(lv!=lu){ if(lv>lu){ v=v/2;lv--;V.add(v); }else{ u=u/2;lu--;U.add(u); } } while(u!=v){ u=u/2;U.add(u); v=v/2;V.add(v); } int szu=U.size()-1;int szv=V.size()-1; long an=0; for(int j=szu;j>0;j--){ if(hs.containsKey(new P(Math.min(U.get(j), U.get(j-1)),Math.max(U.get(j), U.get(j-1))))){ an+=hs.get(new P(Math.min(U.get(j), U.get(j-1)),Math.max(U.get(j), U.get(j-1)))); } } for(int j=szv;j>0;j--){ if(hs.containsKey(new P(Math.min(V.get(j), V.get(j-1)),Math.max(V.get(j), V.get(j-1))))){ an+=hs.get(new P(Math.min(V.get(j), V.get(j-1)),Math.max(V.get(j), V.get(j-1)))); } } op.append(an+"\n"); } } System.out.print(op); } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
445bcb0762d92e65508929ac567c6a6c
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
/** * Created by vladislav on 7/13/16. */ import java.util.*; import java.math.*; public class hell { public static void main(String[] args){ HashMap<Long, Long> costs = new HashMap<Long, Long>(); long n, type, v, u, w; Scanner scan = new Scanner(System.in); n = scan.nextLong(); for(int i = 0; i < n; ++i){ type = scan.nextLong(); if(type == 1){ v = scan.nextLong(); u = scan.nextLong(); w = scan.nextLong(); while(v != u){ if(v > u){ costs.put(v, costs.getOrDefault(v, 0L) + w); v /= 2; }else{ costs.put(u, costs.getOrDefault(u, 0L) + w); u /= 2; } } }else{ v = scan.nextLong(); u = scan.nextLong(); long ans = 0; while(v != u){ if(v > u){ ans += costs.getOrDefault(v, 0L); v /= 2; }else{ ans += costs.getOrDefault(u, 0L); u /= 2; } } System.out.println(ans); } } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
f7a49e16af228615179d087721f7bc36
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.*; import java.util.*; public class Question { static long[] visted; static ArrayList<Integer>[] grid; static TreeMap<Pair, Long> hm; public static long LCAInt(long v, long u) { long res = 0; while (v != u) { if (u < v) { long newv = v / 2; Pair p = new Pair(newv, v); if (hm.containsKey(p)) { res += hm.get(p); } v = newv; } else { long newu = u / 2; Pair p = new Pair(newu, u); if (hm.containsKey(p)) { res += hm.get(p); } u = newu; } } return res; } public static void LCA(long v, long u, long w) { while (v != u) { if (u < v) { long newv = v / 2; Pair p = new Pair(newv, v); long val = 0; if (hm.containsKey(p)) { val = hm.get(p); } hm.put(p, val + w); v = newv; } else { long newu = u / 2; Pair p = new Pair(newu, u); long val = 0; if (hm.containsKey(p)) { val = hm.get(p); } hm.put(p, val + w); u = newu; } } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); long q = sc.nextInt(); hm = new TreeMap<>(); while (q-- > 0) { long qNumber = sc.nextInt(); if (qNumber == 1) { long v = sc.nextLong(); long u = sc.nextLong(); long w = sc.nextLong(); LCA(v, u, w); } else { long v = sc.nextLong(); long u = sc.nextLong(); out.println(LCAInt(v, u)); } } out.flush(); } 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 long 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() { for (long i = 0; i < 3e9; i++) ; } } } class Pair implements Comparable<Pair> { long a; long b; public Pair(long a, long b) { this.a = a; this.b = b; } @Override public int compareTo(Pair o) { return a != o.a ? (a - o.a > 0 ? 1 : -1) : (b - o.b > 0 ? 1 : b - o.b == 0 ? 0 : -1); } // class Pair implements Comparator<Pair> { // long a; // long b; // // public Pair(long a, long b) { // this.a = a; // this.b = b; // } // // @Override // public int compare(Pair o1, Pair o2) { // if(o1.b < o2.b) // return -1; // if(o1.b > o2.b) // return 1; // return 0; // } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
d1b74023c540de1506e678d4ca1fb66a
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.io.PrintWriter; import java.util.*; public class TaskC { public static void main(String[] args) { TaskC tC = new TaskC(); PrintWriter pw = new PrintWriter(System.out); tC.solve(new Scanner(System.in), pw); pw.close(); } public void solve(Scanner input, PrintWriter output) { int q = input.nextInt(); Map <Long, Long> map = new HashMap<Long, Long>(); while (q-- > 0) { int query = input.nextInt(); long u = input.nextLong(); long v = input.nextLong(); long lca = getLca(u, v); //System.out.println("Lca = " + lca); if (query == 1) { // add query long w = input.nextLong(); while (u != lca) { addValue(map, u, w); //System.out.println("add to " + u); u /= 2; } while (v != lca) { addValue(map, v, w); //System.out.println("add to " + v); v /= 2; } } else { // get sum query long result = 0L; while (u != lca) { result += getValue(map, u); //System.out.println("get from " + u + " -> " + result); u /= 2; } while (v != lca) { result += getValue(map, v); //System.out.println("get from " + v + " -> " + result); v /= 2; } output.println(result); } } } private void addValue(Map <Long, Long> map, long u, long w) { if (!map.containsKey(u)) { map.put(u, w); } else { map.put(u, map.get(u) + w); } } private long getValue(Map <Long, Long> map, long u) { if (!map.containsKey(u)) { return 0L; } return map.get(u); } private long getLca(long u, long v) { if (depth(u) > depth(v)) { return getLca(v, u); } while (depth(u) < depth(v)) { v /= 2; } if (u == v) { return u; } return getLca(u/2, v/2); } private int depth(long u) { return (int) (Math.log(u) / Math.log(2)); } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
46fa8e38ea2d35d479102eca4a3f83ac
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.math.BigDecimal; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; import java.util.Set; import java.util.Vector; public class RobinHood2 { static HashMap<Long, Long> tree = new HashMap<Long, Long>(); public static void update(long u, long w, long common_parent) { while(u!=common_parent) { if(tree.containsKey(u)) tree.put(u, tree.get(u)+w); else tree.put(u, w); u=u/2; } tree.put(1l, 0l); } public static long find_common_parent(long u, long v) { Set<Long> u_set = new HashSet<Long>(); while(u!=1) { u_set.add(u); u/=2; } while(v!=1) { if(u_set.contains(v)) return v; v/=2; } return 0; } public static void rule_one(long u, long v, long w) { long common_parent = find_common_parent(u,v); update(u, w, common_parent); update(v, w, common_parent); } public static long rule_two(long u, long v) { long common_parent = find_common_parent(u,v); long ret=0; while(u!=common_parent) { if(tree.containsKey(u)) ret+=tree.get(u); u/=2; } while(v!=common_parent) { if(tree.containsKey(v)) ret+=tree.get(v); v/=2; } return ret; } public static void main(String args[]) { Scanner sc = new Scanner(System.in); long q = sc.nextLong(); long rule,u,v,w; for(long i=0;i<q;i++) { rule = sc.nextLong(); if(rule==1) { u = sc.nextLong(); v = sc.nextLong(); w = sc.nextLong(); sc.nextLine(); //System.out.println(rule +", " + u +", " +v + ", " +w); rule_one(u, v, w); } else { //System.out.println(tree); u = sc.nextLong(); v = sc.nextLong(); sc.nextLine(); //System.out.println(rule +", " + u +", " +v ); System.out.println(rule_two(u,v)); } } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
4bfda61ce65c2734a4f7488b1d32e526
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
import java.util.*; public class Nyc { static Long swap(Long a, Long b) { return a; } public static void main(String args[]) { Scanner sc = new Scanner(System.in); HashMap<Long, Long> map = new HashMap<>(); int q = sc.nextInt(); while (q-- > 0) { int opt = sc.nextInt(); long u = sc.nextLong(); long v = sc.nextLong(); if (opt == 1) { long w = sc.nextLong(); while (u != v) { if (v > u) u = swap(v, v = u); map.compute(u, (key, val) -> val == null ? w : val + w); u /= 2; } } else { long wayCost = 0; while (u != v) { if (v > u) u = swap(v, v = u); if (map.containsKey(u)) wayCost += map.get(u); u /= 2; } System.out.println(wayCost); } } } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output
PASSED
9b0cbe9f80cf7d1b7ff061ae3ce7035c
train_000.jsonl
1468514100
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes).
256 megabytes
/** * Created by Bakytzhan_Manaspayev on 8/2/2016. */ import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.util.*; public class Div2_697C { //7 //1 3 4 30 //1 4 1 2 //1 3 6 8 //2 4 3 //1 6 1 40 //2 3 7 //2 2 4 //94 //0 //32 static Exception exception; private static Scanner in; private static Output out; static boolean isFile = false; public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new Runnable() { @Override public void run() { try { initReaderWriter(); operate(); out.close(); } catch (Exception ex) { exception = ex; } } }, "", 1 << 26); thread.start(); thread.join(); if (exception != null) { throw exception; } } static Long swap(long a, long b) { return a; } private static void operate() throws IOException { int n = in.nextInt(); HashMap<Long, Long> w = new HashMap(); for (int i = 0; i < n; i++) { int type = in.nextInt(); long a = in.nextLong(), b = in.nextLong(); //add route data if (type == 1) { long c = in.nextLong(); while (a != b) { a = swap(Math.max(a, b), b = Math.min(a, b)); w.compute(a, (key, val) -> val == null ? c : c + val); a /= 2; } } //print result if (type == 2) { long sum = 0; while (a != b) { a = swap(Math.max(a, b), b = Math.min(a, b)); sum += w.getOrDefault(a, 0L); a /= 2; } out.println(sum); } } } private static void initReaderWriter() throws Exception { if (isFile) { in = new Scanner("input.txt"); out = new Output(new File("output.txt")); } else { in = new Scanner(); out = new Output(System.out); } } private static boolean log = false; public static void log(String msg) { if (log) { out.println(msg); out.flush(); } } private static class Scanner { StringTokenizer st = null; BufferedReader bf; public Scanner() { bf = new BufferedReader(new InputStreamReader(System.in)); } public Scanner(String fileName) throws FileNotFoundException { bf = new BufferedReader(new FileReader(fileName)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(bf.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return bf.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } } private static class Output extends PrintStream { public Output(OutputStream out) { super(new BufferedOutputStream(out)); } public Output(File file) throws FileNotFoundException { super(new BufferedOutputStream(new FileOutputStream(file))); } } private static void printMemory() { Runtime runtime = Runtime.getRuntime(); long maxMemory = runtime.maxMemory(); long allocatedMemory = runtime.totalMemory(); long freeMemory = runtime.freeMemory(); long div = 1L * 1024 * 1024; // long div = 1L ; System.out.println("used memory[mgb]: " + (runtime.totalMemory() - runtime.freeMemory()) / div); System.out.println(); } static long appCurrentTime = System.currentTimeMillis(); static long appCurrentTimeNano = System.nanoTime(); private static void printCurrentTime() { out.flush(); System.out.println("Time: " + (System.currentTimeMillis() - appCurrentTime)); System.out.println("Time Nano: " + (System.nanoTime() - appCurrentTimeNano)); } }
Java
["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"]
1 second
["94\n0\n32"]
NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32 + 32 + 30 = 94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second).
Java 8
standard input
[ "data structures", "implementation", "trees", "brute force" ]
12814033bec4956e7561767a6778d77e
The first line of input contains a single integer q (1 ≀ q ≀ 1 000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1 ≀ v, u ≀ 1018, v ≠ u, 1 ≀ w ≀ 109 states for every description line.
1,500
For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events.
standard output