contest_id
stringclasses
33 values
problem_id
stringclasses
14 values
statement
stringclasses
181 values
tags
sequencelengths
1
8
code
stringlengths
21
64.5k
language
stringclasses
3 values
1307
B
B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109)  — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2 3 1 2 NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0).
[ "geometry", "greedy", "math" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.util.Map.Entry; public class codeforces { static int mod = 1000000007; public static void main(String[] args) { FastReader sc = new FastReader(); try { StringBuilder ss = new StringBuilder(); int t = sc.nextInt(); while(t-->0) { int n = sc.nextInt(); long x = sc.nextLong(); long a[] = new long[n]; long moves = -1; for(int i = 0 ;i <n;i++) { a[i] = sc.nextLong(); if(a[i] == x) { moves = 1; } } Arrays.parallelSort(a); if(moves == -1) { if(a[n-1] > x) { moves = 2; } else { moves = x/a[n-1]; if(x%a[n-1] != 0) { moves++; } } } ss.append(moves +"\n"); } System.out.println(ss); } catch(Exception e) { System.out.println(e.getMessage()); } } static long pow(long a, long b) { long ans = 1; long temp = a; while(b>0) { if((b&1) == 1) { ans*=temp; } temp = temp*temp; b = b>>1; } return ans; } static long ncr(int n, int r) { return fact(n) / (fact(r) * fact(n - r)); } static long fact(long n) { long res = 1; for (int i = 2; i <= n; i++) { res = (res * i); } return res; } static long gcd(long a, long b) { if(b == 0) { return a; } return gcd(b , a%b); } static ArrayList<Integer> factor(long n) { ArrayList<Integer> al = new ArrayList<>(); for(int i = 1 ; i*i<=n;i++) { if(n%i == 0) { if(n/i == i) { al.add(i); } else { al.add(i); al.add((int) (n/i)); } } } return al; } static class Pair implements Comparable<Pair>{ long a; int b ; Pair(long a, int b){ this.a = a; this.b = b; } @Override public int compareTo(Pair o) { // TODO Auto-generated method stub return (int)(this.a - o.a); } } static ArrayList<Integer> sieve(int n) { boolean a[] = new boolean[n+1]; Arrays.fill(a, false); for(int i = 2 ; i*i <=n ; i++) { if(!a[i]) { for(int j = 2*i ; j<=n ; j+=i) { a[j] = true; } } } ArrayList<Integer> al = new ArrayList<>(); for(int i = 2 ; i <=n;i++) { if(!a[i]) { al.add(i); } } return al; } static ArrayList<Long> pf(long n) { ArrayList<Long> al = new ArrayList<>(); while(n%2 == 0) { al.add(2l); n = n/2; } for(long i = 3 ; i*i<=n ; i+=2) { while(n%i == 0) { al.add(i); n = n/i; } } if(n>2) { al.add( n); } return al; } 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
1295
C
C. Obtain The Stringtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two strings ss and tt consisting of lowercase Latin letters. Also you have a string zz which is initially empty. You want string zz to be equal to string tt. You can perform the following operation to achieve this: append any subsequence of ss at the end of string zz. A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. For example, if z=acz=ac, s=abcdes=abcde, you may turn zz into following strings in one operation: z=acacez=acace (if we choose subsequence aceace); z=acbcdz=acbcd (if we choose subsequence bcdbcd); z=acbcez=acbce (if we choose subsequence bcebce). Note that after this operation string ss doesn't change.Calculate the minimum number of such operations to turn string zz into string tt. InputThe first line contains the integer TT (1≤T≤1001≤T≤100) — the number of test cases.The first line of each testcase contains one string ss (1≤|s|≤1051≤|s|≤105) consisting of lowercase Latin letters.The second line of each testcase contains one string tt (1≤|t|≤1051≤|t|≤105) consisting of lowercase Latin letters.It is guaranteed that the total length of all strings ss and tt in the input does not exceed 2⋅1052⋅105.OutputFor each testcase, print one integer — the minimum number of operations to turn string zz into string tt. If it's impossible print −1−1.ExampleInputCopy3 aabce ace abacaba aax ty yyt OutputCopy1 -1 3
[ "dp", "greedy", "strings" ]
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { public static void main(String[] args) { new Main().solve(new InputReader(System.in), new PrintWriter(System.out)); } private void solve(InputReader in, PrintWriter pw) { int tt = in.nextInt(); while (tt-- > 0) { char[] s = in.next().toCharArray(); char[] t = in.next().toCharArray(); int n = s.length; int m = t.length; final int INF = 0x3f3f3f3f; int[][] f = new int[n + 1][26]; for (int i = 0; i < 26; i++) { f[n][i] = INF; } for (int i = n - 1; i >= 0; i--) { for (int j = 0; j < 26; j++) { if ((char) (j + 'a') == s[i]) { f[i][j] = i; } else { f[i][j] = f[i + 1][j]; } } } int ans = 1, pos = 0; for (int i = 0; i < m; i++) { if (pos == n) { ans++; pos = 0; } if (f[pos][t[i] - 'a'] == INF) { ans++; pos = 0; if (f[pos][t[i] - 'a'] == INF) { ans = INF; break; } } pos = f[pos][t[i] - 'a'] + 1; } pw.println(ans >= INF ? -1 : ans); } pw.close(); } } class InputReader { private final BufferedReader reader; private 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() { String str; try { str = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return str; } public boolean hasNext() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { String nextLine = null; try { nextLine = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (nextLine == null) return false; tokenizer = new StringTokenizer(nextLine); } return true; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
java
1288
A
A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in ⌈dx+1⌉⌈dx+1⌉ days (⌈a⌉⌈a⌉ is the ceiling function: ⌈2.4⌉=3⌈2.4⌉=3, ⌈2⌉=2⌈2⌉=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+⌈dx+1⌉x+⌈dx+1⌉.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1≤T≤501≤T≤50) — the number of test cases.The next TT lines contain test cases – one per line. Each line contains two integers nn and dd (1≤n≤1091≤n≤109, 1≤d≤1091≤d≤109) — the number of days before the deadline and the number of days the program runs.OutputPrint TT answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3 1 1 4 5 5 11 OutputCopyYES YES NO NoteIn the first test case; Adilbek decides not to optimize the program at all; since d≤nd≤n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run ⌈52⌉=3⌈52⌉=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work ⌈112+1⌉=4⌈112+1⌉=4 days.
[ "binary search", "brute force", "math", "ternary search" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.*; public class Main { static long M = (long) (1e9 + 7); 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 { if (st.hasMoreTokens()) { str = st.nextToken("\n"); } else { str = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } return str; } } public static void heapify(int arr[], int n, int i) { int largest = i; int l = 2 * i + 1; int r = 2 * i + 2; if (l < n && arr[l] > arr[largest]) largest = l; if (r < n && arr[r] > arr[largest]) largest = r; if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; heapify(arr, n, largest); } } public static void swap(int[] a, int i, int j) { int temp = (int) a[i]; a[i] = a[j]; a[j] = temp; } public static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } public static int lcm(int a, int b) { return (a * b / gcd(a, b)); } public static String sortString(String inputString) { // Converting input string to character array char[] tempArray = inputString.toCharArray(); // Sorting temp array using Arrays.sort(tempArray); // Returning new sorted string return new String(tempArray); } static boolean isSquare(int n) { int v = (int) Math.sqrt(n); return v * v == n; } static boolean PowerOfTwo(int n) { if (n == 0) return false; return (int) (Math.ceil((Math.log(n) / Math.log(2)))) == (int) (Math.floor(((Math.log(n) / Math.log(2))))); } static int power(long a, long b) { long res = 1; while (b > 0) { if (b % 2 == 1) { res = (res * a) % M; } a = ((a * a) % M); b = b / 2; } return (int) res; } public static boolean isPrime(int n) { for (int i = 2; i * i <= n; i++) if (n % i == 0) { return false; } return true; } static int pown(long n){ if(n==0) return 1; if(n==1) return 1; if((n&(~(n-1)))==n) return 0; return 1; } static long computeXOR(long n) { // If n is a multiple of 4 if (n % 4 == 0) return n; // If n%4 gives remainder 1 if (n % 4 == 1) return 1; // If n%4 gives remainder 2 if (n % 4 == 2) return n + 1; // If n%4 gives remainder 3 return 0; } static long binaryToInteger(String binary) { char[] numbers = binary.toCharArray(); long result = 0; for (int i = numbers.length - 1; i >= 0; i--) if (numbers[i] == '1') result += Math.pow(2, (numbers.length - i - 1)); return result; } static String reverseString(String str){ char ch[]=str.toCharArray(); String rev=""; for(int i=ch.length-1;i>=0;i--){ rev+=ch[i]; } return rev; } public static void main(String[] args) throws Exception { FastReader sc = new FastReader(); int t = sc.nextInt(); while (t-- != 0) { long n=sc.nextLong(); long d=sc.nextLong(); if(n*n+2*n+1>=4*d) { System.out.println("YES"); } else { System.out.println("NO"); } } } }
java
1304
B
B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has nn distinct strings of equal length mm. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers nn and mm (1≤n≤1001≤n≤100, 1≤m≤501≤m≤50) — the number of strings and the length of each string.Next nn lines contain a string of length mm each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInputCopy3 3 tab one bat OutputCopy6 tabbat InputCopy4 2 oo ox xo xx OutputCopy6 oxxxxo InputCopy3 5 hello codef orces OutputCopy0 InputCopy9 4 abab baba abcd bcde cdef defg wxyz zyxw ijji OutputCopy20 ababwxyzijjizyxwbaba NoteIn the first example; "battab" is also a valid answer.In the second example; there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example; the empty string is the only valid palindrome string.
[ "brute force", "constructive algorithms", "greedy", "implementation", "strings" ]
import java.io.*; import java.util.*; import java.lang.*; public class Codeforces { public static void main(String[] args) { Scanner input= new Scanner(System.in); int n=input.nextInt(); int m=input.nextInt(); int palincnt=0; HashMap<String,Integer> map = new HashMap<>(); String[] strings=new String[n]; ArrayList<String> anslist=new ArrayList<>(); for(int i=0;i<n;i++) { strings[i]=input.next(); map.put(strings[i],map.getOrDefault(strings,0)+1); } boolean ok=false; for(int i=0;i<n;i++) { if(map.containsKey(reverse(strings[i]))) { if(strings[i].equals(reverse(strings[i]))) { if((map.get(strings[i])%2!=0)&&(ok==false)&& map.get(strings[i])>0) { int len=map.get(strings[i])/2; String a=strings[i].repeat(len); if(len!=0){ anslist.add(0,a); anslist.add(a); } ok=true; int pos=anslist.size()/2; anslist.add(pos,strings[i]); map.put(strings[i],0); } else { int len=map.get(strings[i])/2; String a=strings[i].repeat(len); if(len!=0){ anslist.add(0,a); anslist.add(a); map.put(strings[i],0); } } } else if((map.get(strings[i])!=0)&&(map.get(reverse(strings[i]))!=0)){ int a=Math.min(map.get(strings[i]),map.get(reverse(strings[i]))); String aa=strings[i].repeat(a); String bb=reverse(strings[i]).repeat(a); anslist.add(0,aa); anslist.add(bb); map.put(strings[i],0); map.put(reverse(strings[i]),0); } } } int length=anslist.size(); System.out.println(length*m); for(int i=0;i<length;i++) { System.out.print(anslist.get(i)); } System.out.println(""); } public static String reverse(String input) { byte[] strAsByteArray = input.getBytes(); byte[] result = new byte[strAsByteArray.length]; for (int i = 0; i < strAsByteArray.length; i++) result[i] = strAsByteArray[strAsByteArray.length - i - 1]; return (new String(result)); } }
java
1307
C
C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1≤|s|≤1051≤|s|≤105) — the text that Bessie intercepted.OutputOutput a single integer  — the number of occurrences of the secret message.ExamplesInputCopyaaabb OutputCopy6 InputCopyusaco OutputCopy1 InputCopylol OutputCopy2 NoteIn the first example; these are all the hidden strings and their indice sets: a occurs at (1)(1), (2)(2), (3)(3) b occurs at (4)(4), (5)(5) ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5) aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3) bb occurs at (4,5)(4,5) aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4) aaa occurs at (1,2,3)(1,2,3) abb occurs at (3,4,5)(3,4,5) aaab occurs at (1,2,3,4)(1,2,3,4) aabb occurs at (2,3,4,5)(2,3,4,5) aaabb occurs at (1,2,3,4,5)(1,2,3,4,5) Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.
[ "brute force", "dp", "math", "strings" ]
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws Exception { FastReader sc = new FastReader(); PrintWriter writer = new PrintWriter(System.out); long mod = 1000000007; int t = 1; while(t-->0) { String s = sc.next(); long mat [][] = new long[26][26]; long ind[] = new long[26]; long max = 0; for(int i = 0; i < s.length(); i++) { int val = s.charAt(i) - 'a'; for(int j = 0; j < 26; j++) { mat[val][j]+=ind[j]; max = Math.max(max, mat[val][j]); } ind[val]++; max = Math.max(max, ind[val]); } writer.println(max); } writer.flush(); writer.close(); } private static long power (long a, long n, long p) { long res = 1; while(n!=0) { if(n%2==1) { res=(res*a)%p; n--; }else { a= (a*a)%p; n/=2; } } return res; } private static boolean isPrime(int c) { for (int i = 2; i*i <= c; i++) { if(c%i==0)return false; } return true; } private static int find(int a , int arr[]) { if(arr[a] != a) return arr[a] = find(arr[a], arr); return arr[a]; } private static void union(int a, int b, int arr[]) { int aa = find(a,arr); int bb = find(b, arr); arr[aa] = bb; } private static int gcd(int a, int b) { if(a==0)return b; return gcd(b%a, a); } public static int[] readIntArray(int size, FastReader s) { int[] array = new int[size]; for (int i = 0; i < size; i++) { array[i] = s.nextInt(); } return array; } 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; } } } class SegmentTree{ int size; long arr[]; SegmentTree(int n){ size = 1; while(size<n)size*=2; arr = new long[size*2]; } public void build(int input[]) { build(input, 0,0, size); } public void set(int i, int v) { set(i,v,0,0,size); } // sum from l + r-1 public long sum(int l, int r) { return sum(l,r,0,0,size); } private void build(int input[], int x, int lx, int rx) { if(rx-lx==1) { if(lx < input.length ) arr[x] = 1; return; } int mid = (lx+rx)/2; build(input, 2*x+1, lx, mid); build(input,2*x+2,mid,rx); arr[x] = arr[2*x+1] + arr[2*x+2]; } private void set(int i, int v, int x, int lx, int rx) { if(rx-lx==1) { arr[x] = v; return; } int mid = (lx+rx)/2; if(i < mid) set(i, v, 2*x+1, lx, mid); else set(i,v,2*x+2,mid,rx); arr[x] = arr[2*x+1] + arr[2*x+2]; } private long sum(int l, int r, int x, int lx, int rx) { if(lx>=r || rx <= l)return 0; if(lx>=l && rx <= r)return arr[x]; int mid = (lx+rx)/2; long s1 = sum(l,r,2*x+1,lx,mid); long s2 = sum(l,r,2*x+2,mid,rx); return s2+s1; } // int first_above(int v, int l, int x, int lx, int rx) { // if(arr[x].a<v)return -1; // if(rx<=l)return -1; // if(rx-lx==1)return lx; // int m = (lx+rx)/2; // int res = first_above(v,l,2*x+1,lx,m); // if(res==-1)res = first_above(v,l,2*x+2,m,rx); // return res; // // } } class Pair implements Comparable<Pair>{ int a; int b; int c; Pair(int a, int b, int c){ this.a = a; this.b = b; this.c = c; } // @Override // public boolean equals(Object obj) { // // if(this == obj) return true; // if(obj == null || obj.getClass()!= this.getClass()) return false; // // Pair pair = (Pair) obj; // return (pair.a == this.a && pair.b == this.b); // } // @Override // public int hashCode() // { // // return Objects.hash(a,b); // return new Long(a).hashCode() * 31 + new Long(b).hashCode(); // } @Override public int compareTo(Pair o) { if(this.c != o.c) return Integer.compare(this.c, o.c); else if(this.a != o.a) return Integer.compare(this.a, o.a); return Integer.compare(this.b, o.b); } @Override public String toString() { return this.a + " " + this.b; } }
java
1287
B
B. Hypersettime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes; shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every feature — color, number, shape, and shading — the three cards must display that feature as either all the same, or pairwise different. The picture below shows how sets look.Polina came up with a new game called "Hyperset". In her game, there are nn cards with kk features, each feature has three possible values: "S", "E", or "T". The original "Set" game can be viewed as "Hyperset" with k=4k=4.Similarly to the original game, three cards form a set, if all features are the same for all cards or are pairwise different. The goal of the game is to compute the number of ways to choose three cards that form a set.Unfortunately, winter holidays have come to an end, and it's time for Polina to go to school. Help Polina find the number of sets among the cards lying on the table.InputThe first line of each test contains two integers nn and kk (1≤n≤15001≤n≤1500, 1≤k≤301≤k≤30) — number of cards and number of features.Each of the following nn lines contains a card description: a string consisting of kk letters "S", "E", "T". The ii-th character of this string decribes the ii-th feature of that card. All cards are distinct.OutputOutput a single integer — the number of ways to choose three cards that form a set.ExamplesInputCopy3 3 SET ETS TSE OutputCopy1InputCopy3 4 SETE ETSE TSES OutputCopy0InputCopy5 4 SETT TEST EEET ESTE STES OutputCopy2NoteIn the third example test; these two triples of cards are sets: "SETT"; "TEST"; "EEET" "TEST"; "ESTE", "STES"
[ "brute force", "data structures", "implementation" ]
//package prog_temps; import java.lang.reflect.Array; import java.util.*; import java.io.*; //166666500+833333500 public class Java_Template { static boolean[] primecheck = new boolean[1000002]; static int M = 1000000007; static int mn = Integer.MIN_VALUE; static int mx = Integer.MAX_VALUE; static int vis[]; static ArrayList<ArrayList<Integer>> list; public static void solve(FastReader sc, PrintWriter w) throws Exception { int n =sc.nI(),k =sc.nI(); int count =0; String arr[] = new String[n]; HashMap<String, Integer> map = new HashMap<>(); for(int i=0;i<n;i++) { arr[i] = sc.nextLine(); if (map.containsKey(arr[i])) { map.put(arr[i], map.get(arr[i]) + 1); } else{ map.put(arr[i], 1); } } String chkr =""; for (int i = 0; i < n ; i++) { for (int j = i+1; j <n ; j++) { // i and j are first 2 sets; chkr =""; for (int l = 0; l < k; l++) { if(arr[i].charAt(l)==arr[j].charAt(l)) { chkr += arr[i].charAt(l); } else { chkr += (char) ('S' + 'E' + 'T' - arr[i].charAt(l) - arr[j].charAt(l)); } } if(map.containsKey(chkr)){ count +=map.get(chkr); } if(arr[i].equals(arr[j])){ count -=2; } } } w.println(count/3); } public static void main(String[] args) throws Exception { FastReader sc = new FastReader(); PrintWriter w = new PrintWriter(System.out); int t = 1; //t = sc.nI(); while (t-- > 0) { solve(sc, w); } w.close(); } // public static void matSort(int[][] arr, int l, int r, int row, int index) { if (l < r) { // Find the middle point int m = l + (r - l) / 2; // Sort first and second halves matSort(arr, l, m, row, index); matSort(arr, m + 1, r, row, index); // Merge the sorted halves matMerge(arr, l, m, r, row, index); } } public static void matMerge(int[][] arr, int l, int m, int r, int row, int index) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int[][] L = new int[2][n1]; int[][] R = new int[2][n2]; /*Copy data to temp arrays*/ for (int i = 0; i < n1; ++i) { L[0][i] = arr[row][l + i]; L[1][i] = arr[index][l + i]; } for (int j = 0; j < n2; ++j) { R[0][j] = arr[row][m + 1 + j]; R[1][j] = arr[index][m + 1 + j]; } /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[0][i] <= R[0][j]) { arr[row][k] = L[0][i]; arr[index][k] = L[1][i]; i++; } else { arr[row][k] = R[0][j]; arr[index][k] = R[1][j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[row][k] = L[0][i]; arr[index][k] = L[1][i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[row][k] = R[0][j]; arr[index][k] = R[1][j]; j++; k++; } } 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 nI() { return Integer.parseInt(next()); } long nL() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } void readArr(int[] ar, int n) { for (int i = 0; i < n; i++) { ar[i] = nI(); } } } public static boolean perfectSqr(long a) { long sqrt = (long) Math.sqrt(a); if (sqrt * sqrt == a) { return true; } return false; } public static void Sieve(int n) { Arrays.fill(primecheck, true); primecheck[0] = false; primecheck[1] = false; for (int i = 2; i * i < n + 1; i++) { if (primecheck[i]) { for (int j = i * 2; j < n + 1; j += i) { primecheck[j] = false; } } } } public static int gcd(int a, int b) { if (b == 0) { return a; } return gcd(b, a % b); } public static long power(long x, long y) { long res = 1; // Initialize result while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = res * x; // y must be even now y = y >> 1; // y = y/2 x = x * x; // Change x to x^2 } return res; } public static void sort(int[] arr, int l, int r) { if (l < r) { // Find the middle point int m = l + (r - l) / 2; // Sort first and second halves sort(arr, l, m); sort(arr, m + 1, r); // Merge the sorted halves merge(arr, l, m, r); } } public static void merge(int[] arr, int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ int L[] = new int[n1]; int R[] = new int[n2]; /*Copy data to temp arrays*/ for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } }
java
1320
B
B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection vv to another intersection uu is the path that starts in vv, ends in uu and has the minimum length among all such paths.Polycarp lives near the intersection ss and works in a building near the intersection tt. Every day he gets from ss to tt by car. Today he has chosen the following path to his workplace: p1p1, p2p2, ..., pkpk, where p1=sp1=s, pk=tpk=t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from ss to tt.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection ss, the system chooses some shortest path from ss to tt and shows it to Polycarp. Let's denote the next intersection in the chosen path as vv. If Polycarp chooses to drive along the road from ss to vv, then the navigator shows him the same shortest path (obviously, starting from vv as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection ww instead, the navigator rebuilds the path: as soon as Polycarp arrives at ww, the navigation system chooses some shortest path from ww to tt and shows it to Polycarp. The same process continues until Polycarp arrives at tt: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1,2,3,4][1,2,3,4] (s=1s=1, t=4t=4): Check the picture by the link http://tk.codeforces.com/a.png When Polycarp starts at 11, the system chooses some shortest path from 11 to 44. There is only one such path, it is [1,5,4][1,5,4]; Polycarp chooses to drive to 22, which is not along the path chosen by the system. When Polycarp arrives at 22, the navigator rebuilds the path by choosing some shortest path from 22 to 44, for example, [2,6,4][2,6,4] (note that it could choose [2,3,4][2,3,4]); Polycarp chooses to drive to 33, which is not along the path chosen by the system. When Polycarp arrives at 33, the navigator rebuilds the path by choosing the only shortest path from 33 to 44, which is [3,4][3,4]; Polycarp arrives at 44 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 22 rebuilds in this scenario. Note that if the system chose [2,3,4][2,3,4] instead of [2,6,4][2,6,4] during the second step, there would be only 11 rebuild (since Polycarp goes along the path, so the system maintains the path [3,4][3,4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105) — the number of intersections and one-way roads in Bertown, respectively.Then mm lines follow, each describing a road. Each line contains two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) denoting a road from intersection uu to intersection vv. All roads in Bertown are pairwise distinct, which means that each ordered pair (u,v)(u,v) appears at most once in these mm lines (but if there is a road (u,v)(u,v), the road (v,u)(v,u) can also appear).The following line contains one integer kk (2≤k≤n2≤k≤n) — the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1≤pi≤n1≤pi≤n, all these integers are pairwise distinct) — the intersections along Polycarp's path in the order he arrived at them. p1p1 is the intersection where Polycarp lives (s=p1s=p1), and pkpk is the intersection where Polycarp's workplace is situated (t=pkt=pk). It is guaranteed that for every i∈[1,k−1]i∈[1,k−1] the road from pipi to pi+1pi+1 exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInputCopy6 9 1 5 5 4 1 2 2 3 3 4 4 1 2 6 6 4 4 2 4 1 2 3 4 OutputCopy1 2 InputCopy7 7 1 2 2 3 3 4 4 5 5 6 6 7 7 1 7 1 2 3 4 5 6 7 OutputCopy0 0 InputCopy8 13 8 7 8 6 7 5 7 4 6 5 6 4 5 3 5 2 4 3 4 2 3 1 2 1 1 8 5 8 7 5 2 1 OutputCopy0 3
[ "dfs and similar", "graphs", "shortest paths" ]
import java.io.*; import java.util.*; public class Codeforces1320B { public static long MOD = 1000000007; public static int n, m, k; public static ArrayList<Integer>[] adj; public static boolean[] vis; public static int[] p, x, y, count, dist; public static void bfs(int a) { LinkedList<Integer> queue = new LinkedList<>(); queue.add(a); Arrays.fill(dist,Integer.MAX_VALUE); dist[a] = 0; vis[a] = true; while (!queue.isEmpty()) { int cur = queue.poll(); for (int i : adj[cur]) { dist[i] = Math.min(dist[i], dist[cur]+1); if (!vis[i]) { vis[i] = true; queue.add(i); } } } } public static void main(String[] args)throws Exception { FastIO sc = new FastIO(); n = sc.nextInt(); m = sc.nextInt(); adj = new ArrayList[n]; dist = new int[n]; vis = new boolean[n]; x = new int[m]; y = new int[m]; count = new int[n]; for (int i=0; i<n; i++) adj[i] = new ArrayList<>(); for (int i=0; i<m; i++) { x[i] = sc.nextInt()-1; y[i] = sc.nextInt()-1; adj[y[i]].add(x[i]); } k = sc.nextInt(); p = new int[k]; for (int i=0; i<k; i++) p[i] = sc.nextInt()-1; bfs(p[k-1]); for (int i=0; i<m; i++) if (dist[y[i]]+1 == dist[x[i]]) count[x[i]]++; int min = 0, max = 0; for (int i=0; i<k-1; i++) { if (dist[p[i+1]]+1 > dist[p[i]]) { min++; max++; } else if (count[p[i]] > 1) max++; } System.out.println(min + " " + max); } static class FastIO { BufferedReader br; StringTokenizer st; public FastIO() { 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
1311
F
F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t⋅vixi+t⋅vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of points.The second line of the input contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1081≤xi≤108), where xixi is the initial coordinate of the ii-th point. It is guaranteed that all xixi are distinct.The third line of the input contains nn integers v1,v2,…,vnv1,v2,…,vn (−108≤vi≤108−108≤vi≤108), where vivi is the speed of the ii-th point.OutputPrint one integer — the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).ExamplesInputCopy3 1 3 2 -100 2 3 OutputCopy3 InputCopy5 2 1 4 3 5 2 2 2 3 4 OutputCopy19 InputCopy2 2 1 -3 0 OutputCopy0
[ "data structures", "divide and conquer", "implementation", "sortings" ]
/* "Everything in the universe is balanced. Every disappointment you face in life will be balanced by something good for you! Keep going, never give up." Just have Patience + 1... */ import java.util.*; import java.lang.*; import java.io.*; public class Solution { static class FenwickTree { long[] tree; int n; FenwickTree(int n) { this.n = n; tree = new long[n + 1]; } public void update(int index, int add) { index++; while (index <= n) { tree[index] += add; index += index & -index; } } public long query(int start, int end) { return prefixQuery(end) - prefixQuery(start - 1); } private long prefixQuery(int index) { index++; long sum = 0; while (index > 0) { sum += tree[index]; index -= index & -index; } return sum; } } static boolean sortBySpeed = false; static class MovingPoint implements Comparable<MovingPoint> { int position; int speed; MovingPoint(int position, int speed) { this.position = position; this.speed = speed; } public int compareTo(MovingPoint m) { if (sortBySpeed) { return Integer.compare(speed, m.speed); } return Integer.compare(position, m.position); } } public static void main(String[] args) throws java.lang.Exception { out = new PrintWriter(new BufferedOutputStream(System.out)); sc = new FastReader(); int test = 1; for (int t = 1; t <= test; t++) { solve(); } out.close(); } private static void solve() { int n = sc.nextInt(); MovingPoint[] movingPoints = new MovingPoint[n]; for (int i = 0; i < n; i++) { movingPoints[i] = new MovingPoint(0, 0); } for (int i = 0; i < n; i++) { movingPoints[i].position = sc.nextInt(); } for (int i = 0; i < n; i++) { movingPoints[i].speed = sc.nextInt(); } sortBySpeed = true; Arrays.sort(movingPoints); // compress speeds so that we can fit speeds in fenwick tree int lastSpeed = movingPoints[0].speed; movingPoints[0].speed = 0; for (int i = 1; i < n; i++) { if (movingPoints[i].speed == lastSpeed) { movingPoints[i].speed = movingPoints[i - 1].speed; }else { lastSpeed = movingPoints[i].speed; movingPoints[i].speed = movingPoints[i - 1].speed + 1; } } sortBySpeed = false; Arrays.sort(movingPoints); /* Now count minimum distance of each moving pairs, so for pair i, j assuming i < j, if speed of i <= speed of j, then the minimum distance we could get is the initial distance between these two moving points. else, point i can intersect at some moment of time with point j, and so minimum distance would be 0. So, total sum of distances would be like : (position_j - position_i1) + (position_j - position_i2) + .... = (count of points having speed <= speed_j) * position_j - (sum of positions having speed <= speed_j). */ FenwickTree count = new FenwickTree(n); FenwickTree sum = new FenwickTree(n); long totalSumOfDistances = 0; for (MovingPoint movingPoint : movingPoints) { int speed = movingPoint.speed; int position = movingPoint.position; totalSumOfDistances += count.prefixQuery(speed) * position - sum.prefixQuery(speed); sum.update(speed, position); count.update(speed, 1); } out.println(totalSumOfDistances); } public static FastReader sc; public static PrintWriter out; static class FastReader { BufferedReader br; StringTokenizer str; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (str == null || !str.hasMoreElements()) { try { str = new StringTokenizer(br.readLine()); } catch (IOException lastMonthOfVacation) { lastMonthOfVacation.printStackTrace(); } } return str.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 lastMonthOfVacation) { lastMonthOfVacation.printStackTrace(); } return str; } } }
java
1310
D
D. Tourismtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputMasha lives in a country with nn cities numbered from 11 to nn. She lives in the city number 11. There is a direct train route between each pair of distinct cities ii and jj, where i≠ji≠j. In total there are n(n−1)n(n−1) distinct routes. Every route has a cost, cost for route from ii to jj may be different from the cost of route from jj to ii.Masha wants to start her journey in city 11, take exactly kk routes from one city to another and as a result return to the city 11. Masha is really careful with money, so she wants the journey to be as cheap as possible. To do so Masha doesn't mind visiting a city multiple times or even taking the same route multiple times.Masha doesn't want her journey to have odd cycles. Formally, if you can select visited by Masha city vv, take odd number of routes used by Masha in her journey and return to the city vv, such journey is considered unsuccessful.Help Masha to find the cheapest (with minimal total cost of all taken routes) successful journey.InputFirst line of input had two integer numbers n,kn,k (2≤n≤80;2≤k≤102≤n≤80;2≤k≤10): number of cities in the country and number of routes in Masha's journey. It is guaranteed that kk is even.Next nn lines hold route descriptions: jj-th number in ii-th line represents the cost of route from ii to jj if i≠ji≠j, and is 0 otherwise (there are no routes i→ii→i). All route costs are integers from 00 to 108108.OutputOutput a single integer — total cost of the cheapest Masha's successful journey.ExamplesInputCopy5 8 0 1 2 2 0 0 0 1 1 2 0 1 0 0 0 2 1 1 0 0 2 0 1 2 0 OutputCopy2 InputCopy3 2 0 1 1 2 0 1 2 2 0 OutputCopy3
[ "dp", "graphs", "probabilities" ]
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; // editorial: randomize coloring, 1 / 512 chance shortest path is ans public class cf1310d { public static void main(String[] args) throws IOException { int n = rni(), k = ni(), d[][] = new int[n][]; for(int i = 0; i < n; ++i) { d[i] = ria(n); } long ans = LMAX; for(int x = 0; x < 5120; ++x) { boolean clr[] = new boolean[n]; for(int i = 0; i < n; ++i) { clr[i] = randInt(0, 1) == 0; } long dp[][] = new long[k + 1][n]; for(long[] row : dp) { fill(row, LMAX >> 1); } dp[0][0] = 0; for(int i = 1; i <= k; ++i) { for(int u = 0; u < n; ++u) { for(int v = 0; v < n; ++v) { if(clr[u] != clr[v]) { dp[i][u] = min(dp[i][u], dp[i - 1][v] + d[v][u]); } } } } ans = min(ans, dp[k][0]); } prln(ans); close(); } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random rand = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e10 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int fli(double d) {return (int)d;} static int cei(double d) {return (int)ceil(d);} static long fll(double d) {return (long)d;} static long cel(double d) {return (long)ceil(d);} static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);} static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);} static int randInt(int min, int max) {return rand.nextInt(max - min + 1) + min;} static long hash(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);} // array util static void reverse(int[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static int[] copy(int[] a) {int[] ans = new int[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static long[] copy(long[] a) {long[] ans = new long[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static char[] copy(char[] a) {char[] ans = new char[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static int[] sorted(int[] a) {int[] ans = copy(a); sort(ans); return ans;} static long[] sorted(long[] a) {long[] ans = copy(a); sort(ans); return ans;} static int[] rsorted(int[] a) {int[] ans = copy(a); rsort(ans); return ans;} static long[] rsorted(long[] a) {long[] ans = copy(a); rsort(ans); return ans;} // graph util static List<List<Integer>> graph(int n) {List<List<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;} static List<List<Integer>> graph(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connect(g, rni() - 1, ni() - 1); return g;} static List<List<Integer>> graph(int n, int m) throws IOException {return graph(graph(n), m);} static List<List<Integer>> dgraph(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connecto(g, rni() - 1, ni() - 1); return g;} static List<List<Integer>> dgraph(List<List<Integer>> g, int n, int m) throws IOException {return dgraph(graph(n), m);} static List<Set<Integer>> sgraph(int n) {List<Set<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;} static List<Set<Integer>> sgraph(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connect(g, rni() - 1, ni() - 1); return g;} static List<Set<Integer>> sgraph(int n, int m) throws IOException {return sgraph(sgraph(n), m);} static List<Set<Integer>> dsgraph(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connecto(g, rni() - 1, ni() - 1); return g;} static List<Set<Integer>> dsgraph(List<Set<Integer>> g, int n, int m) throws IOException {return dsgraph(sgraph(n), m);} static void connect(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);} static void connecto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);} static void dconnect(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);} static void dconnecto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);} // input static void r() throws IOException {input = new StringTokenizer(__in.readLine());} static int ri() throws IOException {return Integer.parseInt(__in.readLine());} static long rl() throws IOException {return Long.parseLong(__in.readLine());} static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;} static int[] riam1(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()) - 1; return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;} static char[] rcha() throws IOException {return __in.readLine().toCharArray();} static String rline() throws IOException {return __in.readLine();} static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());} static int ni() {return Integer.parseInt(input.nextToken());} static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());} static long nl() {return Long.parseLong(input.nextToken());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {__out.println("yes");} static void pry() {__out.println("Yes");} static void prY() {__out.println("YES");} static void prno() {__out.println("no");} static void prn() {__out.println("No");} static void prN() {__out.println("NO");} static void pryesno(boolean b) {__out.println(b ? "yes" : "no");}; static void pryn(boolean b) {__out.println(b ? "Yes" : "No");} static void prYN(boolean b) {__out.println(b ? "YES" : "NO");} static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next()); else __out.println();} static void h() {__out.println("hlfd");} static void flush() {__out.flush();} static void close() {__out.close();} }
java
1294
C
C. Product of Three Numberstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given one integer number nn. Find three distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c and a⋅b⋅c=na⋅b⋅c=n or say that it is impossible to do it.If there are several answers, you can print any.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next nn lines describe test cases. The ii-th test case is given on a new line as one integer nn (2≤n≤1092≤n≤109).OutputFor each test case, print the answer on it. Print "NO" if it is impossible to represent nn as a⋅b⋅ca⋅b⋅c for some distinct integers a,b,ca,b,c such that 2≤a,b,c2≤a,b,c.Otherwise, print "YES" and any possible such representation.ExampleInputCopy5 64 32 97 2 12345 OutputCopyYES 2 4 8 NO NO NO YES 3 5 823
[ "greedy", "math", "number theory" ]
import java.io.*; import java.util.*; public class ProblemB { static HashMap<Long,Integer>mp ; static int MOD = (int)1e9+7; static int MAX = (int)1e5+1; static char c[][]; public static void main(String[] args) throws Exception { Scanner in = new Scanner(); StringBuilder sb = new StringBuilder(); int test = in.readInt(); while(test-->0){ int n = in.readInt(); boolean ok = false; outer: for(int i = 2;i*i<=n;i++){ if(n%i == 0){ int other = n/i; for(int j = 2;j*j<=other;j++){ if(other%j == 0){ if(other/j != j && j != i && i!= other/j){ sb.append("YES\n"); sb.append(i+" "+j+" "+(other/j)+"\n"); ok = true; break outer; } } } } } if(!ok)sb.append("NO\n"); } System.out.println(sb); } public static int go(int a[], long h,int b,int g,int ind){ if(ind>=a.length)return 0; if(h>a[ind]) return 1+go(a,h+a[ind]/2,b,g,ind+1); return Math.max(g>0?go(a,2*h,b,g-1,ind):0,b>0?go(a,3*h,b-1,g,ind):0); } public static int last(int a[],int t){ int l = 0,r= a.length-1,ind = -1; while(l<=r){ int mid = (l+r)/2; if(a[mid] == t){ ind = mid; l = mid+1; }else if(a[mid]<t)l = mid+1; else r = mid-1; } return ind; } public static boolean great(String s){ if(s.charAt(1)>=s.charAt(0)){ if(s.charAt(1)>=s.charAt(s.length()-1))return true; } return false; } public static boolean isSorted(int a[]){ for(int i = 0;i<a.length;i++){ if(i+1<a.length && a[i]>a[i+1])return false; } return true; } public static boolean isPrime(int n){ for(int i = 2;i*i<=n;i++){ if(n%i == 0)return false; } return true; } public static int[] fill(String s){ int a[] = new int[s.length()]; for(int i = 0;i<s.length();i++)a[i] = s.charAt(i)-'0'; return a; } public static long factorial(int n){ long fac = 1; for(int i = 1;i<=n;i++)fac*=i; return fac; } public static ArrayList<Integer> factors(int n){ ArrayList<Integer>l = new ArrayList<>(); for(int i = 1;i*i<=n;i++){ if(n%i == 0){ l.add(i); if(n/i != i)l.add(n/i); } } return l; } public static void build(int seg[],int ind,int l,int r,int a[]){ if(l == r){ seg[ind] = a[l]; return; } int mid = (l+r)/2; build(seg,(2*ind)+1,l,mid,a); build(seg,(2*ind)+2,mid+1,r,a); seg[ind] = Math.min(seg[(2*ind)+1],seg[(2*ind)+2]); } public static long gcd(long a, long b){ return b ==0 ?a:gcd(b,a%b); } public static long nearest(TreeSet<Long> list,long target){ long nearest = -1,sofar = Integer.MAX_VALUE; for(long it:list){ if(Math.abs(it - target)<sofar){ sofar = Math.abs(it - target); nearest = it; } } return nearest; } public static ArrayList<Long> factors(long n){ ArrayList<Long>l = new ArrayList<>(); for(long i = 1;i*i<=n;i++){ if(n%i == 0){ l.add(i); if(n/i != i)l.add(n/i); } } Collections.sort(l); return l; } public static void swap(int a[],int i, int j){ int t = a[i]; a[i] = a[j]; a[j] = t; } public static void swap(ArrayList<Integer>l,int i, int j){ int t = l.get(i);l.set(i, l.get(j));l.set(j, t); } public static boolean isSorted(long a[]){ for(int i =0;i<a.length;i++){ if(i+1<a.length && a[i]>a[i+1])return false; } return true; } public static int first(ArrayList<Long>list,long target){ int index = -1; int l = 0,r = list.size()-1; while(l<=r){ int mid = (l+r)/2; if(list.get(mid) == target){ index = mid; r = mid-1; }else if(list.get(mid)>target){ r = mid-1; }else l = mid+1; } return index; } public static int last(ArrayList<Long>list,long target){ int index = -1; int l = 0,r = list.size()-1; while(l<=r){ int mid = (l+r)/2; if(list.get(mid) == target){ index= mid; l = mid+1; }else if(list.get(mid)<target){ l = mid+1; }else r = mid-1; } return index; } public static void sort(int arr[]){ ArrayList<Integer>list = new ArrayList<>(); for(int it:arr)list.add(it); Collections.sort(list); int z = 0; for(int i = 0;i<arr.length;i++)arr[z++] = list.get(i); } static class Pair{ int x,z; int y; public Pair(int x,int y){ this.x = x; this.y = y; } } static class Scanner{ BufferedReader br; StringTokenizer st; public Scanner(){ br = new BufferedReader(new InputStreamReader(System.in)); } public String read() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } public int readInt() { return Integer.parseInt(read()); } public long readLong() { return Long.parseLong(read()); } public double readDouble(){return Double.parseDouble(read());} public String readLine() throws Exception { return br.readLine(); } } }
java
1295
B
B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4 6 10 010010 5 3 10101 1 0 0 2 0 01 OutputCopy3 0 1 -1 NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232.
[ "math", "strings" ]
import java.io.*; import java.math.BigInteger; import java.util.*; /** * * @author eslam */ public class Solution { // Beginning of the solution static Kattio input = new Kattio(); static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); static ArrayList<ArrayList<Integer>> powerSet = new ArrayList<>(); static ArrayList<LinkedList<Integer>> allprem = new ArrayList<>(); static ArrayList<LinkedList<String>> allprems = new ArrayList<>(); static ArrayList<Long> luc = new ArrayList<>(); static long mod = (long) (1e9 + 7); static int grid[][] = {{0, 0, 1, -1, 1, 1, -1, -1}, {1, -1, 0, 0, 1, -1, 1, -1}}; static long dp[][]; static double cmp = 1e-7; static final double pi = 3.14159265359; static long MO = 998244353; static TreeSet<Integer> s = new TreeSet<>(); public static void main(String[] args) throws IOException { // Kattio input = new Kattio("lis.in"); // BufferedWriter log = new BufferedWriter(new FileWriter(f)); int test = input.nextInt(); loop: for (int co = 1; co <= test; co++) { int n = input.nextInt(); int dif = input.nextInt(); int fre[] = new int[n * 2 + 9]; String w = input.next(); int z = 0; int o = 0; fre[n]++; for (int i = 0; i < n; i++) { if (w.charAt(i) == '0') { z++; } else { o++; } fre[(z - o) + n]++; } if (z - o == 0) { if (dif + n < fre.length && dif + n > -1) { if (fre[dif + n] > 0) { log.write("-1\n"); } else { log.write("0\n"); } } else { log.write("0\n"); } } else { int res = 0; int d = z - o; for (int i = 0; i < fre.length; i++) { int e = i - n; int dd = dif - e; if (d == 0) { if (dd == 0) { res += fre[i]; if (e == d) { res--; } } } else if (dd % d == 0) { if ((dd >= 0 && d >= 0) || (dd <= 0 && d <= 0)) { res += fre[i]; if (e == d) { res--; } } } } log.write(res + "\n"); } } log.flush(); } static void dfs(int node, ArrayList<Integer> a[], boolean vi[], List<Boolean> hasApple) { for (Integer x : a[node]) { if (!vi[x]) { dfs(x, a, vi, hasApple); } } } public static int countPrimeInRange(int n, boolean isPrime[]) { int cnt = 0; Arrays.fill(isPrime, true); for (int i = 2; i * i <= n; i++) { if (isPrime[i]) { for (int j = i * 2; j <= n; j += i) { isPrime[j] = false; } } } for (int i = 2; i <= n; i++) { if (isPrime[i]) { cnt++; } } return cnt; } static Comparator<pair> cmpPair() { Comparator<pair> c = new Comparator<pair>() { @Override public int compare(pair o1, pair o2) { if (o1.x > o2.x) { return -1; } else if (o1.x < o2.x) { return 1; } else { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { return 0; } } } }; return c; } static class pair { long x; long y; public pair(long x, long y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } static pai absSub(pai a, pai b) { doWork(a, b); pai c = new pai(Math.abs(a.x - b.x), a.y); simplifyFraction(b); return c; } static int compare(pai a, pai b) { doWork(a, b); if (a.x < b.x) { return -1; } else { return (int) Math.min(1, a.x - b.x); } } static void doWork(pai a, pai b) { simplifyFraction(a); simplifyFraction(b); long c = a.y; a.y *= b.y; a.x *= b.y; b.y *= c; b.x *= c; } static void simplifyFraction(pai b) { long g = GCD(b.x, b.y); b.x /= g; b.y /= g; } static class tri { int x, y; int z; public tri(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } @Override public String toString() { return x + " " + y + " " + z; } } // // public static pair[] dijkstra(int node, ArrayList<pair> a[]) { // PriorityQueue<tri> q = new PriorityQueue<>(new Comparator<tri>() { // @Override // public int compare(tri o1, tri o2) { // if (o1.y > o2.y) { // return 1; // } else if (o1.y < o2.y) { // return -1; // } else { // return 0; // } // } // }); // q.add(new tri(node, 0, -1)); // pair distance[] = new pair[a.length]; // while (!q.isEmpty()) { // tri p = q.poll(); // int cost = p.y; // if (distance[p.x] != null) { // continue; // } // distance[p.x] = new pair(p.z, cost); // ArrayList<pair> nodes = a[p.x]; // for (pair node1 : nodes) { // if (distance[node1.x] == null) { // tri pa = new tri(node1.x, cost + node1.y, p.x); // q.add(pa); // } // } // } // return distance; // } public static boolean isSortedInc(long[] a, int l, int r) { for (int i = l; i <= r; i++) { if (a[i] > a[i + 1]) { return false; } } return true; } public static boolean isSortedDec(long[] a, int l, int r) { for (int i = l; i <= r; i++) { if (a[i] < a[i + 1]) { return false; } } return true; } static long f(long x) { return (long) ((x * (x + 1) / 2) % mod); } static long Sub(long x, long y) { long z = x - y; if (z < 0) { z += mod; } return z; } static long fast_pow(long a, long p, long mod) { long res = 1; while (p > 0) { if (p % 2 == 0) { a = (a * a) % mod; p /= 2; } else { res = (res * a) % mod; p--; } } return res; } static long add(long a, long b) { a += b; if (a >= mod) { a -= mod; } return a; } static long mul(long a, long b) { return (long) ((long) a * b % mod); } static long modinv(long x) { return fast_pow(x, mod - 2, mod); } static long Div(long x, long y) { return mul(x, modinv(y)); } static void floodFill(int r, int c, int a[][], boolean vi[][], int w[][], int d) { vi[r][c] = true; for (int i = 0; i < 4; i++) { int nr = grid[0][i] + r; int nc = grid[1][i] + c; if (isValid(nr, nc, a.length, a[0].length)) { if (Math.abs(a[r][c] - a[nr][nc]) <= d && !vi[nr][nc]) { floodFill(nr, nc, a, vi, w, d); } } } } static boolean isdigit(char ch) { return ch >= '0' && ch <= '9'; } static boolean lochar(char ch) { return ch >= 'a' && ch <= 'z'; } static boolean cachar(char ch) { return ch >= 'A' && ch <= 'Z'; } static class Pa { long x; long y; public Pa(long x, long y) { this.x = x; this.y = y; } } static long sqrt(long v) { long max = (long) 4e9; long min = 0; long ans = 0; while (max >= min) { long mid = (max + min) / 2; if (mid * mid > v) { max = mid - 1; } else { ans = mid; min = mid + 1; } } return ans; } static long cbrt(long v) { long max = (long) 3e6; long min = 0; long ans = 0; while (max >= min) { long mid = (max + min) / 2; if (mid * mid > v) { max = mid - 1; } else { ans = mid; min = mid + 1; } } return ans; } static void prefixSum2D(long arr[][]) { for (int i = 0; i < arr.length; i++) { prefixSum(arr[i]); } for (int i = 0; i < arr[0].length; i++) { for (int j = 1; j < arr.length; j++) { arr[j][i] += arr[j - 1][i]; } } } public static long baseToDecimal(String w, long base) { long r = 0; long l = 0; for (int i = w.length() - 1; i > -1; i--) { long x = (w.charAt(i) - '0') * (long) Math.pow(base, l); r = r + x; l++; } return r; } static int bs(int v, ArrayList<Integer> a) { int max = a.size() - 1; int min = 0; int ans = 0; while (max >= min) { int mid = (max + min) / 2; if (a.get(mid) >= v) { ans = a.size() - mid; max = mid - 1; } else { min = mid + 1; } } return ans; } static Comparator<tri> cmpTri() { Comparator<tri> c = new Comparator<tri>() { @Override public int compare(tri o1, tri o2) { if (o1.x > o2.x) { return 1; } else if (o1.x < o2.x) { return -1; } else { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { if (o1.z > o2.z) { return 1; } else if (o1.z < o2.z) { return -1; } else { return 0; } } } } }; return c; } static Comparator<pair> cmpPair2() { Comparator<pair> c = new Comparator<pair>() { @Override public int compare(pair o1, pair o2) { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { if (o1.x > o2.x) { return -1; } else if (o1.x < o2.x) { return 1; } else { return 0; } } } }; return c; } static class rec { long x1; long x2; long y1; long y2; public rec(long x1, long y1, long x2, long y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } public long getArea() { return (x2 - x1) * (y2 - y1); } } static long sumOfRange(int x1, int y1, int x2, int y2, long a[][]) { return (a[x2][y2] - a[x1 - 1][y2] - a[x2][y1 - 1]) + a[x1 - 1][y1 - 1]; } // public static int[][] bfs(int i, int j, String w[]) { // Queue<pair> q = new ArrayDeque<>(); // q.add(new pair(i, j)); // int dis[][] = new int[w.length][w[0].length()]; // for (int k = 0; k < w.length; k++) { // Arrays.fill(dis[k], -1); // } // dis[i][j] = 0; // while (!q.isEmpty()) { // pair p = q.poll(); // int cost = dis[p.x][p.y]; // for (int k = 0; k < 4; k++) { // int nx = p.x + grid[0][k]; // int ny = p.y + grid[1][k]; // if (isValid(nx, ny, w.length, w[0].length())) { // if (dis[nx][ny] == -1 && w[nx].charAt(ny) == '.') { // q.add(new pair(nx, ny)); // dis[nx][ny] = cost + 1; // } // } // } // } // return dis; // } public static void graphRepresintion(ArrayList<Integer>[] a, int q) throws IOException { for (int i = 0; i < a.length; i++) { a[i] = new ArrayList<>(); } while (q-- > 0) { int x = input.nextInt(); int y = input.nextInt(); a[x].add(y); a[y].add(x); } } public static boolean isValid(int i, int j, int n, int m) { return (i > -1 && i < n) && (j > -1 && j < m); } // present in the left and right indices public static int[] swap(int data[], int left, int right) { // Swap the data int temp = data[left]; data[left] = data[right]; data[right] = temp; // Return the updated array return data; } // Function to reverse the sub-array // starting from left to the right // both inclusive public static int[] reverse(int data[], int left, int right) { // Reverse the sub-array while (left < right) { int temp = data[left]; data[left++] = data[right]; data[right--] = temp; } // Return the updated array return data; } // Function to find the next permutation // of the given integer array public static boolean findNextPermutation(int data[]) { // If the given dataset is empty // or contains only one element // next_permutation is not possible if (data.length <= 1) { return false; } int last = data.length - 2; // find the longest non-increasing suffix // and find the pivot while (last >= 0) { if (data[last] < data[last + 1]) { break; } last--; } // If there is no increasing pair // there is no higher order permutation if (last < 0) { return false; } int nextGreater = data.length - 1; // Find the rightmost successor to the pivot for (int i = data.length - 1; i > last; i--) { if (data[i] > data[last]) { nextGreater = i; break; } } // Swap the successor and the pivot data = swap(data, nextGreater, last); // Reverse the suffix data = reverse(data, last + 1, data.length - 1); // Return true as the next_permutation is done return true; } public static String revs(String w) { String ans = ""; for (int i = w.length() - 1; i > -1; i--) { ans += w.charAt(i); } return ans; } public static boolean isPalindrome(String w) { for (int i = 0; i < w.length() / 2; i++) { if (w.charAt(i) != w.charAt(w.length() - i - 1)) { return false; } } return true; } public static void getPowerSet(Queue<Integer> a) { int n = a.poll(); if (!a.isEmpty()) { getPowerSet(a); } int s = powerSet.size(); for (int i = 0; i < s; i++) { ArrayList<Integer> ne = new ArrayList<>(); ne.add(n); for (int j = 0; j < powerSet.get(i).size(); j++) { ne.add(powerSet.get(i).get(j)); } powerSet.add(ne); } ArrayList<Integer> p = new ArrayList<>(); p.add(n); powerSet.add(p); } public static int getlo(int va) { int v = 1; while (v <= va) { if ((va&v) != 0) { return v; } v <<= 1; } return 0; } public static void create(long num) { luc.add(num); if (num > power(10, 9)) { return; } create(num * 10 + 4); create(num * 10 + 7); } public static long ceil(long a, long b) { return (a + b - 1) / b; } public static long round(long a, long b) { if (a < 0) { return (a - b / 2) / b; } return (a + b / 2) / b; } public static void allPremutationsst(LinkedList<String> l, boolean visited[], ArrayList<String> st) { if (l.size() == st.size()) { allprems.add(l); } for (int i = 0; i < st.size(); i++) { if (!visited[i]) { visited[i] = true; LinkedList<String> nl = new LinkedList<>(); for (String x : l) { nl.add(x); } nl.add(st.get(i)); allPremutationsst(nl, visited, st); visited[i] = false; } } } public static void allPremutations(LinkedList<Integer> l, boolean visited[], int a[]) { if (l.size() == a.length) { allprem.add(l); } for (int i = 0; i < a.length; i++) { if (!visited[i]) { visited[i] = true; LinkedList<Integer> nl = new LinkedList<>(); for (Integer x : l) { nl.add(x); } nl.add(a[i]); allPremutations(nl, visited, a); visited[i] = false; } } } public static int binarySearch(long[] a, long value) { int l = 0; int r = a.length - 1; while (l <= r) { int m = (l + r) / 2; if (a[m] == value) { return m; } else if (a[m] > value) { r = m - 1; } else { l = m + 1; } } return -1; } public static void reverse(int l, int r, char ch[]) { for (int i = 0; i < r / 2; i++) { char c = ch[i]; ch[i] = ch[r - i - 1]; ch[r - i - 1] = c; } } public static long logK(long v, long k) { long ans = 0; while (v > 1) { ans++; v /= k; } return ans; } public static long power(long a, long p) { long res = 1; while (p > 0) { if (p % 2 == 0) { a = (a * a); p /= 2; } else { res = (res * a); p--; } } return res; } public static long get(long max, long x) { if (x == 1) { return max; } int cnt = 0; while (max > 0) { cnt++; max /= x; } return cnt; } public static int numOF0(long v) { long x = 1; int cnt = 0; while (x <= v) { if ((x & v) == 0) { cnt++; } x <<= 1; } return cnt; } public static int log2(double n) { int cnt = 0; while (n > 1) { n /= 2; cnt++; } return cnt; } public static int[] bfs(int node, ArrayList<Integer> a[]) { Queue<Integer> q = new LinkedList<>(); q.add(node); int distances[] = new int[a.length]; Arrays.fill(distances, -1); distances[node] = 0; while (!q.isEmpty()) { int parent = q.poll(); ArrayList<Integer> nodes = a[parent]; int cost = distances[parent]; for (Integer node1 : nodes) { if (distances[node1] == -1) { q.add(node1); distances[node1] = cost + 1; } } } return distances; } public static void primeFactors(int n, HashMap<Integer, ArrayList<Integer>> h, int ind) { boolean ca = true; while (n % 2 == 0) { if (ca) { if (h.get(2) == null) { h.put(2, new ArrayList<>()); } h.get(2).add(ind); ca = false; } n /= 2; } for (int i = 3; i <= Math.sqrt(n); i += 2) { ca = true; while (n % i == 0) { if (ca) { if (h.get(i) == null) { h.put(i, new ArrayList<>()); } h.get(i).add(ind); ca = false; } n /= i; } if (n < i) { break; } } if (n > 2) { if (h.get(n) == null) { h.put(n, new ArrayList<>()); } h.get(n).add(ind); } } // end of solution public static BigInteger ff(long n) { if (n <= 1) { return BigInteger.ONE; } long t = n - 1; BigInteger b = new BigInteger(t + ""); BigInteger ans = new BigInteger(n + ""); while (t > 1) { ans = ans.multiply(b); b = b.subtract(BigInteger.ONE); t--; } return ans; } public static long factorial(long n) { if (n <= 1) { return 1; } long t = n - 1; while (t > 1) { n = mod((mod(n, mod) * mod(t, mod)), mod); t--; } return n; } public static long rev(long n) { long t = n; long ans = 0; while (t > 0) { ans = ans * 10 + t % 10; t /= 10; } return ans; } public static boolean isPalindrome(int n) { int t = n; int ans = 0; while (t > 0) { ans = ans * 10 + t % 10; t /= 10; } return ans == n; } static boolean isPrime(long num) { if (num == 1) { return false; } if (num == 2) { return true; } if (num % 2 == 0) { return false; } if (num == 3) { return true; } for (long i = 3; i * i <= num; i += 2) { if (num % i == 0) { return false; } } return true; } public static void prefixSum(long[] a) { for (int i = 1; i < a.length; i++) { a[i] = a[i] + a[i - 1]; } } public static void suffixSum(long[] a) { for (int i = a.length - 2; i > -1; i--) { a[i] = a[i] + a[i + 1]; } } static long mod(long a, long b) { long r = a % b; return r < 0 ? r + b : r; } public static long binaryToDecimal(String w) { long r = 0; long l = 0; for (int i = w.length() - 1; i > -1; i--) { long x = (w.charAt(i) - '0') * (long) Math.pow(2, l); r = r + x; l++; } return r; } public static String decimalAnyBase(long n, long base) { String w = ""; while (n > 0) { w = n % base + w; n /= base; } return w; } public static String decimalToBinary(long n) { String w = ""; while (n > 0) { w = n % 2 + w; n /= 2; } return w; } public static void print(int[] a) throws IOException { for (int i = 0; i < a.length; i++) { log.write(a[i] + " "); } log.write("\n"); } public static void read(int[] a) { for (int i = 0; i < a.length; i++) { a[i] = input.nextInt(); } } static class gepair { long x; long y; public gepair(long x, long y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } static class pai { long x; long y; public pai(long x, long y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } public static long LCM(long x, long y) { return x / GCD(x, y) * y; } public static long GCD(long x, long y) { if (y == 0) { return x; } return GCD(y, x % y); } public static void simplifyTheFraction(int a, int b) { long GCD = GCD(a, b); System.out.println(a / GCD + " " + b / GCD); } static class Kattio extends PrintWriter { private BufferedReader r; private StringTokenizer st; // standard input public Kattio() { this(System.in, System.out); } public Kattio(InputStream i, OutputStream o) { super(o); r = new BufferedReader(new InputStreamReader(i)); } // USACO-style file input public Kattio(String problemName) throws IOException { super(problemName + ".out"); r = new BufferedReader(new FileReader(problemName)); } // returns null if no more input String nextLine() { String str = ""; try { str = r.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public String next() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(r.readLine()); } return st.nextToken(); } catch (Exception e) { } return null; } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } } }
java
1304
A
A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb. For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5 0 10 2 3 0 10 3 3 900000000 1000000000 1 9999999 1 2 1 1 1 3 1 1 OutputCopy2 -1 10 -1 1 NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward.
[ "math" ]
import java.util.*; public class Solution{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int test_cases = sc.nextInt(); outer : for(int h=0;h<test_cases;h++){ long x = sc.nextLong(); long y = sc.nextLong(); long a = sc.nextLong(); long b = sc.nextLong(); if((y-x)%(a+b)!=0){ System.out.println(-1); } else{ System.out.println((int)(y-x)/(a+b)); } } } public static int calculate_gcd(int x,int y){ int gcd = 1; if(x%y==0){ return y; } else if(y%x==0){ return x; } else{ for(int i=2;i<=x && i<=y;i++){ if(x%i==0 && y%i==0){ gcd = i; } } return gcd; } } public static long calculate_factorial(long x){ long ans = 1; for(int i=1;i<=x;i++){ ans*=i; } return ans; } public static void swap(int a[], int b[], int index_a, int index_b){ int temp = a[index_a]; a[index_a] = b[index_b]; b[index_b] = temp; } public static long find_maximum(long a[]){ long max = Long.MIN_VALUE; for(int i=0;i<a.length;i++){ max = Math.max(a[i], max); } return max; } public static long find_minimum(long a[]){ long min = Long.MAX_VALUE; for(int i=0;i<a.length;i++){ min = Math.min(a[i], min); } return min; } }
java
1324
E
E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai−1ai−1 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1≤n≤2000,3≤h≤2000,0≤l≤r<h1≤n≤2000,3≤h≤2000,0≤l≤r<h) — the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai<h1≤ai<h), where aiai is the number of hours after which Vova goes to sleep the ii-th time.OutputPrint one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.ExampleInputCopy7 24 21 23 16 17 14 20 20 11 22 OutputCopy3 NoteThe maximum number of good times in the example is 33.The story starts from t=0t=0. Then Vova goes to sleep after a1−1a1−1 hours, now the time is 1515. This time is not good. Then Vova goes to sleep after a2−1a2−1 hours, now the time is 15+16=715+16=7. This time is also not good. Then Vova goes to sleep after a3a3 hours, now the time is 7+14=217+14=21. This time is good. Then Vova goes to sleep after a4−1a4−1 hours, now the time is 21+19=1621+19=16. This time is not good. Then Vova goes to sleep after a5a5 hours, now the time is 16+20=1216+20=12. This time is not good. Then Vova goes to sleep after a6a6 hours, now the time is 12+11=2312+11=23. This time is good. Then Vova goes to sleep after a7a7 hours, now the time is 23+22=2123+22=21. This time is also good.
[ "dp", "implementation" ]
import java.io.*; import java.lang.*; import java.util.*; public class ComdeFormces { static int x[]= {0,-1,1,1,1,1,-1,-1}; static int y[]= {-1,0,0,0,1,-1,1,-1}; // static int dp[][][]; static int seg[]; static int E; static class Trie{ Trie a[]; int ind; public Trie() { this.a=new Trie[3]; this.ind=-1; } } static long ncr[][]; static int cst; static HashMap<Integer,Integer> hm; static int dp[][]; static ArrayList<Integer> tp; public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub FastReader sc=new FastReader(); BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); // OutputStream out = new BufferedOutputStream ( System.out ); // int t=sc.nextInt(); int tc=1; // InverseofNumber(m); // InverseofFactorial(m); // factorial(m); // while(tc--!=0) { int n=sc.nextInt(); int h=sc.nextInt(); int l=sc.nextInt(); int r=sc.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++)a[i]=sc.nextInt(); dp=new int[n][h+1]; for(int i=0;i<n;i++)Arrays.fill(dp[i], -1); log.write(eval(a,0,0,h,l,r)+"\n"); log.flush(); } } static int eval(int a[],int i,int ch,int h,int l,int r) { if(i>=a.length)return (ch>=l && ch<=r)?1:0; if(dp[i][ch]!=-1)return dp[i][ch]; return dp[i][ch]=(i>0 && ch>=l && ch<=r?1:0)+Math.max(eval(a,i+1,(ch+a[i]-1+h)%h,h,l,r), eval(a,i+1,(ch+a[i]+h)%h,h,l,r)); } public static int m=(int)(998244353); public static int mul(int a, int b) { return ((a%m)*(b%m))%m; } public static long mul(long a, long b) { return ((a%m)*(b%m))%m; } public static int add(int a, int b) { return ((a%m)+(b%m))%m; } public static long add(long a, long b) { return ((a%m)+(b%m))%m; } public static long sub(long a,long b) { return ((a%m)-(b%m)+m)%m; } static long gcd(long a,long b) { if(b==0)return a; else return gcd(b,a%b); } static int gcd(int a,int b) { if(b==0)return a; else return gcd(b,a%b); } static long ncr(int n, int r){ if(r>n-r)r=n-r; long ans=1; long m=(int)(1e9+7); for(int i=0;i<r;i++){ ans=ans*(n-i); ans/=i+1; } return ans; } public static class num{ long v; } static long gcd(long a,long b,num x,num y) { if(b==0) { x.v=1; y.v=0; return a; } num x1=new num(); num y1=new num(); long ans=gcd(b,a%b,x1,y1); x.v=y1.v; y.v=x1.v-(a/b)*y1.v; return ans; } static long inverse(long b,long m) { num x=new num(); num y=new num(); long gc=gcd(b,m,x,y); if(gc!=1) { return -1; } return (x.v%m+m)%m; } static long div(long a,long b,long m) { a%=m; if(inverse(b,m)==-1)return a/b; return (inverse(b,m)*a)%m; } public static class trip{ int a; int b; long c; int d; public trip(int a,int b,long c,int d) { this.a=a; this.b=b; this.c=c; this.d=d; } } static void mergesort(int[] a,int start,int end) { if(start>=end)return ; int mid=start+(end-start)/2; mergesort(a,start,mid); mergesort(a,mid+1,end); merge(a,start,mid,end); } static void merge(int[] a, int start,int mid,int end) { int ptr1=start; int ptr2=mid+1; int b[]=new int[end-start+1]; int i=0; while(ptr1<=mid && ptr2<=end) { if(a[ptr1]<=a[ptr2]) { b[i]=a[ptr1]; ptr1++; i++; } else { b[i]=a[ptr2]; ptr2++; i++; } } while(ptr1<=mid) { b[i]=a[ptr1]; ptr1++; i++; } while(ptr2<=end) { b[i]=a[ptr2]; ptr2++; i++; } for(int j=start;j<=end;j++) { a[j]=b[j-start]; } } public static class FastReader { BufferedReader b; StringTokenizer s; public FastReader() { b=new BufferedReader(new InputStreamReader(System.in)); } String next() { while(s==null ||!s.hasMoreElements()) { try { s=new StringTokenizer(b.readLine()); } catch(IOException e) { e.printStackTrace(); } } return s.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=b.readLine(); } catch(IOException e) { e.printStackTrace(); } return str; } boolean hasNext() { if (s != null && s.hasMoreTokens()) { return true; } String tmp; try { b.mark(1000); tmp = b.readLine(); if (tmp == null) { return false; } b.reset(); } catch (IOException e) { return false; } return true; } } public static class pair{ int a; int b; public pair(int a,int b) { this.a=a; this.b=b; } @Override public String toString() { return "{"+this.a+" "+this.b+"}"; } } static long pow(long a, long pw) { long temp; if(pw==0)return 1; temp=pow(a,pw/2); if(pw%2==0)return mul(temp,temp); return mul(a,mul(temp,temp)); } public static int md=998244353; static int pow(int a, int pw) { int temp; if(pw==0)return 1; temp=pow(a,pw/2); if(pw%2==0)return temp*temp; return a*temp*temp; } }
java
1295
D
D. Same GCDstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers aa and mm. Calculate the number of integers xx such that 0≤x<m0≤x<m and gcd(a,m)=gcd(a+x,m)gcd(a,m)=gcd(a+x,m).Note: gcd(a,b)gcd(a,b) is the greatest common divisor of aa and bb.InputThe first line contains the single integer TT (1≤T≤501≤T≤50) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains two integers aa and mm (1≤a<m≤10101≤a<m≤1010).OutputPrint TT integers — one per test case. For each test case print the number of appropriate xx-s.ExampleInputCopy3 4 9 5 10 42 9999999967 OutputCopy6 1 9999999966 NoteIn the first test case appropriate xx-s are [0,1,3,4,6,7][0,1,3,4,6,7].In the second test case the only appropriate xx is 00.
[ "math", "number theory" ]
import java.io.*; import java.util.StringTokenizer; public class SameGCDs { public static long gcd(long A, long B) { while (B != 0) { long C = A; A = B; B = C % B; } return A; } public static long phi(long N) { long result = N; for (long i = 2; i * i <= N; i++) { if (N % i == 0) { while (N % i == 0) N /= i; result -= result / i; } } if (N != 1) result -= result / N; return result; } public static void main(String[] args) { InputReader reader = new InputReader(System.in); PrintWriter writer = new PrintWriter(System.out, false); int T = reader.nextInt(); for (int t = 0; t < T; t++) { long A = reader.nextLong(); long M = reader.nextLong(); writer.println(phi(M / gcd(A, M))); } writer.close(); System.exit(0); } 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 String nextLine() { String str = ""; try { str = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
java
1296
E2
E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1≤res≤n1≤res≤n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1≤ci≤res1≤ci≤res and cici means the color of the ii-th character.ExamplesInputCopy9 abacbecfd OutputCopy2 1 1 2 1 2 1 2 1 2 InputCopy8 aaabbcbb OutputCopy2 1 2 1 2 1 2 1 1 InputCopy7 abcdedc OutputCopy3 1 1 1 1 1 2 3 InputCopy5 abcde OutputCopy1 1 1 1 1 1
[ "data structures", "dp" ]
import java.util.*; import java.io.*; public class E617 { public static void main(String [] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); String s = sc.next(); int [] a = new int [n]; for (int i = 0; i < n; i++) { a[i] = (int) s.charAt(i) - 96; } TreeSet<Pair> map = new TreeSet<>(); int [] ret = new int [n]; int cur = 1; for (int i = 0; i < n; i++) { Pair key = map.floor(new Pair(a[i], 1000000)); if (key == null) { map.add(new Pair(a[i], cur)); ret[i] = cur; cur++; } else { int idx = key.second; ret[i] = idx; map.remove(key); map.add(new Pair(a[i], idx)); } } int ans = 0; for (Pair i: map) { ans = Math.max(ans, i.second); } out.println(ans); for (int i = 0; i < n; i++) out.print(ret[i] + " "); out.close(); } static class Pair implements Comparable<Pair> { int first; int second; Pair(int first, int second) { this.first = first; this.second = second; } @Override public int compareTo(Pair o) { if (first == o.first) return second - o.second; return first - o.first; } } //-----------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
1141
D
D. Colored Bootstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn left boots and nn right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings ll and rr, both of length nn. The character lili stands for the color of the ii-th left boot and the character riri stands for the color of the ii-th right boot.A lowercase Latin letter denotes a specific color, but the question mark ('?') denotes an indefinite color. Two specific colors are compatible if they are exactly the same. An indefinite color is compatible with any (specific or indefinite) color.For example, the following pairs of colors are compatible: ('f', 'f'), ('?', 'z'), ('a', '?') and ('?', '?'). The following pairs of colors are not compatible: ('f', 'g') and ('a', 'z').Compute the maximum number of pairs of boots such that there is one left and one right boot in a pair and their colors are compatible.Print the maximum number of such pairs and the pairs themselves. A boot can be part of at most one pair.InputThe first line contains nn (1≤n≤1500001≤n≤150000), denoting the number of boots for each leg (i.e. the number of left boots and the number of right boots).The second line contains the string ll of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th left boot.The third line contains the string rr of length nn. It contains only lowercase Latin letters or question marks. The ii-th character stands for the color of the ii-th right boot.OutputPrint kk — the maximum number of compatible left-right pairs of boots, i.e. pairs consisting of one left and one right boot which have compatible colors.The following kk lines should contain pairs aj,bjaj,bj (1≤aj,bj≤n1≤aj,bj≤n). The jj-th of these lines should contain the index ajaj of the left boot in the jj-th pair and index bjbj of the right boot in the jj-th pair. All the numbers ajaj should be distinct (unique), all the numbers bjbj should be distinct (unique).If there are many optimal answers, print any of them.ExamplesInputCopy10 codeforces dodivthree OutputCopy5 7 8 4 9 2 2 9 10 3 1 InputCopy7 abaca?b zabbbcc OutputCopy5 6 5 2 3 4 6 7 4 1 2 InputCopy9 bambarbia hellocode OutputCopy0 InputCopy10 code?????? ??????test OutputCopy10 6 2 1 6 7 3 3 5 4 8 9 7 5 1 2 4 10 9 8 10
[ "greedy", "implementation" ]
//import java.io.IOException; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; public class DColoredBoots { static InputReader inputReader=new InputReader(System.in); static void solve() { int n=inputReader.nextInt(); // int m=inputReader.nextInt(); String str1=inputReader.readString(); String str2=inputReader.readString(); //HashMap<Character,Stack<Integer>>str1set=new HashMap<>(); HashMap<Character,Stack<Integer>>str2set=new HashMap<>(); for (char c='a';c<='z';c++) { str2set.put(c,new Stack<>()); } str2set.put('?',new Stack<>()); for (int i=0;i<n;i++) { str2set.get(str2.charAt(i)).add(i+1); } List<String>answer=new ArrayList<>(); boolean visited[]=new boolean[n]; boolean visited2[]=new boolean[n]; for (int i=0;i<n;i++) { if (str1.charAt(i)=='?') { continue; } if (str2set.get(str1.charAt(i)).size() > 0) { int popind=str2set.get(str1.charAt(i)).pop(); String str = (i+1)+" "+(popind); answer.add(str); visited[i]=true; visited2[popind-1]=true; } } int ind=0; for (int i=0;i<n;i++) { if (ind==n) { break; } if (str1.charAt(i)=='?') { while (ind<n&&(visited2[ind]==true||str2.charAt(ind)=='?')) { ind++; } if (ind<n) { visited[i]=true; visited2[ind]=true; answer.add((i+1)+" "+(ind+1)); } } } ind=0; for (int i=0;i<n;i++) { if (str2.charAt(i)=='?'&&!visited2[i]) { while (ind<n&&visited[ind]==true) { ind++; } if (ind<n) { answer.add((ind+1)+" "+(i+1)); visited[ind]=true; visited2[i]=true; } } } out.println(answer.size()); for (String ele:answer) { out.println(ele); } } static PrintWriter out=new PrintWriter((System.out)); public static void main(String args[])throws IOException { solve(); out.close(); } static void Sort(int arr[]) { List<Integer>list=new ArrayList<>(); for (int ele:arr) { list.add(ele); } Collections.sort(list); for (int i=0;i<list.size();i++) { arr[i]=list.get(i); } } static void sortDec(int arr[]) { int len=arr.length; List<Integer>list=new ArrayList<>(); for(int ele:arr) { list.add(ele); } Collections.sort(list,Collections.reverseOrder()); for(int i=0;i<len;i++) { arr[i] = list.get(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
java
1325
F
F. Ehab's Last Theoremtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's the year 5555. You have a graph; and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either.Given a connected graph with nn vertices, you can choose to either: find an independent set that has exactly ⌈n−−√⌉⌈n⌉ vertices. find a simple cycle of length at least ⌈n−−√⌉⌈n⌉. An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice. I have a proof you can always solve one of these problems, but it's too long to fit this margin.InputThe first line contains two integers nn and mm (5≤n≤1055≤n≤105, n−1≤m≤2⋅105n−1≤m≤2⋅105) — the number of vertices and edges in the graph.Each of the next mm lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between vertices uu and vv. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.OutputIf you choose to solve the first problem, then on the first line print "1", followed by a line containing ⌈n−−√⌉⌈n⌉ distinct integers not exceeding nn, the vertices in the desired independent set.If you, however, choose to solve the second problem, then on the first line print "2", followed by a line containing one integer, cc, representing the length of the found cycle, followed by a line containing cc distinct integers integers not exceeding nn, the vertices in the desired cycle, in the order they appear in the cycle.ExamplesInputCopy6 6 1 3 3 4 4 2 2 6 5 6 5 1 OutputCopy1 1 6 4InputCopy6 8 1 3 3 4 4 2 2 6 5 6 5 1 1 4 2 5 OutputCopy2 4 1 5 2 4InputCopy5 4 1 2 1 3 2 4 2 5 OutputCopy1 3 4 5 NoteIn the first sample:Notice that you can solve either problem; so printing the cycle 2−4−3−1−5−62−4−3−1−5−6 is also acceptable.In the second sample:Notice that if there are multiple answers you can print any, so printing the cycle 2−5−62−5−6, for example, is acceptable.In the third sample:
[ "constructive algorithms", "dfs and similar", "graphs", "greedy" ]
import java.io.*; import java.util.*; public class CF1325F extends PrintWriter { CF1325F() { super(System.out); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1325F o = new CF1325F(); o.main(); o.flush(); } int[] oo, oj; int __ = 1; int link(int o, int j) { oo[__] = o; oj[__] = j; return __++; } int[] ae, pp, dd; boolean[] bad; int[] qu; int cnt; void init(int n, int m) { oo = new int[1 + m * 2]; oj = new int[1 + m * 2]; ae = new int[n]; pp = new int[n]; dd = new int[n]; Arrays.fill(dd, -1); bad = new boolean[n]; qu = new int[k]; } int n, k; boolean dfs(int p, int i, int d) { pp[i] = p; dd[i] = d; for (int o = ae[i]; o != 0; o = oo[o]) { int j = oj[o]; if (dd[j] == -1) { if (dfs(i, j, d + 1)) return true; } else { int l = d - dd[j] + 1; if (l >= k) { println(2); println(l); while (true) { print(i + 1 + " "); if (i == j) { println(); break; } i = pp[i]; } return true; } } } if (!bad[i] && cnt < k) { qu[cnt++] = i; for (int h = 1; h < k && i >= 0; h++) { bad[i] = true; i = pp[i]; } } return false; } void main() { n = sc.nextInt(); k = (int) Math.sqrt(n); while (k * k < n) k++; int m = sc.nextInt(); init(n, m); while (m-- > 0) { int i = sc.nextInt() - 1; int j = sc.nextInt() - 1; ae[i] = link(ae[i], j); ae[j] = link(ae[j], i); } if (!dfs(-1, 0, 0)) { println(1); for (int h = 0; h < cnt; h++) print(qu[h] + 1 + " "); println(); } } }
java
1141
A
A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.It is easy to prove that any way to transform nn to mm contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers nn and mm (1≤n≤m≤5⋅1081≤n≤m≤5⋅108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840 OutputCopy7 InputCopy42 42 OutputCopy0 InputCopy48 72 OutputCopy-1 NoteIn the first example; the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840.120→240→720→1440→4320→12960→25920→51840. The are 77 steps in total.In the second example, no moves are needed. Thus, the answer is 00.In the third example, it is impossible to transform 4848 to 7272.
[ "implementation", "math" ]
import java.util.*; public class cf17 { public static void main(String arg[]) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int m=sc.nextInt(); int result = -1; if (m % n == 0) { result = 0; int d = m / n; while (d % 2 == 0) { d /= 2; result++; } while (d % 3 == 0) { d /= 3; result++; } if (d != 1) result = -1; } System.out.println(result); } }
java
1301
B
B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer kk (0≤k≤1090≤k≤109) and replaces all missing elements in the array aa with kk.Let mm be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai−ai+1||ai−ai+1| for all 1≤i≤n−11≤i≤n−1) in the array aa after Dark replaces all missing elements with kk.Dark should choose an integer kk so that mm is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1041≤t≤104)  — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer nn (2≤n≤1052≤n≤105) — the size of the array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−1≤ai≤109−1≤ai≤109). If ai=−1ai=−1, then the ii-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of nn for all test cases does not exceed 4⋅1054⋅105.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of mm and an integer kk (0≤k≤1090≤k≤109) that makes the maximum absolute difference between adjacent elements in the array aa equal to mm.Make sure that after replacing all the missing elements with kk, the maximum absolute difference between adjacent elements becomes mm.If there is more than one possible kk, you can print any of them.ExampleInputCopy7 5 -1 10 -1 12 -1 5 -1 40 35 -1 35 6 -1 -1 9 -1 3 -1 2 -1 -1 2 0 -1 4 1 -1 3 -1 7 1 -1 7 5 2 -1 5 OutputCopy1 11 5 35 3 6 0 42 0 0 1 2 3 4 NoteIn the first test case after replacing all missing elements with 1111 the array becomes [11,10,11,12,11][11,10,11,12,11]. The absolute difference between any adjacent elements is 11. It is impossible to choose a value of kk, such that the absolute difference between any adjacent element will be ≤0≤0. So, the answer is 11.In the third test case after replacing all missing elements with 66 the array becomes [6,6,9,6,3,6][6,6,9,6,3,6]. |a1−a2|=|6−6|=0|a1−a2|=|6−6|=0; |a2−a3|=|6−9|=3|a2−a3|=|6−9|=3; |a3−a4|=|9−6|=3|a3−a4|=|9−6|=3; |a4−a5|=|6−3|=3|a4−a5|=|6−3|=3; |a5−a6|=|3−6|=3|a5−a6|=|3−6|=3. So, the maximum difference between any adjacent elements is 33.
[ "binary search", "greedy", "ternary search" ]
//Some of the methods are copied from GeeksforGeeks Website import java.util.*; import java.lang.*; import java.io.*; public class Main { //static Scanner sc=new Scanner(System.in); static Reader sc=new Reader(); // static FastReader sc=new FastReader(System.in); static long mod = (long)(1e9)+ 7; static int max_num=(int)1e5+5; public static void main (String[] args) throws java.lang.Exception { try{ /* Collections.sort(al,(a,b)->a.x-b.x); Collections.sort(al,Collections.reverseOrder()); long n=sc.nextLong(); String s=sc.next(); char a[]=s.toCharArray(); StringBuilder sb=new StringBuilder(); map.put(a[i],map.getOrDefault(a[i],0)+1); */ int t = sc.nextInt(); for(int tt=1;tt<=t;tt++) { int n=sc.nextInt(); long min=long_max,max=long_min; long a[]=new long[n]; for(int i=0;i<n;i++) { a[i]=sc.nextLong(); } for(int i=0;i<n-1;i++) { if(a[i]==-1 && a[i+1]!=-1) { min=Math.min(min,a[i+1]); max=Math.max(max,a[i+1]); } } for(int i=0;i<n-1;i++) { if(a[i]!=-1 && a[i+1]==-1) { min=Math.min(min,a[i]); max=Math.max(max,a[i]); } } long ans=(min+max)/2,res=0; for(int i=0;i<n;i++) if(a[i]==-1) a[i]=ans; for(int i=0;i<n-1;i++) { res=Math.max(res,Math.abs(a[i+1]-a[i])); } out.println(res+" "+ans); } out.flush(); out.close(); } catch(Exception e) {} } /* ...SOLUTION ENDS HERE...........SOLUTION ENDS HERE... */ static void flag(boolean flag) { out.println(flag ? "YES" : "NO"); out.flush(); } /* Map<Long,Long> map=new HashMap<>(); for(int i=0;i<n;i++) { if(!map.containsKey(a[i])) map.put(a[i],1); else map.replace(a[i],map.get(a[i])+1); } Set<Map.Entry<Long,Long>> hmap=map.entrySet(); for(Map.Entry<Long,Long> data : hmap) { } Iterator<Integer> itr = set.iterator(); while(itr.hasNext()) { int val=itr.next(); } */ // static class Pair // { // int x,y; // Pair(int x,int y) // { // this.x=x; // this.y=y; // } // } // Arrays.sort(p, new Comparator<Pair>() // { // @Override // public int compare(Pair o1,Pair o2) // { // if(o1.x>o2.x) return 1; // else if(o1.x==o2.x) // { // if(o1.y>o2.y) return 1; // else return -1; // } // else return -1; // }}); static void print(int a[]) { int n=a.length; for(int i=0;i<n;i++) { out.print(a[i]+" "); } out.println(); out.flush(); } static void print(long a[]) { int n=a.length; for(int i=0;i<n;i++) { out.print(a[i]+" "); } out.println(); out.flush(); } static void print_int(ArrayList<Integer> al) { int si=al.size(); for(int i=0;i<si;i++) { out.print(al.get(i)+" "); } out.println(); out.flush(); } static void print_long(ArrayList<Long> al) { int si=al.size(); for(int i=0;i<si;i++) { out.print(al.get(i)+" "); } out.println(); out.flush(); } static int LowerBound(int a[], int x) { // x is the target value or key int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]>=x) r=m; else l=m; } return r; } static int UpperBound(int a[], int x) {// x is the key or target value int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]<=x) l=m; else r=m; } return l+1; } static void DFS(ArrayList<Integer> graph[],boolean[] visited, int u) { visited[u]=true; int v=0; for(int i=0;i<graph[u].size();i++) { v=graph[u].get(i); if(!visited[v]) DFS(graph,visited,v); } } static boolean[] prime(int num) { boolean[] bool = new boolean[num]; for (int i = 0; i< bool.length; i++) { bool[i] = true; } for (int i = 2; i< Math.sqrt(num); i++) { if(bool[i] == true) { for(int j = (i*i); j<num; j = j+i) { bool[j] = false; } } } if(num >= 0) { bool[0] = false; bool[1] = false; } return bool; } static long nCr(long a,long b,long mod) { return (((fact[(int)a] * modInverse(fact[(int)b],mod))%mod * modInverse(fact[(int)(a - b)],mod))%mod + mod)%mod; } static long fact[]=new long[max_num]; static void fact_fill() { fact[0]=1l; for(int i=1;i<max_num;i++) { fact[i]=(fact[i-1]*(long)i); if(fact[i]>=mod) fact[i]%=mod; } } static long modInverse(long a, long m) { return power(a, m - 2, m); } static long power(long x, long y, long m) { if (y == 0) return 1; long p = power(x, y / 2, m) % m; p = (long)((p * (long)p) % m); if (y % 2 == 0) return p; else return (long)((x * (long)p) % m); } static long sum_array(int a[]) { int n=a.length; long sum=0; for(int i=0;i<n;i++) sum+=a[i]; return sum; } static long sum_array(long a[]) { int n=a.length; long sum=0; for(int i=0;i<n;i++) sum+=a[i]; return sum; } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void sort(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void reverse_array(int a[]) { int n=a.length; int i,t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } static void reverse_array(long a[]) { int n=a.length; int i; long t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b%a, a); } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } static class FastReader{ byte[] buf = new byte[2048]; int index, total; InputStream in; FastReader(InputStream is) { in = is; } int scan() throws IOException { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) { return -1; } } return buf[index++]; } String next() throws IOException { int c; for (c = scan(); c <= 32; c = scan()); StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) { sb.append((char) c); } return sb.toString(); } int nextInt() throws IOException { int c, val = 0; for (c = scan(); c <= 32; c = scan()); boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } long nextLong() throws IOException { int c; long val = 0; for (c = scan(); c <= 32; c = scan()); boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static PrintWriter out=new PrintWriter(System.out); static int int_max=Integer.MAX_VALUE; static int int_min=Integer.MIN_VALUE; static long long_max=Long.MAX_VALUE; static long long_min=Long.MIN_VALUE; } // Thank You !
java
1291
B
B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10 1 248618 3 12 10 8 6 100 11 15 9 7 8 4 0 1 1 0 2 0 0 2 0 1 2 1 0 2 1 1 3 0 1 0 3 1 0 1 OutputCopyYes Yes Yes No No Yes Yes Yes Yes No NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened.
[ "greedy", "implementation" ]
import java.util.*; import java.io.*; public class A { static class Pair { long x; long y; public Pair(long x, long y) { this.x = x; this.y = y; } } static long gcd(long n, long m) { if (m == 0) return n; else return gcd(m, n % m); } static long lcm(long n, long m) { return (n * m) / gcd(n, m); } static void dfs(ArrayList<ArrayList<Integer>> adj, int s, int[] vis, int[] cnt) { for (int i : adj.get(s)) { if (vis[i] == 1) { continue; } cnt[0]++; vis[i] = 1; dfs(adj, i, vis, cnt); } } public static long solve(long a, long b, long x, long y, long n) { if (a - n >= x) { return ((a - n) * b); } else { n -= a - x; a = x; if (b - n >= y) { return (a * (b - n)); } else { b = y; return (a * b); } } } static int high(int n) { int p = (int) (Math.log(n) / Math.log(2)); return (int) Math.pow(2, p); } static void reverseandflip(char[] s1, int pos) { int i = 0; int j = pos; while (i <= j) { if (s1[i] == s1[j]) { if (s1[i] == '1') { s1[i] = '0'; s1[j] = '0'; } else { s1[i] = '1'; s1[j] = '1'; } } i++; j--; } } static int bs(ArrayList<Integer> pow, long target) { int low = 0; int idx = -1; int high = pow.size() - 1; while (low <= high) { int mid = (low + high) / 2; if (pow.get(mid) <= target) { low = mid + 1; idx = mid; } else { high = mid - 1; } } return idx; } static boolean prime(int n) { int m = (int) Math.sqrt(n); for (int i = 2; i <= m; i++) if (n % i == 0) return false; return true; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); StringBuilder str = new StringBuilder(); int t = sc.nextInt(); for (int xx = 0; xx < t; xx++) { int n = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } boolean ok = true; boolean ok1 = true; for (int i = 0; i < n; i++) { if (arr[i] < n - i - 1) ok1 = false; } int a = 0; arr[0] = 0; for (int i = 0; i < n; i++) { if (arr[i] >= i && a == 0) { continue; } a++; if(a==1) i--; if (arr[i] < n - i - 1) ok = false; } if (ok || ok1) str.append("Yes" + "\n"); else str.append("No" + "\n"); } System.out.println(str); sc.close(); } }
java
1285
C
C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2 OutputCopy1 2 InputCopy6 OutputCopy2 3 InputCopy4 OutputCopy1 4 InputCopy1 OutputCopy1 1
[ "brute force", "math", "number theory" ]
// import java.io.BufferedReader; // import java.io.InputStreamReader; // public class Main{ // static int m=(int)1e9+7; // public static void main(String[] args) throws Exception{ // BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); // int t=Integer.parseInt(br.readLine()); // while(t-->0){ // String[] in=br.readLine().split(" "); // int a=Integer.parseInt(in[0]); // int b=Integer.parseInt(in[1]); // int c=Integer.parseInt(in[2]); // // System.out.println(expo(b,c,m-1)); // System.out.println(expo(a,expo(b,c,m-1),m)); // } // } // static int expo(int a,int b,int c){ // if(a==0 && b==0) return 1; // long res=1; // long x=a; // while(b>0){ // if((b&1)==1){ // res=(x*res)%c; // } // x=(x*x)%c; // b=b>>1; // } // return (int)(res%c); // } // } import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class Main { static long mod = (long) 1e9 + 7; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); long t=Long.parseLong(br.readLine()); // while(t-->0){ // } long ans=1; long n=(long)t; long num1=1; long num2=n; for(long i=1;i*i<=n;i++){ if(n%i==0){ if(gcd(i,n/i)==1){ num1=i; num2=n/i; } } } System.out.print(num1+" "+num2); } static long n_of_factors(long[][] a) { long ans = 1; for (int i = 0; i < a.length; i++) { ans = ans * (a[i][1] + 1) % mod; } return ans % mod; } static long sum_of_factors(long[][] a) { long ans = 1; for (int i = 0; i < a.length; i++) { long res = (((expo(a[i][0], a[i][1] + 1) - 1) % mod) * (modular_inverse(a[i][0] - 1)) % mod) % mod; ans = ((res % mod) * (ans % mod)) % mod; } return (ans % mod); } static long prod_of_divisors(long[][] a) { long ans = 1; long d = 1; for (int i = 0; i < a.length; i++) { long res = expo(a[i][0], (a[i][1] * (a[i][1] + 1) / 2)); ans = ((expo(ans, a[i][1] + 1) % mod) * (expo(res, d) % mod)) % mod; d = (d * (a[i][1] + 1)) % (mod - 1); } return ans % mod; } static long expo(long a, long b) { long ans = 1; a = a % mod; while (b > 0) { if ((b & 1) == 1) { ans = ans * a % mod; } a = a * a % mod; b >>= 1; } return ans % mod; } static long modular_inverse(long a) { return expo(a, mod - 2) % mod; } static long phin(long a) { if (isPrime(a)) return a - 1; long res = a; for (int i = 2; i * i <= (int) a; i++) { if (a % i == 0) { while (a % i == 0) { a = a / i; } res -= res / i; } } if (a > 1) { res -= res / a; } return res; } static boolean isPrime(long a) { if (a < 2) return false; for (int i = 2; i * i <= (int) a; i++) { if (a % i == 0) return false; } return true; } static long catlan(long a) { long ans = 1; for (int i = 1; i <= a; i++) { ans = ans * (4 * i - 2) % mod; ans = ((ans % mod) * modular_inverse(i + 1)) % mod; } return ans % mod; } static HashMap<Long, Long> primeFactors(long n) { HashMap<Long, Long> m1 = new HashMap<>(); for (int i = 2; (long) i * (long) i <= n; i++) { if (n % i == 0) { while (n % i == 0) { m1.put((long) i, m1.getOrDefault(i, 0l) + 1); n = n / i; } } } return m1; } static long gcd(long a,long b){ a=Math.abs(a); b=Math.abs(b); if(b==0) return a; return gcd(b,a%b); } // } }
java
1293
A
A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5 5 2 3 1 2 3 4 3 3 4 1 2 10 2 6 1 2 3 4 5 7 2 1 1 2 100 76 8 76 75 36 67 41 74 10 77 OutputCopy2 0 4 0 2 NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor.
[ "binary search", "brute force", "implementation" ]
import java.io.*; import java.util.*; import java.lang.*; public class Codeforces{ public static void main(String[] args) { Scanner input= new Scanner(System.in); int test=input.nextInt(); while(test-->0) { int n=input.nextInt(),s=input.nextInt(),k=input.nextInt(); List<Integer> a=new ArrayList<>(); while(k--!=0) { a.add(input.nextInt()); } int d=0; for(int i=0;i<n;i++) { int x=s-i; int y=s+i; if(x>0 && !a.contains(x)) { d=i; break; } if(y<n+1 && !a.contains(y)) { d=i; break; } } System.out.println(d); } } }
java
1304
B
B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has nn distinct strings of equal length mm. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers nn and mm (1≤n≤1001≤n≤100, 1≤m≤501≤m≤50) — the number of strings and the length of each string.Next nn lines contain a string of length mm each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInputCopy3 3 tab one bat OutputCopy6 tabbat InputCopy4 2 oo ox xo xx OutputCopy6 oxxxxo InputCopy3 5 hello codef orces OutputCopy0 InputCopy9 4 abab baba abcd bcde cdef defg wxyz zyxw ijji OutputCopy20 ababwxyzijjizyxwbaba NoteIn the first example; "battab" is also a valid answer.In the second example; there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example; the empty string is the only valid palindrome string.
[ "brute force", "constructive algorithms", "greedy", "implementation", "strings" ]
import java.util.HashSet; import java.util.Scanner; public class LongestPalindrome { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); String arr[] = new String [n]; for(int i=0;i<n;i++){ arr[i]= sc.next(); } HashSet<String>s1 = new HashSet<>(); HashSet<String>s2 = new HashSet<>(); for(int i=0;i<n;i++){ String rev = reverse(arr[i]); if(!s1.contains(arr[i])&&!s1.contains(rev)){ s1.add(arr[i]); }else if(s1.contains(rev)&&!s2.contains(arr[i])){ s2.add(arr[i]); } } String fs =""; String ls =""; for(String key:s2){ String rev = reverse(key); if(s1.contains(rev)){ fs+=rev; ls=key+ls; } } String mid =""; for(String s:s1){ if(!s2.contains(s)) if(isPalindrome(s)){ mid = s; break; } } String ans = fs+mid+ls; System.out.println(ans.length()); System.out.println(ans); } private static boolean isPalindrome(String s) { int i=0; int j=s.length()-1; while(i<j){ if(s.charAt(i)!=s.charAt(j)){ return false; } i++; j--; } return true; } private static String reverse(String s) { String ans = ""; for(int i=s.length()-1;i>=0;i--){ ans+=s.charAt(i); } return ans; } }
java
1300
B
B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3 1 1 1 3 6 5 4 1 2 3 5 13 4 20 13 2 5 8 3 17 16 OutputCopy0 1 5 NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference.
[ "greedy", "implementation", "sortings" ]
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t>0){ t--; int n=sc.nextInt(); int[] arr=new int[2*n]; for(int i=0;i<2*n;i++){ arr[i]=sc.nextInt(); } Arrays.sort(arr); System.out.println(arr[n]-arr[n-1]); } } }
java
1315
A
A. Dead Pixeltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputScreen resolution of Polycarp's monitor is a×ba×b pixels. Unfortunately, there is one dead pixel at his screen. It has coordinates (x,y)(x,y) (0≤x<a,0≤y<b0≤x<a,0≤y<b). You can consider columns of pixels to be numbered from 00 to a−1a−1, and rows — from 00 to b−1b−1.Polycarp wants to open a rectangular window of maximal size, which doesn't contain the dead pixel. The boundaries of the window should be parallel to the sides of the screen.Print the maximal area (in pixels) of a window that doesn't contain the dead pixel inside itself.InputIn the first line you are given an integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. In the next lines you are given descriptions of tt test cases.Each test case contains a single line which consists of 44 integers a,b,xa,b,x and yy (1≤a,b≤1041≤a,b≤104; 0≤x<a0≤x<a; 0≤y<b0≤y<b) — the resolution of the screen and the coordinates of a dead pixel. It is guaranteed that a+b>2a+b>2 (e.g. a=b=1a=b=1 is impossible).OutputPrint tt integers — the answers for each test case. Each answer should contain an integer equal to the maximal possible area (in pixels) of a rectangular window, that doesn't contain the dead pixel.ExampleInputCopy6 8 8 0 0 1 10 0 3 17 31 10 4 2 1 0 0 5 10 3 9 10 10 4 8 OutputCopy56 6 442 1 45 80 NoteIn the first test case; the screen resolution is 8×88×8, and the upper left pixel is a dead pixel. Here you can see one of two possible layouts of the maximal window.
[ "implementation" ]
import java.io.*; import java.util.*; public class DeadPixel { public static void main(String[] args)throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine().trim()); int t=Integer.parseInt(st.nextToken()); for(int e=1;e<=t;e++) { st=new StringTokenizer(br.readLine()); int a=Integer.parseInt(st.nextToken()); int b=Integer.parseInt(st.nextToken()); int x=Integer.parseInt(st.nextToken()); int y=Integer.parseInt(st.nextToken()); PriorityQueue<Integer> maxPq=new PriorityQueue<>(Collections.reverseOrder()); maxPq.add(x*b); maxPq.add((a-x-1)*b); maxPq.add((b-y-1)*a); maxPq.add(y*a); System.out.println(maxPq.peek()); } } }
java
1312
D
D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4 OutputCopy6 InputCopy3 5 OutputCopy10 InputCopy42 1337 OutputCopy806066790 InputCopy100000 200000 OutputCopy707899035 NoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3].
[ "combinatorics", "math" ]
//package Codeforces; import java.io.*; import java.util.*; public class CountTheArrays { static long mod = 998244353; static long[] fact; static long[] inverse; static long pow(long a, long b){ if(b<0) return 0; long p = 1; while(b > 0){ if(b%2==1) p = (p*a)%mod; a = (a * a)%mod; b /= 2; } return p; } static void preCompute(int n){ fact = new long[n]; inverse = new long[n]; fact[0] = 1; inverse[0] = 1; for(int i=1;i<n;i++){ fact[i] = (fact[i-1] * i)%mod; inverse[i] = pow(fact[i], mod-2); } } static long nCr(int n, int r){ if(n < 0 || r < 0) return 0; long num = fact[n]; long deno = (inverse[n-r] * inverse[r])%mod; num = (num * deno)%mod; return num; } public static void main(String[] args) throws IOException { Soumit sc = new Soumit(); int n = sc.nextInt(); int m = sc.nextInt(); preCompute(m+20); long ans = 0; for(int i=n-1;i<=m;i++){ long cur = (((long) i-1) * ((nCr(i-2, n-3) * pow(2, n-3))%mod))%mod; ans = (ans + cur)%mod; } System.out.println(ans); sc.close(); } static class Soumit { final private int BUFFER_SIZE = 1 << 18; final private DataInputStream din; final private byte[] buffer; private PrintWriter pw; private int bufferPointer, bytesRead; StringTokenizer st; public Soumit() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Soumit(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public void streamOutput(String file) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); pw = new PrintWriter(bw); } public void println(String a) { pw.println(a); } public void print(String a) { pw.print(a); } public String readLine() throws IOException { byte[] buf = new byte[3000064]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public void sort(int[] arr) { ArrayList<Integer> arlist = new ArrayList<>(); for (int i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public void sort(long[] arr) { ArrayList<Long> arlist = new ArrayList<>(); for (long i : arr) arlist.add(i); Collections.sort(arlist); for (int i = 0; i < arr.length; i++) arr[i] = arlist.get(i); } public int[] nextIntArray(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) throws IOException { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } public double[] nextDoubleArray(int n) throws IOException { double[] arr = new double[n]; for (int i = 0; i < n; i++) { arr[i] = nextDouble(); } return arr; } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { /*if (din == null) return;*/ if (din != null) din.close(); if (pw != null) pw.close(); } } }
java
1301
B
B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer kk (0≤k≤1090≤k≤109) and replaces all missing elements in the array aa with kk.Let mm be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai−ai+1||ai−ai+1| for all 1≤i≤n−11≤i≤n−1) in the array aa after Dark replaces all missing elements with kk.Dark should choose an integer kk so that mm is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1041≤t≤104)  — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer nn (2≤n≤1052≤n≤105) — the size of the array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−1≤ai≤109−1≤ai≤109). If ai=−1ai=−1, then the ii-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of nn for all test cases does not exceed 4⋅1054⋅105.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of mm and an integer kk (0≤k≤1090≤k≤109) that makes the maximum absolute difference between adjacent elements in the array aa equal to mm.Make sure that after replacing all the missing elements with kk, the maximum absolute difference between adjacent elements becomes mm.If there is more than one possible kk, you can print any of them.ExampleInputCopy7 5 -1 10 -1 12 -1 5 -1 40 35 -1 35 6 -1 -1 9 -1 3 -1 2 -1 -1 2 0 -1 4 1 -1 3 -1 7 1 -1 7 5 2 -1 5 OutputCopy1 11 5 35 3 6 0 42 0 0 1 2 3 4 NoteIn the first test case after replacing all missing elements with 1111 the array becomes [11,10,11,12,11][11,10,11,12,11]. The absolute difference between any adjacent elements is 11. It is impossible to choose a value of kk, such that the absolute difference between any adjacent element will be ≤0≤0. So, the answer is 11.In the third test case after replacing all missing elements with 66 the array becomes [6,6,9,6,3,6][6,6,9,6,3,6]. |a1−a2|=|6−6|=0|a1−a2|=|6−6|=0; |a2−a3|=|6−9|=3|a2−a3|=|6−9|=3; |a3−a4|=|9−6|=3|a3−a4|=|9−6|=3; |a4−a5|=|6−3|=3|a4−a5|=|6−3|=3; |a5−a6|=|3−6|=3|a5−a6|=|3−6|=3. So, the maximum difference between any adjacent elements is 33.
[ "binary search", "greedy", "ternary search" ]
//<———My cp———— //https://takeuforward.org/interview-experience/strivers-cp-sheet/?utm_source=youtube&utm_medium=striver&utm_campaign=yt_video import java.util.*; import java.io.*; public class Solution{ static PrintWriter pw = new PrintWriter(System.out); static FastReader fr = new FastReader(System.in); private static long MOD = 1_000_000_007; public static void main(String[] args) throws Exception{ int t = fr.nextInt(); while(t-->0){ int n = fr.nextInt(); int[] vals = new int[n]; int spaceC = 0 ; for(int i = 0;i<n;i++){ vals[i] = fr.nextInt(); if(vals[i]==-1){ spaceC++; } } if(spaceC==n){ pw.println(0+" "+0); }else{ long minElement = Integer.MAX_VALUE; long maxValue = Integer.MIN_VALUE; for(int i =0;i<n;i++){ if(vals[i]==-1){ if(i!=n-1 && vals[i+1]!=-1){ minElement = Math.min(vals[i+1], minElement); maxValue = Math.max(vals[i+1], maxValue); } if(i!=0 && vals[i-1]!=-1){ minElement = Math.min(vals[i-1], minElement); maxValue = Math.max(vals[i-1], maxValue); } } } long lowMid = (maxValue+minElement)/2; long highMid = (maxValue+minElement+1)/2; long lowDiff = calc(vals,lowMid); long highDiff = calc(vals, highMid); if(lowDiff<highDiff){ pw.println(lowDiff+" "+lowMid); }else{ pw.println(highDiff+" "+highMid); } } } pw.close(); } public static long calc(int[] vals,long mid){ long maxDiff = 0; for (int i = 0; i < vals.length-1; i++) { long a = vals[i]; long b = vals[i+1]; if(a==-1){ a=mid; } if(b==-1){ b=mid; } maxDiff=Math.max(Math.abs(a-b), maxDiff); } return maxDiff; } public static boolean poss(int[][] mat,int r,int c,int n){ if(r<0||c<0||r>=n||c>=n||mat[r][c]!=0){ return false; } return true; } static class Pair{ int min; int max; public Pair(int min,int max){ this.min = min; this.max = max; } @Override public String toString() { return "min: "+min+" max: "+max; } } public static long opNeeded(long c,long[] vals){ long tempResult = 0; for(int j = 0;j<vals.length;j++){ tempResult=tempResult+Math.abs((long)(vals[j]-Math.pow(c,j))); } if(tempResult<0){ tempResult=Long.MAX_VALUE; } return tempResult; } static int isPerfectSquare(int vals){ int lastPow=1; while(lastPow*lastPow<vals){ lastPow++; } if(lastPow*lastPow==vals){ return lastPow*lastPow; }else{ return -1; } } public static int[] sort(int[] vals){ ArrayList<Integer> values = new ArrayList<>(); for(int i = 0;i<vals.length;i++){ values.add(vals[i]); } Collections.sort(values); for(int i =0;i<values.size();i++){ vals[i] = values.get(i); } return vals; } public static long[] sort(long[] vals){ ArrayList<Long> values = new ArrayList<>(); for(int i = 0;i<vals.length;i++){ values.add(vals[i]); } Collections.sort(values); for(int i =0;i<values.size();i++){ vals[i] = values.get(i); } return vals; } public static void reverseArray(long[] vals){ int startIndex = 0; int endIndex = vals.length-1; while(startIndex<=endIndex){ long temp = vals[startIndex]; vals[startIndex] = vals[endIndex]; vals[endIndex] = temp; startIndex++; endIndex--; } } public static void reverseArray(int[] vals){ int startIndex = 0; int endIndex = vals.length-1; while(startIndex<=endIndex){ int temp = vals[startIndex]; vals[startIndex] = vals[endIndex]; vals[endIndex] = temp; startIndex++; endIndex--; } } static class FastReader{ byte[] buf = new byte[2048]; int index, total; InputStream in; FastReader(InputStream is) { in = is; } int scan() throws IOException { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) { return -1; } } return buf[index++]; } String next() throws IOException { int c; for (c = scan(); c <= 32; c = scan()); StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) { sb.append((char) c); } return sb.toString(); } int nextInt() throws IOException { int c, val = 0; for (c = scan(); c <= 32; c = scan()); boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } long nextLong() throws IOException { int c; long val = 0; for (c = scan(); c <= 32; c = scan()); boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } } public static int GCD(int numA, int numB){ if(numA==0){ return numB; }else if(numB==0){ return numA; }else{ if(numA>numB){ return GCD(numA%numB,numB); }else{ return GCD(numA,numB%numA); } } } }
java
1316
A
A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers 0≤ai≤m0≤ai≤m The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105)  — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m)  — scores of the students.OutputFor each testcase, output one integer  — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2 4 10 1 2 3 4 4 5 1 2 3 4 OutputCopy10 5 NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m.
[ "implementation" ]
import java.util.Scanner; public class codeforces1316A { public static void main(String[] args) { Scanner s=new Scanner(System.in); StringBuilder sb=new StringBuilder(); int t=s.nextInt(),i,n,m,sum; while(t-->0) { n=s.nextInt(); m=s.nextInt(); sum=0; int[] a = new int[n]; for(i=0;i<n;i++) { a[i]=s.nextInt(); sum=sum+a[i]; } sb.append(Math.min(m,sum)+"\n"); } System.out.print(sb); } }
java
1305
B
B. Kuroni and Simple Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNow that Kuroni has reached 10 years old; he is a big boy and doesn't like arrays of integers as presents anymore. This year he wants a Bracket sequence as a Birthday present. More specifically, he wants a bracket sequence so complex that no matter how hard he tries, he will not be able to remove a simple subsequence!We say that a string formed by nn characters '(' or ')' is simple if its length nn is even and positive, its first n2n2 characters are '(', and its last n2n2 characters are ')'. For example, the strings () and (()) are simple, while the strings )( and ()() are not simple.Kuroni will be given a string formed by characters '(' and ')' (the given string is not necessarily simple). An operation consists of choosing a subsequence of the characters of the string that forms a simple string and removing all the characters of this subsequence from the string. Note that this subsequence doesn't have to be continuous. For example, he can apply the operation to the string ')()(()))', to choose a subsequence of bold characters, as it forms a simple string '(())', delete these bold characters from the string and to get '))()'. Kuroni has to perform the minimum possible number of operations on the string, in such a way that no more operations can be performed on the remaining string. The resulting string does not have to be empty.Since the given string is too large, Kuroni is unable to figure out how to minimize the number of operations. Can you help him do it instead?A sequence of characters aa is a subsequence of a string bb if aa can be obtained from bb by deletion of several (possibly, zero or all) characters.InputThe only line of input contains a string ss (1≤|s|≤10001≤|s|≤1000) formed by characters '(' and ')', where |s||s| is the length of ss.OutputIn the first line, print an integer kk  — the minimum number of operations you have to apply. Then, print 2k2k lines describing the operations in the following format:For each operation, print a line containing an integer mm  — the number of characters in the subsequence you will remove.Then, print a line containing mm integers 1≤a1<a2<⋯<am1≤a1<a2<⋯<am  — the indices of the characters you will remove. All integers must be less than or equal to the length of the current string, and the corresponding subsequence must form a simple string.If there are multiple valid sequences of operations with the smallest kk, you may print any of them.ExamplesInputCopy(()(( OutputCopy1 2 1 3 InputCopy)( OutputCopy0 InputCopy(()()) OutputCopy1 4 1 2 5 6 NoteIn the first sample; the string is '(()(('. The operation described corresponds to deleting the bolded subsequence. The resulting string is '((('; and no more operations can be performed on it. Another valid answer is choosing indices 22 and 33, which results in the same final string.In the second sample, it is already impossible to perform any operations.
[ "constructive algorithms", "greedy", "strings", "two pointers" ]
import java.io.*; import java.lang.reflect.Array; import java.util.*; public class edu130 { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } 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()); } String nextLine() { String str = ""; try { str = br.readLine().trim(); } catch (Exception e) { e.printStackTrace(); } return str; } } static class FastWriter { private final BufferedWriter bw; public FastWriter() { this.bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(Object object) throws IOException { bw.append("" + object); } public void println(Object object) throws IOException { print(object); bw.append("\n"); } public void close() throws IOException { bw.close(); } } public static boolean func(long x,long k){ return (k-((x*x)+(x)+1))%(2*x)==0; } public static void main(String[] args) { //RSRRSRSSSR try { FastReader sc = new FastReader(); FastWriter out = new FastWriter(); String s=sc.next(); ArrayList<Integer> ff=new ArrayList<>(); ArrayList<Integer> ss=new ArrayList<>(); int i=0; int j=s.length()-1; while(i<j){ if(s.charAt(i)=='(' && s.charAt(j)==')'){ ff.add(i); ss.add(j); i++; j--; } else if(s.charAt(i)=='(' && s.charAt(j)=='('){ j--; } else if(s.charAt(i)==')' && s.charAt(j)==')'){ i++; }else{ i++; j--; } } if(ff.size()==0){ System.out.println(0); }else { System.out.println(1); System.out.println(ff.size() + ss.size()); int fd = 0; int sd = ss.size() - 1; while (fd < ff.size()) { System.out.print((ff.get(fd++) + 1) + " "); } while (sd >= 0) { System.out.print((ss.get(sd--) + 1) + " "); } } }catch(Exception e){ return; } } private static void swap(long[] arr, int i, int ii) { long temp=arr[i]; arr[i]=arr[ii]; arr[ii]=temp; } public static int lcm(int a,int b){ return (a/gcd(a,b))*b; } private static int gcd(int a, int b) { if(b==0)return a; return gcd(b,a%b); } static class Pair { int a; int b; Pair(int a, int b) { this.a = a; this.b = b; } } }
java
1316
D
D. Nash Matrixtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputNash designed an interesting yet simple board game where a player is simply required to follow instructions written on the cell where the player currently stands. This board game is played on the n×nn×n board. Rows and columns of this board are numbered from 11 to nn. The cell on the intersection of the rr-th row and cc-th column is denoted by (r,c)(r,c).Some cells on the board are called blocked zones. On each cell of the board, there is written one of the following 55 characters  — UU, DD, LL, RR or XX  — instructions for the player. Suppose that the current cell is (r,c)(r,c). If the character is RR, the player should move to the right cell (r,c+1)(r,c+1), for LL the player should move to the left cell (r,c−1)(r,c−1), for UU the player should move to the top cell (r−1,c)(r−1,c), for DD the player should move to the bottom cell (r+1,c)(r+1,c). Finally, if the character in the cell is XX, then this cell is the blocked zone. The player should remain in this cell (the game for him isn't very interesting from now on).It is guaranteed that the characters are written in a way that the player will never have to step outside of the board, no matter at which cell he starts.As a player starts from a cell, he moves according to the character in the current cell. The player keeps moving until he lands in a blocked zone. It is also possible that the player will keep moving infinitely long.For every of the n2n2 cells of the board Alice, your friend, wants to know, how will the game go, if the player starts in this cell. For each starting cell of the board, she writes down the cell that the player stops at, or that the player never stops at all. She gives you the information she has written: for each cell (r,c)(r,c) she wrote: a pair (xx,yy), meaning if a player had started at (r,c)(r,c), he would end up at cell (xx,yy). or a pair (−1−1,−1−1), meaning if a player had started at (r,c)(r,c), he would keep moving infinitely long and would never enter the blocked zone. It might be possible that Alice is trying to fool you and there's no possible grid that satisfies all the constraints Alice gave you. For the given information Alice provided you, you are required to decipher a possible board, or to determine that such a board doesn't exist. If there exist several different boards that satisfy the provided information, you can find any of them.InputThe first line of the input contains a single integer nn (1≤n≤1031≤n≤103)  — the side of the board.The ii-th of the next nn lines of the input contains 2n2n integers x1,y1,x2,y2,…,xn,ynx1,y1,x2,y2,…,xn,yn, where (xj,yj)(xj,yj) (1≤xj≤n,1≤yj≤n1≤xj≤n,1≤yj≤n, or (xj,yj)=(−1,−1)(xj,yj)=(−1,−1)) is the pair written by Alice for the cell (i,j)(i,j). OutputIf there doesn't exist a board satisfying the information that Alice gave you, print a single line containing INVALID. Otherwise, in the first line print VALID. In the ii-th of the next nn lines, print the string of nn characters, corresponding to the characters in the ii-th row of the suitable board you found. Each character of a string can either be UU, DD, LL, RR or XX. If there exist several different boards that satisfy the provided information, you can find any of them.ExamplesInputCopy2 1 1 1 1 2 2 2 2 OutputCopyVALID XL RX InputCopy3 -1 -1 -1 -1 -1 -1 -1 -1 2 2 -1 -1 -1 -1 -1 -1 -1 -1 OutputCopyVALID RRD UXD ULLNoteFor the sample test 1 :The given grid in output is a valid one. If the player starts at (1,1)(1,1), he doesn't move any further following XX and stops there. If the player starts at (1,2)(1,2), he moves to left following LL and stops at (1,1)(1,1). If the player starts at (2,1)(2,1), he moves to right following RR and stops at (2,2)(2,2). If the player starts at (2,2)(2,2), he doesn't move any further following XX and stops there. The simulation can be seen below : For the sample test 2 : The given grid in output is a valid one, as a player starting at any cell other than the one at center (2,2)(2,2), keeps moving in an infinitely long cycle and never stops. Had he started at (2,2)(2,2), he wouldn't have moved further following instruction XX .The simulation can be seen below :
[ "constructive algorithms", "dfs and similar", "graphs", "implementation" ]
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; public class Codecraft20D { 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; } } // long start = System.currentTimeMillis(); // long end = System.currentTimeMillis(); // System.out.println((end - start) + "ms"); static char[][] answer; static Pair[][] grid; static boolean[][] visited; static int n; public static void main(String[] args) throws IOException { FastReader s=new FastReader(); n = s.nextInt(); answer = new char[n][n]; grid = new Pair[n][n]; visited = new boolean[n][n]; ArrayList<Pair> x_list = new ArrayList<>(); ArrayList<Pair> minusone_list = new ArrayList<>(); for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ int a = s.nextInt(); int b = s.nextInt(); Pair p ; if(a==-1 || b==-1){ p = new Pair(-1,-1); minusone_list.add(new Pair(i,j)); } else { p = new Pair(a-1,b-1); if(i==a-1 && j==b-1){ answer[i][j] = 'X'; x_list.add(new Pair(i,j)); } } grid[i][j] = p; } } //now dfs on X for every x for(Pair p:x_list){ int x =p.x; int y =p.y; visited[x][y] = true; x_dfs(x,y,p); } x_list.clear(); //now we have left with only -1s // debug(visited); for(Pair p:minusone_list){ int x =p.x; int y = p.y; Pair parent = new Pair(-1,-1); if(!visited[x][y]){ // System.out.println(x+" "+y); // if this x has no adjacent -1 print -1 int x_left = x-1; int x_right = x+1; int y_left = y-1; int y_right = y+1; if(x_left>=0 && isEqual(parent,grid[x-1][y])){ answer[x][y] = 'U'; visited[x][y] = true; minus_dfs(x,y); } else if(x_right<n && isEqual(parent,grid[x+1][y])){ answer[x][y] ='D'; visited[x][y] = true; minus_dfs(x,y); } else if(y_left>=0 && isEqual(parent,grid[x][y-1])){ answer[x][y] ='L'; visited[x][y] = true; minus_dfs(x,y); } else if(y_right<n && isEqual(parent,grid[x][y+1])){ answer[x][y] ='R'; visited[x][y] = true; minus_dfs(x,y); } else { System.out.println("INVALID"); // debug(answer); return; } // minusone_list.remove(p); } // minusone_list.clear(); } minusone_list.clear(); //now check if every grid is filled for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ if(answer[i][j]==(char)0){ System.out.println("INVALID"); return; } } } //print valid System.out.println("VALID"); debug(answer); } public static void x_dfs(int x,int y,Pair parent){ // int x_left = x-1; // int x_right = x+1; // int y_left = y-1; // int y_right = y+1; if(x-1>=0 && isEqual(parent,grid[x-1][y]) && !visited[x-1][y]){ visited[x-1][y] = true; answer[x-1][y] = 'D'; x_dfs(x-1,y,parent); } if(x+1<n && isEqual(parent,grid[x+1][y]) && !visited[x+1][y]){ visited[x+1][y] = true; answer[x+1][y] = 'U'; x_dfs(x+1,y,parent); } if(y-1>=0 && isEqual(parent,grid[x][y-1]) && !visited[x][y-1]){ visited[x][y-1] = true; answer[x][y-1] ='R'; x_dfs(x,y-1,parent); } if(y+1<n && isEqual(parent,grid[x][y+1]) && !visited[x][y+1]){ visited[x][y+1] = true; answer[x][y+1] ='L'; x_dfs(x,y+1,parent); } } static Pair parent = new Pair(-1,-1); public static void minus_dfs(int x,int y){ //two conditions if it has adjacent -1 other than prev then continue //else this forms a cycle if(x-1>=0 && isEqual(parent,grid[x-1][y]) && !visited[x-1][y]){ answer[x-1][y] ='D'; visited[x-1][y] = true; minus_dfs(x-1,y); } if(x+1<n && isEqual(parent,grid[x+1][y]) && !visited[x+1][y]){ answer[x+1][y] ='U'; visited[x+1][y] = true; minus_dfs(x+1,y); } if(y-1>=0 && isEqual(parent,grid[x][y-1]) && !visited[x][y-1]){ answer[x][y-1]='R'; visited[x][y-1] = true; minus_dfs(x,y-1); } if(y+1<n && isEqual(parent,grid[x][y+1]) && !visited[x][y+1]){ answer[x][y+1] ='L'; visited[x][y+1] = true; minus_dfs(x,y+1); } } static class Pair{ int x; int y; Pair(int x,int y){ this.x = x; this.y = y; } } static boolean isEqual(Pair p,Pair q){ if(q.x==p.x && q.y == p.y){ return true; } return false; } public static void print(String str,int val){ System.out.println(str+" "+val); } public static void debug(char[][] arr) throws IOException { OutputStream out = new BufferedOutputStream( System.out ); int len = arr.length; int len2 = arr[0].length; for(int i=0;i<len;i++){ for(int j=0;j<len2;j++){ out.write((arr[i][j]+"").getBytes()); } out.write("\n".getBytes()); out.flush(); } out.close(); } public static void debug(long[][] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.println(Arrays.toString(arr[i])); } } public static void debug(int[][] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.println(Arrays.toString(arr[i])); } } public static void debug(boolean[][] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.println(Arrays.toString(arr[i])); } } public static void print(int[] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.print(arr[i]+" "); } System.out.print('\n'); } public static void print(String[] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.print(arr[i]+" "); } System.out.print('\n'); } public static void print(long[] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.print(arr[i]+" "); } System.out.print('\n'); } // OutputStream out = new BufferedOutputStream( System.out ); // for(int i=1;i<n;i++){ // out.write((max_divisor[i]+" ").getBytes()); //} // out.flush(); }
java
1307
D
D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n)  — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n)  — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3 1 3 5 1 2 2 3 3 4 3 5 2 4 OutputCopy3 InputCopy5 4 2 2 4 1 2 2 3 3 4 4 5 OutputCopy3 NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33. The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33.
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "shortest paths", "sortings" ]
import java.util.*; import javax.swing.text.Segment; import java.io.*; import java.math.*; import java.sql.Array; import java.sql.ResultSet; import java.sql.SQLException; public class Main { private static class MyScanner { private static final int BUF_SIZE = 2048; BufferedReader br; private MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } private boolean isSpace(char c) { return c == '\n' || c == '\r' || c == ' '; } String next() { try { StringBuilder sb = new StringBuilder(); int r; while ((r = br.read()) != -1 && isSpace((char)r)); if (r == -1) { return null; } sb.append((char) r); while ((r = br.read()) != -1 && !isSpace((char)r)) { sb.append((char)r); } return sb.toString(); } catch (IOException e) { e.printStackTrace(); } return null; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } static class Reader{ BufferedReader br; StringTokenizer st; public Reader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static long mod = (long)(1e9 + 7); static void sort(long[] arr ) { ArrayList<Long> al = new ArrayList<>(); for(long e:arr) al.add(e); Collections.sort(al); for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i); } static void sort(int[] arr ) { ArrayList<Integer> al = new ArrayList<>(); for(int e:arr) al.add(e); Collections.sort(al); for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i); } static void sort(char[] arr) { ArrayList<Character> al = new ArrayList<Character>(); for(char cc:arr) al.add(cc); Collections.sort(al); for(int i = 0 ;i<arr.length ;i++) arr[i] = al.get(i); } static void rvrs(int[] arr) { int i =0 , j = arr.length-1; while(i>=j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++; j--; } } static void rvrs(long[] arr) { int i =0 , j = arr.length-1; while(i>=j) { long temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++; j--; } } static long mod_mul( long mod , long... a) { long ans = a[0]%mod; for(int i = 1 ; i<a.length ; i++) { ans = (ans * (a[i]%mod))%mod; } return ans; } static long mod_sum(long mod , long... a) { long ans = 0; for(long e:a) { ans = (ans + e)%mod; } return ans; } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static boolean[] prime(int num) { boolean[] bool = new boolean[num]; for (int i = 0; i< bool.length; i++) { bool[i] = true; } for (int i = 2; i< Math.sqrt(num); i++) { if(bool[i] == true) { for(int j = (i*i); j<num; j = j+i) { bool[j] = false; } } } if(num >= 0) { bool[0] = false; bool[1] = false; } return bool; } static long modInverse(long a, long m) { long g = gcd(a, m); return power(a, m - 2, m); } static long lcm(long a , long b) { return (a*b)/gcd(a, b); } static int lcm(int a , int b) { return (int)((a*b)/gcd(a, b)); } static long power(long x, long y, long m){ if (y == 0) return 1; long p = power(x, y / 2, m) % m; p = (int)((p * (long)p) % m); if (y % 2 == 0) return p; else return (int)((x * (long)p) % m); } static class Combinations{ private long[] z; private long[] z1; private long[] z2; public Combinations(long N , long mod) { z = new long[(int)N+1]; z1 = new long[(int)N+1]; z[0] = 1; for(int i =1 ; i<=N ; i++) z[i] = (z[i-1]*i)%mod; z2 = new long[(int)N+1]; z2[0] = z2[1] = 1; for (int i = 2; i <= N; i++) z2[i] = z2[(int)(mod % i)] * (mod - mod / i) % mod; z1[0] = z1[1] = 1; for (int i = 2; i <= N; i++) z1[i] = (z2[i] * z1[i - 1]) % mod; } long fac(long n) { return z[(int)n]; } long invrsNum(long n) { return z2[(int)n]; } long invrsFac(long n) { return invrsFac((int)n); } long ncr(long N, long R, long mod) { if(R<0 || R>N ) return 0; long ans = ((z[(int)N] * z1[(int)R]) % mod * z1[(int)(N - R)]) % mod; return ans; } } static class DisjointUnionSets { int[] rank, parent; int n; public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; this.n = 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), 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] = rank[xRoot] + 1; } } } static int max(int... a ) { int max = a[0]; for(int e:a) max = Math.max(max, e); return max; } static long max(long... a ) { long max = a[0]; for(long e:a) max = Math.max(max, e); return max; } static int min(int... a ) { int min = a[0]; for(int e:a) min = Math.min(e, min); return min; } static long min(long... a ) { long min = a[0]; for(long e:a) min = Math.min(e, min); return min; } static int[] KMP(String str) { int n = str.length(); int[] kmp = new int[n]; for(int i = 1 ; i<n ; i++) { int j = kmp[i-1]; while(j>0 && str.charAt(i) != str.charAt(j)) { j = kmp[j-1]; } if(str.charAt(i) == str.charAt(j)) j++; kmp[i] = j; } return kmp; } /************************************************ Query **************************************************************************************/ /***************************************** Sparse Table ********************************************************/ static class SparseTable{ private long[][] st; SparseTable(long[] arr){ int n = arr.length; st = new long[n][25]; log = new int[n+2]; build_log(n+1); build(arr); } private void build(long[] arr) { int n = arr.length; for(int i = n-1 ; i>=0 ; i--) { for(int j = 0 ; j<25 ; j++) { int r = i + (1<<j)-1; if(r>=n) break; if(j == 0 ) st[i][j] = arr[i]; else st[i][j] = Math.max(st[i][j-1] , st[ i + ( 1 << (j-1) ) ][ j-1 ] ); } } } public long gcd(long a ,long b) { if(a == 0) return b; return gcd(b%a , a); } public long query(int l ,int r) { int w = r-l+1; int power = log[w]; return Math.max(st[l][power],st[r - (1<<power) + 1][power]); } private int[] log; void build_log(int n) { log[1] = 0; for(int i = 2 ; i<=n ; i++) { log[i] = 1 + log[i/2]; } } } /******************************************************** Segement Tree *****************************************************/ /** static class SegmentTree{ long[] tree; long[] arr; int n; SegmentTree(long[] arr){ this.n = arr.length; tree = new long[4*n+1]; this.arr = arr; buildTree(0, n-1, 1); } void buildTree(int s ,int e ,int index ) { if(s == e) { tree[index] = arr[s]; return; } int mid = (s+e)/2; buildTree( s, mid, 2*index); buildTree( mid+1, e, 2*index+1); tree[index] = Math.min(tree[2*index] , tree[2*index+1]); } long query(int si ,int ei) { return query(0 ,n-1 , si ,ei , 1 ); } private long query( int ss ,int se ,int qs , int qe,int index) { if(ss>=qs && se<=qe) return tree[index]; if(qe<ss || se<qs) return (long)(1e17); int mid = (ss + se)/2; long left = query( ss , mid , qs ,qe , 2*index); long right= query(mid + 1 , se , qs ,qe , 2*index+1); return Math.min(left, right); } public void update(int index , int val) { arr[index] = val; for(long e:arr) System.out.print(e+" "); update(index , 0 , n-1 , 1); } private void update(int id ,int si , int ei , int index) { if(id < si || id>ei) return; if(si == ei ) { tree[index] = arr[id]; return; } if(si > ei) return; int mid = (ei + si)/2; update( id, si, mid , 2*index); update( id , mid+1, ei , 2*index+1); tree[index] = Math.min(tree[2*index] ,tree[2*index+1]); } } */ /* ***************************************************************************************************************************************************/ // static MyScanner sc = new MyScanner(); // only in case of less memory static Reader sc = new Reader(); static StringBuilder sb = new StringBuilder(); public static void main(String args[]) throws IOException { int tc = 1; // tc = sc.nextInt(); for(int i = 1 ; i<=tc ; i++) { // sb.append("Case #" + i + ": " ); // During KickStart && HackerCup TEST_CASE(); } System.out.println(sb); } static boolean[] s ; static void TEST_CASE() { int n = sc.nextInt() , m = sc.nextInt() , k = sc.nextInt(); adj = new ArrayList<>(); ArrayList<Integer> a = new ArrayList<>(); s = new boolean[n+1]; for(int i = 0 ; i<k ; i++) { a.add(sc.nextInt()); s[a.get(i)] = true; } for(int i =0 ;i<=n ; i++) adj.add(new ArrayList<>()); for(int i =0 ;i<m ; i++) { int u = sc.nextInt() , v = sc.nextInt(); adj.get(u).add(v); adj.get(v).add(u); } pres = false; int[] d1 = bfs(n , 1); if(pres) { // System.out.println("hi"); System.out.println(d1[n]); return; } int[] dn = bfs(n , n); Comparator<Integer> comp = new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return Integer.compare(d1[o1], d1[o2]); } }; Collections.sort(a , comp); int ans = 0 , curr = dn[a.get(k-1)]; for(int i = k-2 ; i>=0 ; i--) { ans = max(ans , d1[a.get(i)] + curr + 1); curr = max(curr , dn[a.get(i)]); } ans = min(ans , d1[n]); System.out.println(ans); } static ArrayList<ArrayList<Integer>> adj; static boolean pres; static int[] bfs(int n , int ind) { int[] dis = new int[n+1]; Set<Integer> set = new HashSet<>(); LinkedList<int[]> ll = new LinkedList<>(); ll.add(new int[]{ind , 0}); while(!ll.isEmpty()) { int[] pa = ll.removeFirst(); if(set.contains(pa[0])) continue; dis[pa[0]] = pa[1]; set.add(pa[0]); for(int v:adj.get(pa[0])) { if(s[v] && s[pa[0]]) pres = true; if(set.contains(v)) continue; ll.addLast(new int[] {v , pa[1] + 1}); } } return dis; } } /*******************************************************************************************************************************************************/ /** */
java
1294
D
D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array; for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array; for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai−xai:=ai−x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,…,yj][y1,y2,…,yj].InputThe first line of the input contains two integers q,xq,x (1≤q,x≤4⋅1051≤q,x≤4⋅105) — the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0≤yj≤1090≤yj≤109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query — for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3 0 1 2 2 0 0 10 OutputCopy1 2 3 3 4 4 7 InputCopy4 3 1 2 1 2 OutputCopy0 0 0 0 NoteIn the first example: After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11. After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22. After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33. After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations). After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44. After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44. After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations: a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5, a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3, a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3, a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6, a[6]:=a[6]−3=10−3=7a[6]:=a[6]−3=10−3=7, a[6]:=a[6]−3=7−3=4a[6]:=a[6]−3=7−3=4. The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77.
[ "data structures", "greedy", "implementation", "math" ]
import java.util.Scanner; public class d { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int q = sc.nextInt(); int x = sc.nextInt(); int cnt[]=new int[x]; int mex=0; StringBuilder sb=new StringBuilder(""); while(q-- != 0) { int val=sc.nextInt(); cnt[val%x]++; while(cnt[mex%x]!=0) { cnt[mex%x]--; mex++; } sb.append(mex+"\n"); } System.out.println(sb); } }
java
1307
B
B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109)  — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2 3 1 2 NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0).
[ "geometry", "greedy", "math" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.sort; public class Codeforces { // static int mod = 998244353; static int mod = 1000000007; public static void main(String[] args) { FastReader fastReader = new FastReader(); PrintWriter out = new PrintWriter(System.out); int t = fastReader.nextInt(); while (t-- > 0) { int n = fastReader.nextInt(); int x = fastReader.nextInt(); int a[] = fastReader.ria(n); int max = maxof(a); boolean contains = false; for (int i = 0; i < n; i++) { if (a[i] == x) { contains = true; } } if (contains) { out.println(1); continue; } if (max < x) { int div = x / max; if (x % max != 0) { div++; } out.println(div); } else { out.println(2); } } out.close(); } // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final long LMAX = 9223372036854775807L; static Random __r = new Random(); // math util static int minof(int a, int b, int c) { return min(a, min(b, c)); } static int minof(int... x) { if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min; } static long minof(long a, long b, long c) { return min(a, min(b, c)); } static long minof(long... x) { if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min; } static int maxof(int a, int b, int c) { return max(a, max(b, c)); } static int maxof(int... x) { if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max; } static long maxof(long a, long b, long c) { return max(a, max(b, c)); } static long maxof(long... x) { if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max; } static int powi(int a, int b) { if (a == 0) return 0; int ans = 1; while (b > 0) { if ((b & 1) > 0) ans *= a; a *= a; b >>= 1; } return ans; } static long powl(long a, int b) { if (a == 0) return 0; long ans = 1; while (b > 0) { if ((b & 1) > 0) ans *= a; a *= a; b >>= 1; } return ans; } static int fli(double d) { return (int) d; } static int cei(double d) { return (int) ceil(d); } static long fll(double d) { return (long) d; } static long cel(double d) { return (long) ceil(d); } static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } static long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } static int[] exgcd(int a, int b) { if (b == 0) return new int[] { 1, 0 }; int[] y = exgcd(b, a % b); return new int[] { y[1], y[0] - y[1] * (a / b) }; } static long[] exgcd(long a, long b) { if (b == 0) return new long[] { 1, 0 }; long[] y = exgcd(b, a % b); return new long[] { y[1], y[0] - y[1] * (a / b) }; } static int randInt(int min, int max) { return __r.nextInt(max - min + 1) + min; } static long mix(long x) { x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31); } public static boolean[] findPrimes(int limit) { assert limit >= 2; final boolean[] nonPrimes = new boolean[limit]; nonPrimes[0] = true; nonPrimes[1] = true; int sqrt = (int) Math.sqrt(limit); for (int i = 2; i <= sqrt; i++) { if (nonPrimes[i]) continue; for (int j = i; j < limit; j += i) { if (!nonPrimes[j] && i != j) nonPrimes[j] = true; } } return nonPrimes; } // array util static void reverse(int[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(long[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(double[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void reverse(char[] a) { for (int i = 0, n = a.length, half = n / 2; i < half; ++i) { char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap; } } static void shuffle(int[] a) { int n = a.length - 1; for (int i = 0; i < n; ++i) { int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap; } } static void shuffle(long[] a) { int n = a.length - 1; for (int i = 0; i < n; ++i) { int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap; } } static void shuffle(double[] a) { int n = a.length - 1; for (int i = 0; i < n; ++i) { int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap; } } static void rsort(int[] a) { shuffle(a); sort(a); } static void rsort(long[] a) { shuffle(a); sort(a); } static void rsort(double[] a) { shuffle(a); sort(a); } static int[] copy(int[] a) { int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } static long[] copy(long[] a) { long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } static double[] copy(double[] a) { double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } static char[] copy(char[] a) { char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans; } 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()); } int[] ria(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = Integer.parseInt(next()); return a; } long nextLong() { return Long.parseLong(next()); } long[] rla(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = Long.parseLong(next()); return a; } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
java
1321
C
C. Remove Adjacenttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss consisting of lowercase Latin letters. Let the length of ss be |s||s|. You may perform several operations on this string.In one operation, you can choose some index ii and remove the ii-th character of ss (sisi) if at least one of its adjacent characters is the previous letter in the Latin alphabet for sisi. For example, the previous letter for b is a, the previous letter for s is r, the letter a has no previous letters. Note that after each removal the length of the string decreases by one. So, the index ii should satisfy the condition 1≤i≤|s|1≤i≤|s| during each operation.For the character sisi adjacent characters are si−1si−1 and si+1si+1. The first and the last characters of ss both have only one adjacent character (unless |s|=1|s|=1).Consider the following example. Let s=s= bacabcab. During the first move, you can remove the first character s1=s1= b because s2=s2= a. Then the string becomes s=s= acabcab. During the second move, you can remove the fifth character s5=s5= c because s4=s4= b. Then the string becomes s=s= acabab. During the third move, you can remove the sixth character s6=s6='b' because s5=s5= a. Then the string becomes s=s= acaba. During the fourth move, the only character you can remove is s4=s4= b, because s3=s3= a (or s5=s5= a). The string becomes s=s= acaa and you cannot do anything with it. Your task is to find the maximum possible number of characters you can remove if you choose the sequence of operations optimally.InputThe first line of the input contains one integer |s||s| (1≤|s|≤1001≤|s|≤100) — the length of ss.The second line of the input contains one string ss consisting of |s||s| lowercase Latin letters.OutputPrint one integer — the maximum possible number of characters you can remove if you choose the sequence of moves optimally.ExamplesInputCopy8 bacabcab OutputCopy4 InputCopy4 bcda OutputCopy3 InputCopy6 abbbbb OutputCopy5 NoteThe first example is described in the problem statement. Note that the sequence of moves provided in the statement is not the only; but it can be shown that the maximum possible answer to this test is 44.In the second example, you can remove all but one character of ss. The only possible answer follows. During the first move, remove the third character s3=s3= d, ss becomes bca. During the second move, remove the second character s2=s2= c, ss becomes ba. And during the third move, remove the first character s1=s1= b, ss becomes a.
[ "brute force", "constructive algorithms", "greedy", "strings" ]
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { static InputStream is; static PrintWriter out; static String INPUT = ""; static final int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE; static final long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE; static final long mod = (long) 1e9 + 7; static void solve() { int caseNo = 1; // for (int T = sc.nextInt(); T > 1; T--, caseNo++) { solveIt(caseNo); } solveIt(caseNo); } // Solution static void solveIt(int testCaseNo) { int n = sc.nextInt(); StringBuilder sb = new StringBuilder(sc.next()); for (char ch = 'z'; ch >= 'b';) { boolean done = false; for (int i = 0; i < sb.length(); i++) { if (i - 1 >= 0 && sb.charAt(i) == ch && ch - sb.charAt(i - 1) == 1) { sb.deleteCharAt(i); done = true; break; } else if (i + 1 < sb.length() && sb.charAt(i) == ch && ch - sb.charAt(i + 1) == 1) { sb.deleteCharAt(i); done = true; break; } } if (!done) ch--; } System.out.println(n - sb.length()); } public static void main(String[] args) throws Exception { long S = System.currentTimeMillis(); is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); solve(); out.flush(); long G = System.currentTimeMillis(); sc.tr(G - S + "ms"); } static class sc { private static boolean endOfFile() { if (bufferLength == -1) return true; int lptr = ptrbuf; while (lptr < bufferLength) { if (!isThisTheSpaceCharacter(inputBufffferBigBoi[lptr++])) return false; } try { is.mark(1000); while (true) { int b = is.read(); if (b == -1) { is.reset(); return true; } else if (!isThisTheSpaceCharacter(b)) { is.reset(); return false; } } } catch (IOException e) { return true; } } private static byte[] inputBufffferBigBoi = new byte[1024]; static int bufferLength = 0, ptrbuf = 0; private static int justReadTheByte() { if (bufferLength == -1) throw new InputMismatchException(); if (ptrbuf >= bufferLength) { ptrbuf = 0; try { bufferLength = is.read(inputBufffferBigBoi); } catch (IOException e) { throw new InputMismatchException(); } if (bufferLength <= 0) return -1; } return inputBufffferBigBoi[ptrbuf++]; } private static boolean isThisTheSpaceCharacter(int c) { return !(c >= 33 && c <= 126); } private static int skipItBishhhhhhh() { int b; while ((b = justReadTheByte()) != -1 && isThisTheSpaceCharacter(b)); return b; } private static double nextDouble() { return Double.parseDouble(next()); } private static char nextChar() { return (char) skipItBishhhhhhh(); } private static String next() { int b = skipItBishhhhhhh(); StringBuilder sb = new StringBuilder(); while (!(isThisTheSpaceCharacter(b))) { sb.appendCodePoint(b); b = justReadTheByte(); } return sb.toString(); } private static char[] readCharArray(int n) { char[] buf = new char[n]; int b = skipItBishhhhhhh(), p = 0; while (p < n && !(isThisTheSpaceCharacter(b))) { buf[p++] = (char) b; b = justReadTheByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private static char[][] readCharMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = readCharArray(m); return map; } private static int[] readIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } private static long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } private static int nextInt() { int num = 0, b; boolean minus = false; while ((b = justReadTheByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if (b == '-') { minus = true; b = justReadTheByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = justReadTheByte(); } } private static long nextLong() { long num = 0; int b; boolean minus = false; while ((b = justReadTheByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if (b == '-') { minus = true; b = justReadTheByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = justReadTheByte(); } } private static void tr(Object... o) { if (INPUT.length() != 0) System.out.println(Arrays.deepToString(o)); } } } // And I wish you could sing along, But this song is a joke, and the melody I // wrote, wrong
java
1296
E1
E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2001≤n≤200) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9 abacbecfd OutputCopyYES 001010101 InputCopy8 aaabbcbb OutputCopyYES 01011011 InputCopy7 abcdedc OutputCopyNO InputCopy5 abcde OutputCopyYES 00000
[ "constructive algorithms", "dp", "graphs", "greedy", "sortings" ]
import java.io.*; import java.math.BigInteger; import java.util.*; /** * * @author eslam */ public class Solution { // Beginning of the solution static Kattio input = new Kattio(); static BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); static ArrayList<ArrayList<Integer>> powerSet = new ArrayList<>(); static ArrayList<LinkedList<Integer>> allprem = new ArrayList<>(); static ArrayList<LinkedList<String>> allprems = new ArrayList<>(); static ArrayList<Long> luc = new ArrayList<>(); static long mod = (long) (1e9 + 7); static int grid[][] = {{0, 0, 1, -1, 1, 1, -1, -1}, {1, -1, 0, 0, 1, -1, 1, -1}}; static long dp[][]; static double cmp = 1e-7; static final double pi = 3.14159265359; static int ans[]; static boolean can; public static void main(String[] args) throws IOException { // Kattio input = new Kattio("input"); // BufferedWriter log = new BufferedWriter(new FileWriter(f)); int test = 1;//input.nextInt(); loop: for (int co = 1; co <= test; co++) { int n = input.nextInt(); char ch[] = input.next().toCharArray(); pair a[] = new pair[n]; for (int i = 0; i < n; i++) { a[i] = new pair(i, ch[i]); } ans = new int[n]; can = true; ArrayList<Integer> graph[] = new ArrayList[n]; for (int i = 0; i < n; i++) { graph[i] = new ArrayList<>(); } for (int i = 0; i < n; i++) { for (int j = 0; j < n - 1 - i; j++) { if (a[j].y > a[j + 1].y) { pair c = a[j]; a[j] = a[j + 1]; a[j + 1] = c; graph[a[j].x].add(a[j + 1].x); graph[a[j + 1].x].add(a[j].x); } } } boolean vi[] = new boolean[n]; for (int i = 0; i < n; i++) { if (!vi[i]) { dfs(i, graph, vi, 1); } } if (!can) { log.write("NO\n"); } else { log.write("YES\n"); for (int an : ans) { log.write(an + ""); } log.write("\n"); } } log.flush(); } static void dfs(int node, ArrayList<Integer> graph[], boolean vi[], int cur) { vi[node] = true; ans[node] = cur; for (Integer x : graph[node]) { if (!vi[x]) { dfs(x, graph, vi, 1 - cur); } else if (ans[x] != 1 - cur) { can = false; return; } } } static class pair { int x; int y; public pair(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } static class tri { int x, y; int z; public tri(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } @Override public String toString() { return x + " " + y + " " + z; } } public static pair[] dijkstra(int node, ArrayList<pair> a[]) { PriorityQueue<tri> q = new PriorityQueue<>(new Comparator<tri>() { @Override public int compare(tri o1, tri o2) { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { return 0; } } }); q.add(new tri(node, 0, -1)); pair distance[] = new pair[a.length]; while (!q.isEmpty()) { tri p = q.poll(); int cost = p.y; if (distance[p.x] != null) { continue; } distance[p.x] = new pair(p.z, cost); ArrayList<pair> nodes = a[p.x]; for (pair node1 : nodes) { if (distance[node1.x] == null) { tri pa = new tri(node1.x, cost + node1.y, p.x); q.add(pa); } } } return distance; } public static boolean isSortedInc(int[] a, int l, int r) { for (int i = l; i <= r; i++) { if (a[i] > a[i + 1]) { return false; } } return true; } public static boolean isSortedDec(int[] a, int l, int r) { for (int i = l; i <= r; i++) { if (a[i] < a[i + 1]) { return false; } } return true; } static long f(long x) { return (long) ((x * (x + 1) / 2) % mod); } static long Sub(long x, long y) { long z = x - y; if (z < 0) { z += mod; } return z; } static long add(long a, long b) { a += b; if (a >= mod) { a -= mod; } return a; } static long mul(long a, long b) { return (long) ((long) a * b % mod); } static long powlog(long base, long power) { if (power == 0) { return 1; } long x = powlog(base, power / 2); x = mul(x, x); if ((power & 1) == 1) { x = mul(x, base); } return x; } static long modinv(long x) { return fast_pow(x, mod - 2, mod); } static long Div(long x, long y) { return mul(x, modinv(y)); } static void floodFill(int r, int c, int a[][], boolean vi[][], int w[][], int d) { vi[r][c] = true; for (int i = 0; i < 4; i++) { int nr = grid[0][i] + r; int nc = grid[1][i] + c; if (isValid(nr, nc, a.length, a[0].length)) { if (Math.abs(a[r][c] - a[nr][nc]) <= d && !vi[nr][nc]) { floodFill(nr, nc, a, vi, w, d); } } } } static boolean isdigit(char ch) { return ch >= '0' && ch <= '9'; } static boolean lochar(char ch) { return ch >= 'a' && ch <= 'z'; } static boolean cachar(char ch) { return ch >= 'A' && ch <= 'Z'; } static class Pa { long x; long y; public Pa(long x, long y) { this.x = x; this.y = y; } } static long sqrt(long v) { long max = (long) 4e9; long min = 0; long ans = 0; while (max >= min) { long mid = (max + min) / 2; if (mid * mid > v) { max = mid - 1; } else { ans = mid; min = mid + 1; } } return ans; } static long cbrt(long v) { long max = (long) 3e6; long min = 0; long ans = 0; while (max >= min) { long mid = (max + min) / 2; if (mid * mid > v) { max = mid - 1; } else { ans = mid; min = mid + 1; } } return ans; } static void prefixSum2D(long arr[][]) { for (int i = 0; i < arr.length; i++) { prefixSum(arr[i]); } for (int i = 0; i < arr[0].length; i++) { for (int j = 1; j < arr.length; j++) { arr[j][i] += arr[j - 1][i]; } } } public static long baseToDecimal(String w, long base) { long r = 0; long l = 0; for (int i = w.length() - 1; i > -1; i--) { long x = (w.charAt(i) - '0') * (long) Math.pow(base, l); r = r + x; l++; } return r; } static int bs(int v, ArrayList<Integer> a) { int max = a.size() - 1; int min = 0; int ans = 0; while (max >= min) { int mid = (max + min) / 2; if (a.get(mid) >= v) { ans = a.size() - mid; max = mid - 1; } else { min = mid + 1; } } return ans; } static Comparator<tri> cmpTri() { Comparator<tri> c = new Comparator<tri>() { @Override public int compare(tri o1, tri o2) { if (o1.x > o2.x) { return 1; } else if (o1.x < o2.x) { return -1; } else { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { if (o1.z > o2.z) { return 1; } else if (o1.z < o2.z) { return -1; } else { return 0; } } } } }; return c; } static Comparator<pair> cmpPair2() { Comparator<pair> c = new Comparator<pair>() { @Override public int compare(pair o1, pair o2) { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { if (o1.x > o2.x) { return -1; } else if (o1.x < o2.x) { return 1; } else { return 0; } } } }; return c; } static Comparator<pair> cmpPair() { Comparator<pair> c = new Comparator<pair>() { @Override public int compare(pair o1, pair o2) { if (o1.x < o2.x) { return -1; } else if (o1.x > o2.x) { return 1; } else { if (o1.y > o2.y) { return 1; } else if (o1.y < o2.y) { return -1; } else { return 0; } } } }; return c; } static class rec { long x1; long x2; long y1; long y2; public rec(long x1, long y1, long x2, long y2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } public long getArea() { return (x2 - x1) * (y2 - y1); } } static long sumOfRange(int x1, int y1, int x2, int y2, long a[][]) { return (a[x2][y2] - a[x1 - 1][y2] - a[x2][y1 - 1]) + a[x1 - 1][y1 - 1]; } public static int[][] bfs(int i, int j, String w[]) { Queue<pair> q = new ArrayDeque<>(); q.add(new pair(i, j)); int dis[][] = new int[w.length][w[0].length()]; for (int k = 0; k < w.length; k++) { Arrays.fill(dis[k], -1); } dis[i][j] = 0; while (!q.isEmpty()) { pair p = q.poll(); int cost = dis[p.x][p.y]; for (int k = 0; k < 4; k++) { int nx = p.x + grid[0][k]; int ny = p.y + grid[1][k]; if (isValid(nx, ny, w.length, w[0].length())) { if (dis[nx][ny] == -1 && w[nx].charAt(ny) == '.') { q.add(new pair(nx, ny)); dis[nx][ny] = cost + 1; } } } } return dis; } public static void graphRepresintion(ArrayList<Integer>[] a, int q) throws IOException { for (int i = 0; i < a.length; i++) { a[i] = new ArrayList<>(); } while (q-- > 0) { int x = input.nextInt(); int y = input.nextInt(); a[x].add(y); a[y].add(x); } } public static boolean isValid(int i, int j, int n, int m) { return (i > -1 && i < n) && (j > -1 && j < m); } // present in the left and right indices public static int[] swap(int data[], int left, int right) { // Swap the data int temp = data[left]; data[left] = data[right]; data[right] = temp; // Return the updated array return data; } // Function to reverse the sub-array // starting from left to the right // both inclusive public static int[] reverse(int data[], int left, int right) { // Reverse the sub-array while (left < right) { int temp = data[left]; data[left++] = data[right]; data[right--] = temp; } // Return the updated array return data; } // Function to find the next permutation // of the given integer array public static boolean findNextPermutation(int data[]) { // If the given dataset is empty // or contains only one element // next_permutation is not possible if (data.length <= 1) { return false; } int last = data.length - 2; // find the longest non-increasing suffix // and find the pivot while (last >= 0) { if (data[last] < data[last + 1]) { break; } last--; } // If there is no increasing pair // there is no higher order permutation if (last < 0) { return false; } int nextGreater = data.length - 1; // Find the rightmost successor to the pivot for (int i = data.length - 1; i > last; i--) { if (data[i] > data[last]) { nextGreater = i; break; } } // Swap the successor and the pivot data = swap(data, nextGreater, last); // Reverse the suffix data = reverse(data, last + 1, data.length - 1); // Return true as the next_permutation is done return true; } public static String revs(String w) { String ans = ""; for (int i = w.length() - 1; i > -1; i--) { ans += w.charAt(i); } return ans; } public static boolean isPalindrome(String w) { for (int i = 0; i < w.length() / 2; i++) { if (w.charAt(i) != w.charAt(w.length() - i - 1)) { return false; } } return true; } public static void getPowerSet(Queue<Integer> a) { int n = a.poll(); if (!a.isEmpty()) { getPowerSet(a); } int s = powerSet.size(); for (int i = 0; i < s; i++) { ArrayList<Integer> ne = new ArrayList<>(); ne.add(n); for (int j = 0; j < powerSet.get(i).size(); j++) { ne.add(powerSet.get(i).get(j)); } powerSet.add(ne); } ArrayList<Integer> p = new ArrayList<>(); p.add(n); powerSet.add(p); } public static int getlo(int va) { int v = 1; while (v <= va) { if ((va&v) != 0) { return v; } v <<= 1; } return 0; } static long fast_pow(long a, long p, long mod) { long res = 1; while (p > 0) { if (p % 2 == 0) { a = (a * a) % mod; p /= 2; } else { res = (res * a) % mod; p--; } } return res; } public static int countPrimeInRange(int n, boolean isPrime[]) { int cnt = 0; Arrays.fill(isPrime, true); for (int i = 2; i * i <= n; i++) { if (isPrime[i]) { for (int j = i * 2; j <= n; j += i) { isPrime[j] = false; } } } for (int i = 2; i <= n; i++) { if (isPrime[i]) { cnt++; } } return cnt; } public static void create(long num) { luc.add(num); if (num > power(10, 9)) { return; } create(num * 10 + 4); create(num * 10 + 7); } public static long ceil(long a, long b) { return (a + b - 1) / b; } public static long round(long a, long b) { if (a < 0) { return (a - b / 2) / b; } return (a + b / 2) / b; } public static void allPremutationsst(LinkedList<String> l, boolean visited[], ArrayList<String> st) { if (l.size() == st.size()) { allprems.add(l); } for (int i = 0; i < st.size(); i++) { if (!visited[i]) { visited[i] = true; LinkedList<String> nl = new LinkedList<>(); for (String x : l) { nl.add(x); } nl.add(st.get(i)); allPremutationsst(nl, visited, st); visited[i] = false; } } } public static void allPremutations(LinkedList<Integer> l, boolean visited[], int a[]) { if (l.size() == a.length) { allprem.add(l); } for (int i = 0; i < a.length; i++) { if (!visited[i]) { visited[i] = true; LinkedList<Integer> nl = new LinkedList<>(); for (Integer x : l) { nl.add(x); } nl.add(a[i]); allPremutations(nl, visited, a); visited[i] = false; } } } public static int binarySearch(long[] a, long value) { int l = 0; int r = a.length - 1; while (l <= r) { int m = (l + r) / 2; if (a[m] == value) { return m; } else if (a[m] > value) { r = m - 1; } else { l = m + 1; } } return -1; } public static void reverse(int l, int r, char ch[]) { for (int i = 0; i < r / 2; i++) { char c = ch[i]; ch[i] = ch[r - i - 1]; ch[r - i - 1] = c; } } public static long logK(long v, long k) { int ans = 0; while (v > 1) { ans++; v /= k; } return ans; } public static long power(long a, long p) { long res = 1; while (p > 0) { if (p % 2 == 0) { a = (a * a); p /= 2; } else { res = (res * a); p--; } } return res; } public static long get(long max, long x) { if (x == 1) { return max; } int cnt = 0; while (max > 0) { cnt++; max /= x; } return cnt; } public static int numOF0(long v) { long x = 1; int cnt = 0; while (x <= v) { if ((x & v) == 0) { cnt++; } x <<= 1; } return cnt; } public static int log2(double n) { int cnt = 0; while (n > 1) { n /= 2; cnt++; } return cnt; } public static int[] bfs(int node, ArrayList<Integer> a[]) { Queue<Integer> q = new LinkedList<>(); q.add(node); int distances[] = new int[a.length]; Arrays.fill(distances, -1); distances[node] = 0; while (!q.isEmpty()) { int parent = q.poll(); ArrayList<Integer> nodes = a[parent]; int cost = distances[parent]; for (Integer node1 : nodes) { if (distances[node1] == -1) { q.add(node1); distances[node1] = cost + 1; } } } return distances; } public static void primeFactors(int n, HashMap<Integer, ArrayList<Integer>> h, int ind) { boolean ca = true; while (n % 2 == 0) { if (ca) { if (h.get(2) == null) { h.put(2, new ArrayList<>()); } h.get(2).add(ind); ca = false; } n /= 2; } for (int i = 3; i <= Math.sqrt(n); i += 2) { ca = true; while (n % i == 0) { if (ca) { if (h.get(i) == null) { h.put(i, new ArrayList<>()); } h.get(i).add(ind); ca = false; } n /= i; } if (n < i) { break; } } if (n > 2) { if (h.get(n) == null) { h.put(n, new ArrayList<>()); } h.get(n).add(ind); } } // end of solution public static BigInteger ff(long n) { if (n <= 1) { return BigInteger.ONE; } long t = n - 1; BigInteger b = new BigInteger(t + ""); BigInteger ans = new BigInteger(n + ""); while (t > 1) { ans = ans.multiply(b); b = b.subtract(BigInteger.ONE); t--; } return ans; } public static long factorial(long n) { if (n <= 1) { return 1; } long t = n - 1; while (t > 1) { n = mod((mod(n, mod) * mod(t, mod)), mod); t--; } return n; } public static long rev(long n) { long t = n; long ans = 0; while (t > 0) { ans = ans * 10 + t % 10; t /= 10; } return ans; } public static boolean isPalindrome(int n) { int t = n; int ans = 0; while (t > 0) { ans = ans * 10 + t % 10; t /= 10; } return ans == n; } static boolean isPrime(long num) { if (num == 1) { return false; } if (num == 2) { return true; } if (num % 2 == 0) { return false; } if (num == 3) { return true; } for (long i = 3; i * i <= num; i += 2) { if (num % i == 0) { return false; } } return true; } public static void prefixSum(long[] a) { for (int i = 1; i < a.length; i++) { a[i] = a[i] + a[i - 1]; } } public static void suffixSum(long[] a) { for (int i = a.length - 2; i > -1; i--) { a[i] = a[i] + a[i + 1]; } } static long mod(long a, long b) { long r = a % b; return r < 0 ? r + b : r; } public static long binaryToDecimal(String w) { long r = 0; long l = 0; for (int i = w.length() - 1; i > -1; i--) { long x = (w.charAt(i) - '0') * (long) Math.pow(2, l); r = r + x; l++; } return r; } public static String decimalAnyBase(long n, long base) { String w = ""; while (n > 0) { w = n % base + w; n /= base; } return w; } public static String decimalToBinary(long n) { String w = ""; while (n > 0) { w = n % 2 + w; n /= 2; } return w; } public static void print(int[] a) throws IOException { for (int i = 0; i < a.length; i++) { log.write(a[i] + " "); } log.write("\n"); } public static void read(int[] a) { for (int i = 0; i < a.length; i++) { a[i] = input.nextInt(); } } static class gepair { long x; long y; public gepair(long x, long y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } static class pai { long x; int y; public pai(long x, int y) { this.x = x; this.y = y; } @Override public String toString() { return x + " " + y; } } public static long LCM(long x, long y) { return x / GCD(x, y) * y; } public static long GCD(long x, long y) { if (y == 0) { return x; } return GCD(y, x % y); } public static void simplifyTheFraction(int a, int b) { long GCD = GCD(a, b); System.out.println(a / GCD + " " + b / GCD); } static class Kattio extends PrintWriter { private BufferedReader r; private StringTokenizer st; // standard input public Kattio() { this(System.in, System.out); } public Kattio(InputStream i, OutputStream o) { super(o); r = new BufferedReader(new InputStreamReader(i)); } // USACO-style file input public Kattio(String problemName) throws IOException { super(problemName + ".out"); r = new BufferedReader(new FileReader(problemName)); } // returns null if no more input String nextLine() { String str = ""; try { str = r.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public String next() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(r.readLine()); } return st.nextToken(); } catch (Exception e) { } return null; } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } } static class RedBlackNode<T extends Comparable<T>> { /** * Possible color for this node */ public static final int BLACK = 0; /** * Possible color for this node */ public static final int RED = 1; // the key of each node public T key; /** * Parent of node */ RedBlackNode<T> parent; /** * Left child */ RedBlackNode<T> left; /** * Right child */ RedBlackNode<T> right; // the number of elements to the left of each node public int numLeft = 0; // the number of elements to the right of each node public int numRight = 0; // the color of a node public int color; RedBlackNode() { color = BLACK; numLeft = 0; numRight = 0; parent = null; left = null; right = null; } // Constructor which sets key to the argument. RedBlackNode(T key) { this(); this.key = key; } }// end class RedBlackNode static class RedBlackTree<T extends Comparable<T>> { // Root initialized to nil. private RedBlackNode<T> nil = new RedBlackNode<T>(); private RedBlackNode<T> root = nil; public RedBlackTree() { root.left = nil; root.right = nil; root.parent = nil; } // @param: X, The node which the lefRotate is to be performed on. // Performs a leftRotate around X. private void leftRotate(RedBlackNode<T> x) { // Call leftRotateFixup() which updates the numLeft // and numRight values. leftRotateFixup(x); // Perform the left rotate as described in the algorithm // in the course text. RedBlackNode<T> y; y = x.right; x.right = y.left; // Check for existence of y.left and make pointer changes if (!isNil(y.left)) { y.left.parent = x; } y.parent = x.parent; // X's parent is nul if (isNil(x.parent)) { root = y; } // X is the left child of it's parent else if (x.parent.left == x) { x.parent.left = y; } // X is the right child of it's parent. else { x.parent.right = y; } // Finish of the leftRotate y.left = x; x.parent = y; }// end leftRotate(RedBlackNode X) // @param: X, The node which the leftRotate is to be performed on. // Updates the numLeft & numRight values affected by leftRotate. private void leftRotateFixup(RedBlackNode x) { // Case 1: Only X, X.right and X.right.right always are not nil. if (isNil(x.left) && isNil(x.right.left)) { x.numLeft = 0; x.numRight = 0; x.right.numLeft = 1; } // Case 2: X.right.left also exists in addition to Case 1 else if (isNil(x.left) && !isNil(x.right.left)) { x.numLeft = 0; x.numRight = 1 + x.right.left.numLeft + x.right.left.numRight; x.right.numLeft = 2 + x.right.left.numLeft + x.right.left.numRight; } // Case 3: X.left also exists in addition to Case 1 else if (!isNil(x.left) && isNil(x.right.left)) { x.numRight = 0; x.right.numLeft = 2 + x.left.numLeft + x.left.numRight; } // Case 4: X.left and X.right.left both exist in addtion to Case 1 else { x.numRight = 1 + x.right.left.numLeft + x.right.left.numRight; x.right.numLeft = 3 + x.left.numLeft + x.left.numRight + x.right.left.numLeft + x.right.left.numRight; } }// end leftRotateFixup(RedBlackNode X) // @param: X, The node which the rightRotate is to be performed on. // Updates the numLeft and numRight values affected by the Rotate. private void rightRotate(RedBlackNode<T> y) { // Call rightRotateFixup to adjust numRight and numLeft values rightRotateFixup(y); // Perform the rotate as described in the course text. RedBlackNode<T> x = y.left; y.left = x.right; // Check for existence of X.right if (!isNil(x.right)) { x.right.parent = y; } x.parent = y.parent; // y.parent is nil if (isNil(y.parent)) { root = x; } // y is a right child of it's parent. else if (y.parent.right == y) { y.parent.right = x; } // y is a left child of it's parent. else { y.parent.left = x; } x.right = y; y.parent = x; }// end rightRotate(RedBlackNode y) // @param: y, the node around which the righRotate is to be performed. // Updates the numLeft and numRight values affected by the rotate private void rightRotateFixup(RedBlackNode y) { // Case 1: Only y, y.left and y.left.left exists. if (isNil(y.right) && isNil(y.left.right)) { y.numRight = 0; y.numLeft = 0; y.left.numRight = 1; } // Case 2: y.left.right also exists in addition to Case 1 else if (isNil(y.right) && !isNil(y.left.right)) { y.numRight = 0; y.numLeft = 1 + y.left.right.numRight + y.left.right.numLeft; y.left.numRight = 2 + y.left.right.numRight + y.left.right.numLeft; } // Case 3: y.right also exists in addition to Case 1 else if (!isNil(y.right) && isNil(y.left.right)) { y.numLeft = 0; y.left.numRight = 2 + y.right.numRight + y.right.numLeft; } // Case 4: y.right & y.left.right exist in addition to Case 1 else { y.numLeft = 1 + y.left.right.numRight + y.left.right.numLeft; y.left.numRight = 3 + y.right.numRight + y.right.numLeft + y.left.right.numRight + y.left.right.numLeft; } }// end rightRotateFixup(RedBlackNode y) public void insert(T key) { insert(new RedBlackNode<T>(key)); } // @param: z, the node to be inserted into the Tree rooted at root // Inserts z into the appropriate position in the RedBlackTree while // updating numLeft and numRight values. private void insert(RedBlackNode<T> z) { // Create a reference to root & initialize a node to nil RedBlackNode<T> y = nil; RedBlackNode<T> x = root; // While we haven't reached a the end of the tree keep // tryint to figure out where z should go while (!isNil(x)) { y = x; // if z.key is < than the current key, go left if (z.key.compareTo(x.key) < 0) { // Update X.numLeft as z is < than X x.numLeft++; x = x.left; } // else z.key >= X.key so go right. else { // Update X.numGreater as z is => X x.numRight++; x = x.right; } } // y will hold z's parent z.parent = y; // Depending on the value of y.key, put z as the left or // right child of y if (isNil(y)) { root = z; } else if (z.key.compareTo(y.key) < 0) { y.left = z; } else { y.right = z; } // Initialize z's children to nil and z's color to red z.left = nil; z.right = nil; z.color = RedBlackNode.RED; // Call insertFixup(z) insertFixup(z); }// end insert(RedBlackNode z) // @param: z, the node which was inserted and may have caused a violation // of the RedBlackTree properties // Fixes up the violation of the RedBlackTree properties that may have // been caused during insert(z) private void insertFixup(RedBlackNode<T> z) { RedBlackNode<T> y = nil; // While there is a violation of the RedBlackTree properties.. while (z.parent.color == RedBlackNode.RED) { // If z's parent is the the left child of it's parent. if (z.parent == z.parent.parent.left) { // Initialize y to z 's cousin y = z.parent.parent.right; // Case 1: if y is red...recolor if (y.color == RedBlackNode.RED) { z.parent.color = RedBlackNode.BLACK; y.color = RedBlackNode.BLACK; z.parent.parent.color = RedBlackNode.RED; z = z.parent.parent; } // Case 2: if y is black & z is a right child else if (z == z.parent.right) { // leftRotaet around z's parent z = z.parent; leftRotate(z); } // Case 3: else y is black & z is a left child else { // recolor and rotate round z's grandpa z.parent.color = RedBlackNode.BLACK; z.parent.parent.color = RedBlackNode.RED; rightRotate(z.parent.parent); } } // If z's parent is the right child of it's parent. else { // Initialize y to z's cousin y = z.parent.parent.left; // Case 1: if y is red...recolor if (y.color == RedBlackNode.RED) { z.parent.color = RedBlackNode.BLACK; y.color = RedBlackNode.BLACK; z.parent.parent.color = RedBlackNode.RED; z = z.parent.parent; } // Case 2: if y is black and z is a left child else if (z == z.parent.left) { // rightRotate around z's parent z = z.parent; rightRotate(z); } // Case 3: if y is black and z is a right child else { // recolor and rotate around z's grandpa z.parent.color = RedBlackNode.BLACK; z.parent.parent.color = RedBlackNode.RED; leftRotate(z.parent.parent); } } } // Color root black at all times root.color = RedBlackNode.BLACK; }// end insertFixup(RedBlackNode z) // @param: node, a RedBlackNode // @param: node, the node with the smallest key rooted at node public RedBlackNode<T> treeMinimum(RedBlackNode<T> node) { // while there is a smaller key, keep going left while (!isNil(node.left)) { node = node.left; } return node; }// end treeMinimum(RedBlackNode node) // @param: X, a RedBlackNode whose successor we must find // @return: return's the node the with the next largest key // from X.key public RedBlackNode<T> treeSuccessor(RedBlackNode<T> x) { // if X.left is not nil, call treeMinimum(X.right) and // return it's value if (!isNil(x.left)) { return treeMinimum(x.right); } RedBlackNode<T> y = x.parent; // while X is it's parent's right child... while (!isNil(y) && x == y.right) { // Keep moving up in the tree x = y; y = y.parent; } // Return successor return y; }// end treeMinimum(RedBlackNode X) // @param: z, the RedBlackNode which is to be removed from the the tree // Remove's z from the RedBlackTree rooted at root public void remove(RedBlackNode<T> v) { RedBlackNode<T> z = search(v.key); // Declare variables RedBlackNode<T> x = nil; RedBlackNode<T> y = nil; // if either one of z's children is nil, then we must remove z if (isNil(z.left) || isNil(z.right)) { y = z; } // else we must remove the successor of z else { y = treeSuccessor(z); } // Let X be the left or right child of y (y can only have one child) if (!isNil(y.left)) { x = y.left; } else { x = y.right; } // link X's parent to y's parent x.parent = y.parent; // If y's parent is nil, then X is the root if (isNil(y.parent)) { root = x; } // else if y is a left child, set X to be y's left sibling else if (!isNil(y.parent.left) && y.parent.left == y) { y.parent.left = x; } // else if y is a right child, set X to be y's right sibling else if (!isNil(y.parent.right) && y.parent.right == y) { y.parent.right = x; } // if y != z, trasfer y's satellite data into z. if (y != z) { z.key = y.key; } // Update the numLeft and numRight numbers which might need // updating due to the deletion of z.key. fixNodeData(x, y); // If y's color is black, it is a violation of the // RedBlackTree properties so call removeFixup() if (y.color == RedBlackNode.BLACK) { removeFixup(x); } }// end remove(RedBlackNode z) // @param: y, the RedBlackNode which was actually deleted from the tree // @param: key, the value of the key that used to be in y private void fixNodeData(RedBlackNode<T> x, RedBlackNode<T> y) { // Initialize two variables which will help us traverse the tree RedBlackNode<T> current = nil; RedBlackNode<T> track = nil; // if X is nil, then we will start updating at y.parent // Set track to y, y.parent's child if (isNil(x)) { current = y.parent; track = y; } // if X is not nil, then we start updating at X.parent // Set track to X, X.parent's child else { current = x.parent; track = x; } // while we haven't reached the root while (!isNil(current)) { // if the node we deleted has a different key than // the current node if (y.key != current.key) { // if the node we deleted is greater than // current.key then decrement current.numRight if (y.key.compareTo(current.key) > 0) { current.numRight--; } // if the node we deleted is less than // current.key thendecrement current.numLeft if (y.key.compareTo(current.key) < 0) { current.numLeft--; } } // if the node we deleted has the same key as the // current node we are checking else { // the cases where the current node has any nil // children and update appropriately if (isNil(current.left)) { current.numLeft--; } else if (isNil(current.right)) { current.numRight--; } // the cases where current has two children and // we must determine whether track is it's left // or right child and update appropriately else if (track == current.right) { current.numRight--; } else if (track == current.left) { current.numLeft--; } } // update track and current track = current; current = current.parent; } }//end fixNodeData() // @param: X, the child of the deleted node from remove(RedBlackNode v) // Restores the Red Black properties that may have been violated during // the removal of a node in remove(RedBlackNode v) private void removeFixup(RedBlackNode<T> x) { RedBlackNode<T> w; // While we haven't fixed the tree completely... while (x != root && x.color == RedBlackNode.BLACK) { // if X is it's parent's left child if (x == x.parent.left) { // set w = X's sibling w = x.parent.right; // Case 1, w's color is red. if (w.color == RedBlackNode.RED) { w.color = RedBlackNode.BLACK; x.parent.color = RedBlackNode.RED; leftRotate(x.parent); w = x.parent.right; } // Case 2, both of w's children are black if (w.left.color == RedBlackNode.BLACK && w.right.color == RedBlackNode.BLACK) { w.color = RedBlackNode.RED; x = x.parent; } // Case 3 / Case 4 else { // Case 3, w's right child is black if (w.right.color == RedBlackNode.BLACK) { w.left.color = RedBlackNode.BLACK; w.color = RedBlackNode.RED; rightRotate(w); w = x.parent.right; } // Case 4, w = black, w.right = red w.color = x.parent.color; x.parent.color = RedBlackNode.BLACK; w.right.color = RedBlackNode.BLACK; leftRotate(x.parent); x = root; } } // if X is it's parent's right child else { // set w to X's sibling w = x.parent.left; // Case 1, w's color is red if (w.color == RedBlackNode.RED) { w.color = RedBlackNode.BLACK; x.parent.color = RedBlackNode.RED; rightRotate(x.parent); w = x.parent.left; } // Case 2, both of w's children are black if (w.right.color == RedBlackNode.BLACK && w.left.color == RedBlackNode.BLACK) { w.color = RedBlackNode.RED; x = x.parent; } // Case 3 / Case 4 else { // Case 3, w's left child is black if (w.left.color == RedBlackNode.BLACK) { w.right.color = RedBlackNode.BLACK; w.color = RedBlackNode.RED; leftRotate(w); w = x.parent.left; } // Case 4, w = black, and w.left = red w.color = x.parent.color; x.parent.color = RedBlackNode.BLACK; w.left.color = RedBlackNode.BLACK; rightRotate(x.parent); x = root; } } }// end while // set X to black to ensure there is no violation of // RedBlack tree Properties x.color = RedBlackNode.BLACK; }// end removeFixup(RedBlackNode X) // @param: key, the key whose node we want to search for // @return: returns a node with the key, key, if not found, returns null // Searches for a node with key k and returns the first such node, if no // such node is found returns null public RedBlackNode<T> search(T key) { // Initialize a pointer to the root to traverse the tree RedBlackNode<T> current = root; // While we haven't reached the end of the tree while (!isNil(current)) { // If we have found a node with a key equal to key if (current.key.equals(key)) // return that node and exit search(int) { return current; } // go left or right based on value of current and key else if (current.key.compareTo(key) < 0) { current = current.right; } // go left or right based on value of current and key else { current = current.left; } } // we have not found a node whose key is "key" return null; }// end search(int key) // @param: key, any Comparable object // @return: return's the number of elements greater than key public int numGreater(T key) { // Call findNumGreater(root, key) which will return the number // of nodes whose key is greater than key return findNumGreater(root, key); }// end numGreater(int key) // @param: key, any Comparable object // @return: return's teh number of elements smaller than key public int numSmaller(T key) { // Call findNumSmaller(root,key) which will return // the number of nodes whose key is greater than key return findNumSmaller(root, key); }// end numSmaller(int key) // @param: node, the root of the tree, the key who we must // compare other node key's to. // @return: the number of nodes greater than key. public int findNumGreater(RedBlackNode<T> node, T key) { // Base Case: if node is nil, return 0 if (isNil(node)) { return 0; } // If key is less than node.key, all elements right of node are // greater than key, add this to our total and look to the left else if (key.compareTo(node.key) < 0) { return 1 + node.numRight + findNumGreater(node.left, key); } // If key is greater than node.key, then look to the right as // all elements to the left of node are smaller than key else { return findNumGreater(node.right, key); } }// end findNumGreater(RedBlackNode, int key) /** * Returns sorted list of keys greater than key. Size of list will not * exceed maxReturned * * @param key Key to search for * @param maxReturned Maximum number of results to return * @return List of keys greater than key. List may not exceed * maxReturned */ public List<T> getGreaterThan(T key, Integer maxReturned) { List<T> list = new ArrayList<T>(); getGreaterThan(root, key, list); return list.subList(0, Math.min(maxReturned, list.size())); } private void getGreaterThan(RedBlackNode<T> node, T key, List<T> list) { if (isNil(node)) { return; } else if (node.key.compareTo(key) > 0) { getGreaterThan(node.left, key, list); list.add(node.key); getGreaterThan(node.right, key, list); } else { getGreaterThan(node.right, key, list); } } // @param: node, the root of the tree, the key who we must compare other // node key's to. // @return: the number of nodes smaller than key. public int findNumSmaller(RedBlackNode<T> node, T key) { // Base Case: if node is nil, return 0 if (isNil(node)) { return 0; } // If key is less than node.key, look to the left as all // elements on the right of node are greater than key else if (key.compareTo(node.key) <= 0) { return findNumSmaller(node.left, key); } // If key is larger than node.key, all elements to the left of // node are smaller than key, add this to our total and look // to the right. else { return 1 + node.numLeft + findNumSmaller(node.right, key); } }// end findNumSmaller(RedBlackNode nod, int key) // @param: node, the RedBlackNode we must check to see whether it's nil // @return: return's true of node is nil and false otherwise private boolean isNil(RedBlackNode node) { // return appropriate value return node == nil; }// end isNil(RedBlackNode node) // @return: return's the size of the tree // Return's the # of nodes including the root which the RedBlackTree // rooted at root has. public int size() { // Return the number of nodes to the root's left + the number of // nodes on the root's right + the root itself. return root.numLeft + root.numRight + 1; }// end size() }// end class RedBlackTree }
java
1141
A
A. Game 23time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp plays "Game 23". Initially he has a number nn and his goal is to transform it to mm. In one move, he can multiply nn by 22 or multiply nn by 33. He can perform any number of moves.Print the number of moves needed to transform nn to mm. Print -1 if it is impossible to do so.It is easy to prove that any way to transform nn to mm contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).InputThe only line of the input contains two integers nn and mm (1≤n≤m≤5⋅1081≤n≤m≤5⋅108).OutputPrint the number of moves to transform nn to mm, or -1 if there is no solution.ExamplesInputCopy120 51840 OutputCopy7 InputCopy42 42 OutputCopy0 InputCopy48 72 OutputCopy-1 NoteIn the first example; the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840.120→240→720→1440→4320→12960→25920→51840. The are 77 steps in total.In the second example, no moves are needed. Thus, the answer is 00.In the third example, it is impossible to transform 4848 to 7272.
[ "implementation", "math" ]
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) throws IOException { // BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); // PrintWriter out=new PrintWriter(System.out); Scanner sc=new Scanner(System.in); // String testcases[]=br.readLine().split(" "); // int t=Integer.parseInt(testcases[0]); int n=sc.nextInt(); int m=sc.nextInt(); if(m%n==0) { if(m==n) System.out.println("0"); else { int req=m/n; int two=0; while(req%2==0) { two++; req/=2; } int three=0; while(req%3==0) { three++; req/=3; } if(req!=1) System.out.println("-1"); else System.out.println(two+three); } } else System.out.println("-1"); } // static ArrayList<Integer> getFactors(int n) // { // ArrayList<Integer> al=new ArrayList<>(); // for(int i=1;i<=Math.sqrt(n);i++) // { // if(n%i==0) // { // al.add(i); // if(n/i!=i) // al.add(n/i); // } // } // return al; // } // static void sort(long[] a) { // ArrayList<Long> l=new ArrayList<>(); // for (long i:a) l.add(i); // Collections.sort(l); // for (int i=0; i<a.length; i++) a[i]=l.get(i); // } // static int gcd(int a, int b) { // return b==0?a:gcd(b, a%b); // } // static int lcm(int a, int b){ // return ((a/gcd(a,b))*b); // } // static boolean coprime(int a, int b) { // if(a==1||b==1) // return true; // if ( __gcd(a, b) == 1) // return true; // else // return false; // } // private static boolean checkSquare(long n) // { // if (Math.ceil((double)Math.sqrt(n)) == // Math.floor((double)Math.sqrt(n))) // return true; // else // return false; // } // private static long floorSqrt(long x) // { // if (x == 0 || x == 1) // return x; // long start = 1, end = x / 2, ans = 0; // while (start <= end) { // long mid = (start + end) / 2; // if (mid * mid == x) // return (int)mid; // if (mid * mid < x) { // start = mid + 1; // ans = mid; // } // else // end = mid - 1; // } // return (long)ans; // } } // class Pair{ // int a=0; // int b=0; // Pair(int x, int y) // { // this.a=x; // this.b=y; // } // }
java
1296
E2
E2. String Coloring (hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is a hard version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters the minimum number of colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to find the minimum number of colors which you have to color the given string in so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIn the first line print one integer resres (1≤res≤n1≤res≤n) — the minimum number of colors in which you have to color the given string so that after coloring it can become sorted by some sequence of swaps.In the second line print any possible coloring that can be used to sort the string using some sequence of swaps described in the problem statement. The coloring is the array cc of length nn, where 1≤ci≤res1≤ci≤res and cici means the color of the ii-th character.ExamplesInputCopy9 abacbecfd OutputCopy2 1 1 2 1 2 1 2 1 2 InputCopy8 aaabbcbb OutputCopy2 1 2 1 2 1 2 1 1 InputCopy7 abcdedc OutputCopy3 1 1 1 1 1 2 3 InputCopy5 abcde OutputCopy1 1 1 1 1 1
[ "data structures", "dp" ]
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1296e2 { public static void main(String[] args) throws IOException { int n = ri(), ans[] = new int[n]; char[] s = rcha(); sgt sgt = new sgt(27, Integer::max, 0); for (int i = 0; i < n; ++i) { int c = s[i] - 'a'; sgt.upd(c, ans[i] = sgt.qry(c + 1, 27) + 1); } prln(maxof(ans)); prln(ans); close(); } @FunctionalInterface interface IntOperator { int merge(int a, int b); } static class sgt { IntOperator op; int n, sgt[], id; sgt(int sz, IntOperator operator, int identity) { n = sz; sgt = new int[4 * n + 5]; op = operator; id = identity; } sgt(int[] a, IntOperator operator, int identity) { n = a.length; sgt = new int[4 * n + 5]; op = operator; build(1, a, 0, n - 1); id = identity; } void set(int i, int x) { set(1, i, x, 0, n - 1); } void upd(int i, int x) { upd(1, i, x, 0, n - 1); } int qry(int l, int r) { return qry(1, l, r - 1, 0, n - 1); } void set(int node, int i, int x, int l, int r) { if (l == r) { sgt[node] = x; } else { int m = l + (r - l) / 2; if (i <= m) { set(node << 1, i, x, l, m); } else { set(node << 1 | 1, i, x, m + 1, r); } pull(node); } } void upd(int node, int i, int x, int l, int r) { if (l == r) { sgt[node] = op.merge(sgt[node], x); } else { int m = l + (r - l) / 2; if (i <= m) { upd(node << 1, i, x, l, m); } else { upd(node << 1 | 1, i, x, m + 1, r); } pull(node); } } int qry(int node, int i, int j, int l, int r) { if (r < i || j < l) { return id; } else if (i <= l && r <= j) { return sgt[node]; } else { int m = l + (r - l) / 2; return op.merge(qry(node << 1, i, j, l, m), qry(node << 1 | 1, i, j, m + 1, r)); } } void build(int node, int[] a, int l, int r) { if (l == r) { sgt[node] = a[l]; } else { int m = l + (r - l) / 2; build(node << 1, a, l, m); build(node << 1 | 1, a, m + 1, r); pull(node); } } void pull(int node) { sgt[node] = op.merge(sgt[node << 1], sgt[node << 1 | 1]); } } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __rand = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e9 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int fli(double d) {return (int)d;} static int cei(double d) {return (int)ceil(d);} static long fll(double d) {return (long)d;} static long cel(double d) {return (long)ceil(d);} static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);} static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);} static int lcm(int a, int b) {return a * b / gcf(a, b);} static long lcm(long a, long b) {return a * b / gcf(a, b);} static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;} static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);} // array util static void reverse(int[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(double[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static void rsort(double[] a) {shuffle(a); sort(a);} static int[] copy(int[] a) {int[] ans = new int[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static long[] copy(long[] a) {long[] ans = new long[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static double[] copy(double[] a) {double[] ans = new double[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static char[] copy(char[] a) {char[] ans = new char[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} // graph util static List<List<Integer>> g(int n) {List<List<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;} static List<Set<Integer>> sg(int n) {List<Set<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;} static void c(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);} static void cto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);} static void dc(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);} static void dcto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);} // input static void r() throws IOException {input = new StringTokenizer(rline());} static int ri() throws IOException {return Integer.parseInt(rline());} static long rl() throws IOException {return Long.parseLong(rline());} static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for(int i = 0; i < n; ++i) a[i] = ni(); return a;} static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for(int i = 0; i < n; ++i) a[i] = ni() - 1; return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for(int i = 0; i < n; ++i) a[i] = nl(); return a;} static char[] rcha() throws IOException {return rline().toCharArray();} static String rline() throws IOException {return __in.readLine();} static String n() {return input.nextToken();} static int rni() throws IOException {r(); return ni();} static int ni() {return Integer.parseInt(n());} static long rnl() throws IOException {r(); return nl();} static long nl() {return Long.parseLong(n());} static double rnd() throws IOException {r(); return nd();} static double nd() {return Double.parseDouble(n());} static List<List<Integer>> rg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;} static void rg(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);} static List<List<Integer>> rdg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;} static void rdg(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);} static List<Set<Integer>> rsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;} static void rsg(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);} static List<Set<Integer>> rdsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;} static void rdsg(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {__out.println("yes");} static void pry() {__out.println("Yes");} static void prY() {__out.println("YES");} static void prno() {__out.println("no");} static void prn() {__out.println("No");} static void prN() {__out.println("NO");} static void pryesno(boolean b) {__out.println(b ? "yes" : "no");}; static void pryn(boolean b) {__out.println(b ? "Yes" : "No");} static void prYN(boolean b) {__out.println(b ? "YES" : "NO");} static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(double... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next()); else __out.println();} static void h() {__out.println("hlfd"); flush();} static void flush() {__out.flush();} static void close() {__out.close();} }
java
1305
A
A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100)  — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000)  — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000)  — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2 3 1 8 5 8 4 5 3 1 7 5 6 1 2 OutputCopy1 8 5 8 4 5 5 1 7 6 2 1 NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.
[ "brute force", "constructive algorithms", "greedy", "sortings" ]
import java.util.*; public class practice { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int t = scan.nextInt(); while (t --> 0) { int n = scan.nextInt(); int a[] = new int[n]; int b[] = new int[n]; for (int i = 0; i < n; i++) a[i] = scan.nextInt(); for (int i = 0; i < n; i++) b[i] = scan.nextInt(); Arrays.sort(a); Arrays.sort(b); for (int i = 0; i < n; i++) System.out.print(a[i] + " "); System.out.println(); for (int i = 0; i < n; i++) System.out.print(b[i] + " "); System.out.println(); } scan.close(); } }
java
13
A
A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3 ≤ A ≤ 1000).OutputOutput should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7/3InputCopy3OutputCopy2/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively.
[ "implementation", "math" ]
import java.util.Scanner; public class Main { public static int converter(int val,int base){ int res = 0; while(val > 0){ int d = val%base; val = val/base; res += d; } return res; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int finalans = 0; int count = 0; for(int i = 2;i<n;i++){ finalans += converter(n,i); count++; } for(int i = count-1;i>=2;i--){ if(finalans %i == 0 && count%i == 0){ finalans = finalans/i; count = count/i; } } System.out.println(finalans + "/" + count); } }
java
1284
D
D. New Year and Conferencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputFilled with optimism; Hyunuk will host a conference about how great this new year will be!The conference will have nn lectures. Hyunuk has two candidate venues aa and bb. For each of the nn lectures, the speaker specified two time intervals [sai,eai][sai,eai] (sai≤eaisai≤eai) and [sbi,ebi][sbi,ebi] (sbi≤ebisbi≤ebi). If the conference is situated in venue aa, the lecture will be held from saisai to eaieai, and if the conference is situated in venue bb, the lecture will be held from sbisbi to ebiebi. Hyunuk will choose one of these venues and all lectures will be held at that venue.Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x,y][x,y] overlaps with a lecture held in interval [u,v][u,v] if and only if max(x,u)≤min(y,v)max(x,u)≤min(y,v).We say that a participant can attend a subset ss of the lectures if the lectures in ss do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue aa or venue bb to hold the conference.A subset of lectures ss is said to be venue-sensitive if, for one of the venues, the participant can attend ss, but for the other venue, the participant cannot attend ss.A venue-sensitive set is problematic for a participant who is interested in attending the lectures in ss because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.InputThe first line contains an integer nn (1≤n≤1000001≤n≤100000), the number of lectures held in the conference.Each of the next nn lines contains four integers saisai, eaieai, sbisbi, ebiebi (1≤sai,eai,sbi,ebi≤1091≤sai,eai,sbi,ebi≤109, sai≤eai,sbi≤ebisai≤eai,sbi≤ebi).OutputPrint "YES" if Hyunuk will be happy. Print "NO" otherwise.You can print each letter in any case (upper or lower).ExamplesInputCopy2 1 2 3 6 3 4 7 8 OutputCopyYES InputCopy3 1 3 2 4 4 5 6 7 3 4 5 5 OutputCopyNO InputCopy6 1 5 2 9 2 4 5 8 3 6 7 11 7 10 12 16 8 11 13 17 9 12 14 18 OutputCopyYES NoteIn second example; lecture set {1,3}{1,3} is venue-sensitive. Because participant can't attend this lectures in venue aa, but can attend in venue bb.In first and third example, venue-sensitive set does not exist.
[ "binary search", "data structures", "hashing", "sortings" ]
//package com.cf.hello2020;//package com.cf.r664; 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.PrintWriter; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.SortedMap; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; public class D { private FastScanner in; private PrintWriter out; public static void main(String[] args) { new D().run(); } private void run() { in = new FastScanner(System.in); out = new PrintWriter(System.out); int n = in.nextInt(); List<Speaker> speakers = IntStream.range(0, n).mapToObj(i -> Speaker.read(in)).collect(Collectors.toList()); if (existsSensitiveness(speakers)) { out.println("NO"); } else { out.println("YES"); } out.close(); } private boolean existsSensitiveness(List<Speaker> speakers) { for (int i = 0; i < 2; i++) { if (existsSensitiveness(speakers, i)) { return true; } } return false; } private boolean existsSensitiveness(List<Speaker> speakers, int intersectingIdx) { List<Event> events = IntStream.range(0, speakers.size()) .boxed() .flatMap(idx -> Stream.of(new Event(idx, true, speakers.get(idx).s[intersectingIdx]), new Event(idx, false, speakers.get(idx).e[intersectingIdx]))) .sorted() .collect(Collectors.toList()); Multiset<Integer> beginningsOnTheOtherVenue = new Multiset<>(Integer::compareTo); Multiset<Integer> endingsOnTheOtherVenue = new Multiset<>(Integer::compareTo); for (Event e : events) { if (e.opening) { beginningsOnTheOtherVenue.addOne(speakers.get(e.idx).s[1 - intersectingIdx]); endingsOnTheOtherVenue.addOne(speakers.get(e.idx).e[1 - intersectingIdx]); if (endingsOnTheOtherVenue.size() > 1 && endingsOnTheOtherVenue.smallest() < beginningsOnTheOtherVenue.biggest()) { return true; } } else { beginningsOnTheOtherVenue.removeOne(speakers.get(e.idx).s[1 - intersectingIdx]); endingsOnTheOtherVenue.removeOne(speakers.get(e.idx).e[1 - intersectingIdx]); } } return false; } private static class Event implements Comparable<Event> { int idx; boolean opening; int time; public Event(int idx, boolean opening, int time) { this.idx = idx; this.opening = opening; this.time = time; } @Override public int compareTo(Event o) { return 2 * Integer.compare(time, o.time) - Boolean.compare(opening, o.opening); } @Override public String toString() { return "Event{" + "idx=" + idx + ", opening=" + opening + ", time=" + time + '}'; } } private static class Speaker { int[] s; int[] e; public Speaker(int[] s, int[] e) { this.s = s; this.e = e; } public static Speaker read(FastScanner scanner) { int sa = scanner.nextInt(); int ea = scanner.nextInt(); int sb = scanner.nextInt(); int eb = scanner.nextInt(); return new Speaker(new int[] {sa, sb}, new int[] {ea, eb}); } @Override public String toString() { return "Speaker{" + "s=" + Arrays.toString(s) + ", e=" + Arrays.toString(e) + '}'; } } private static class Multiset<T> { SortedMap<T, Integer> realMap; int in = 0; public Multiset(Comparator<T> comparator) { this.realMap = new TreeMap<>(comparator); } void addOne(T elem) { in++; realMap.put(elem, realMap.getOrDefault(elem, 0) + 1); } void removeOne(T elem) { in--; if (realMap.get(elem) == 1) realMap.remove(elem); else realMap.put(elem, realMap.get(elem) - 1); } T smallest() { return realMap.firstKey(); } T biggest() { return realMap.lastKey(); } public int size() { return in; } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String next() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } boolean hasMoreTokens() { while (st == null || !st.hasMoreTokens()) { String s = null; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } if (s == null) return false; st = new StringTokenizer(s); } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
java
1316
B
B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string: Pick an integer kk, (1≤k≤n1≤k≤n). For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s[i:i+k−1] of ss. For example, if string ss is qwer and k=2k=2, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length 22) weqr (after reversing the second substring of length 22) werq (after reversing the last substring of length 22) Hence, the resulting string after modifying ss with k=2k=2 is werq. Vasya wants to choose a kk such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of kk. Among all such kk, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string aa is lexicographically smaller than a string bb if and only if one of the following holds: aa is a prefix of bb, but a≠ba≠b; in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb. InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤50001≤t≤5000). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤50001≤n≤5000) — the length of the string ss.The second line of each test case contains the string ss of nn lowercase latin letters.It is guaranteed that the sum of nn over all test cases does not exceed 50005000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s′s′ achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1≤k≤n1≤k≤n) that you chose for performing the modification. If there are multiple values of kk that give the lexicographically smallest string, output the smallest value of kk among them.ExampleInputCopy6 4 abab 6 qwerty 5 aaaaa 6 alaska 9 lfpbavjsm 1 p OutputCopyabab 1 ertyqw 3 aaaaa 1 aksala 6 avjsmbpfl 5 p 1 NoteIn the first testcase of the first sample; the string modification results for the sample abab are as follows : for k=1k=1 : abab for k=2k=2 : baba for k=3k=3 : abab for k=4k=4 : babaThe lexicographically smallest string achievable through modification is abab for k=1k=1 and 33. Smallest value of kk needed to achieve is hence 11.
[ "brute force", "constructive algorithms", "implementation", "sortings", "strings" ]
import java.io.*; import java.lang.reflect.Array; import java.util.*; public class edu130 { //private static Object m; static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } 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()); } String nextLine() { String str = ""; try { str = br.readLine().trim(); } catch (Exception e) { e.printStackTrace(); } return str; } } static class FastWriter { private final BufferedWriter bw; public FastWriter() { this.bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(Object object) throws IOException { bw.append("" + object); } public void println(Object object) throws IOException { print(object); bw.append("\n"); } public void close() throws IOException { bw.close(); } } public static boolean func(long x,long k){ return (k-((x*x)+(x)+1))%(2*x)==0; } public static void gg(int [] arr, int l, int r, int count , int[] ans){ if(r<l){ return; } if(r==l){ ans[l]=count; return; } int m=l; for(int i=l+1;i<=r;i++){ if(arr[i]>arr[m]){ m=i; } } ans[m]=count; gg(arr,l,m-1,count+1,ans); gg(arr,m+1,r,count+1,ans); } public static void main(String[] args) { //RSRRSRSSSR try { FastReader sc = new FastReader(); FastWriter out = new FastWriter(); int t=sc.nextInt(); while(t-->0) { int n=sc.nextInt(); String s=sc.next(); HashMap<String,ArrayList<Integer>> map=new HashMap<>(); map.put(s,new ArrayList<>()); map.get(s).add(1); for(int i=2;i<=n;i++){ if(i==n){ StringBuilder ff=new StringBuilder(s); map.putIfAbsent(ff.reverse().toString(),new ArrayList<>() ); map.get(ff.toString()).add(i); }else{ StringBuilder ff=new StringBuilder(s.substring(0,i-1)); StringBuilder ss=new StringBuilder(s.substring(i-1,n)); if((n-(i-1))%2==0 ){ ss.append(ff); }else{ ss.append(ff.reverse()); } map.putIfAbsent(ss.toString(),new ArrayList<>()); map.get(ss.toString()).add(i); } } // System.out.println(map); String [] arr=new String[map.size()]; int k=0; for(String key:map.keySet()){ arr[k++]= key.toString(); } Arrays.sort(arr); String gg=arr[0]; System.out.println(gg); //System.out.println(map); //StringBuilder str=new StringBuilder(gg); //System.out.println(map.get(str.toString())); //System.out.println(map.get(gg)); System.out.println(map.get(gg).get(0)); } }catch(Exception e){ return; } } private static char check(char c, char c1, char c2) { if(c2=='-'){ for(int i=0;i<26;i++){ char gg=(char)('a'+i); if(gg!=c && gg!=c1 ){ return gg; } } return '+'; }else{ for(int i=0;i<26;i++){ char gg=(char)('a'+i); if(gg!=c && gg!=c1 && gg!=c2){ return gg; } } return '+'; } } private static char get(StringBuilder sb, int i,char ff,char ss) { if(i==sb.length()-1){ for(int f = 0; f<26; f++){ if((char)('a'+f)!=ff ){ return (char) ('a'+ f); } } } else if(i==sb.length()-2){ for(int f = 0; f<26; f++){ if((char)('a'+f)!=ff && (char)('a'+f)!=ss && (char)('a'+f)!=sb.charAt(i+1) ){ return (char) ('a'+ f); } } }else{ for(int f = 0; f<26; f++){ if((char)('a'+f)!=ff && (char)('a'+f)!=ss && (char)('a'+f)!=sb.charAt(i+1) && (char)('a'+f)!=sb.charAt(i+2)){ return (char) ('a'+ f); } } } return 'l'; } public static int gg(int num){ int count=0; while(num>0){ count++; num=(num>>1); } return count; } private static void swap(int[] arr, int i, int ii) { int temp=arr[i]; arr[i]=arr[ii]; arr[ii]=temp; } public static int lcm(int a,int b){ return (a/gcd(a,b))*b; } private static int gcd(int a, int b) { if(b==0)return a; return gcd(b,a%b); } static class Pair { int a; int b; Pair(int a, int b) { this.a = a; this.b = b; } } }
java
1290
B
B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions: If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss; If we write the strings t1,t2,…,tkt1,t2,…,tk in order, the resulting string will be equal to tt; For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= "gamegame". Then the string t=t= "megamage" is a reducible anagram of ss, we may choose for example s1=s1= "game", s2=s2= "gam", s3=s3= "e" and t1=t1= "mega", t2=t2= "mag", t3=t3= "e": On the other hand, we can prove that t=t= "memegaga" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105)  — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.ExamplesInputCopyaaaaa 3 1 1 2 4 5 5 OutputCopyYes No Yes InputCopyaabbbbbbc 6 1 2 2 4 2 2 1 9 5 7 3 5 OutputCopyNo Yes Yes Yes No No NoteIn the first sample; in the first and third queries; the substring is "a"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand; in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= "a", s2=s2= "aa", t1=t1= "a", t2=t2= "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram.
[ "binary search", "constructive algorithms", "data structures", "strings", "two pointers" ]
import java.io.*; import java.util.*; public class Main{ /* Integer.parseInt(re.readLine()); Integer.parseInt(tk.nextToken()); tk = new StringTokenizer(re.readLine()); */ private static StringTokenizer tk; private static BufferedReader re; private static ArrayList<TreeSet<Integer>> list; private static void tokenize()throws IOException{ tk = new StringTokenizer(re.readLine()); } public static void main(String []args)throws IOException{ re = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); char s[] = re.readLine().toCharArray(); list = new ArrayList<>(); for(int i=0; i<26; i++) list.add(new TreeSet<>()); for(int i=0; i<s.length; i++){ int k = s[i]-'a'; list.get(k).add(i); } int q = Integer.parseInt(re.readLine()); while(q-->0){ tokenize(); int l = Integer.parseInt(tk.nextToken())-1, r = Integer.parseInt(tk.nextToken())-1; if(r == l) pw.println("Yes"); else if(s[l] != s[r]) pw.println("Yes"); else{ int count = 0; for(int i=0; i<26; i++){ int fp; if(list.get(i).ceiling(l) != null){ fp = list.get(i).ceiling(l); if(fp <= r) count++; } } if(count > 2) pw.println("Yes"); else pw.println("No"); } } pw.flush(); pw.close(); } }
java
1305
C
C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10 8 5 OutputCopy3InputCopy3 12 1 4 5 OutputCopy0InputCopy3 7 1 4 9 OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7.
[ "brute force", "combinatorics", "math", "number theory" ]
import java.util.*; import java.io.*; public class Main { static long mod = 1000000007; static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); public static void main(String[] args) throws IOException { FastReader sc = new FastReader(); int t = 1; while( t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); int arr[] = new int[n]; for( int i = 0 ;i < n ;i++) { arr[i] = sc.nextInt(); } if( n > 1000) { out.println(0); } else { long ans = 1; for( int i = 0 ;i < n ;i++) { for( int j = i+1 ;j < n ;j++) { ans*=Math.abs(arr[j] - arr[i])%m; ans%=m; } } out.println(ans); } } out.flush(); } /* * time for a change */ public static boolean ifpowof2(long n ) { return ((n&(n-1)) == 0); } static boolean isprime(long x ) { if( x== 2) { return true; } if( x%2 == 0) { return false; } for( long i = 3 ;i*i <= x ;i+=2) { if( x%i == 0) { return false; } } return true; } static boolean[] sieveOfEratosthenes(long n) { boolean prime[] = new boolean[(int)n + 1]; for (int i = 0; i <= n; i++) { prime[i] = true; } for (long p = 2; p * p <= n; p++) { if (prime[(int)p] == true) { for (long i = p * p; i <= n; i += p) prime[(int)i] = false; } } return prime; } public static int[] nextLargerElement(int[] arr, int n) { Stack<Integer> stack = new Stack<>(); int rtrn[] = new int[n]; rtrn[n-1] = -1; stack.push( n-1); for( int i = n-2 ;i >= 0 ; i--){ int temp = arr[i]; int lol = -1; while( !stack.isEmpty() && arr[stack.peek()] <= temp){ if(arr[stack.peek()] == temp ) { lol = stack.peek(); } stack.pop(); } if( stack.isEmpty()){ if( lol != -1) { rtrn[i] = lol; } else { rtrn[i] = -1; } } else{ rtrn[i] = stack.peek(); } stack.push( i); } return rtrn; } static void mysort(int[] arr) { for(int i=0;i<arr.length;i++) { int rand = (int) (Math.random() * arr.length); int loc = arr[rand]; arr[rand] = arr[i]; arr[i] = loc; } Arrays.sort(arr); } static void mySort(long[] arr) { for(int i=0;i<arr.length;i++) { int rand = (int) (Math.random() * arr.length); long loc = arr[rand]; arr[rand] = arr[i]; arr[i] = loc; } Arrays.sort(arr); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } static long rightmostsetbit(long n) { return n&-n; } static long leftmostsetbit(long n) { long k = (long)(Math.log(n) / Math.log(2)); return k; } static HashMap<Long,Long> primefactor( long n){ HashMap<Long ,Long> hm = new HashMap<>(); long temp = 0; while( n%2 == 0) { temp++; n/=2; } if( temp!= 0) { hm.put( 2L, temp); } long c = (long)Math.sqrt(n); for( long i = 3 ; i <= c ; i+=2) { temp = 0; while( n% i == 0) { temp++; n/=i; } if( temp!= 0) { hm.put( i, temp); } } if( n!= 1) { hm.put( n , 1L); } return hm; } static ArrayList<Long> allfactors(long abs) { HashMap<Long,Integer> hm = new HashMap<>(); ArrayList<Long> rtrn = new ArrayList<>(); for( long i = 2 ;i*i <= abs; i++) { if( abs% i == 0) { hm.put( i , 0); hm.put(abs/i, 0); } } for( long x : hm.keySet()) { rtrn.add(x); } if( abs != 0) { rtrn.add(abs); } return rtrn; } public static int[][] prefixsum( int n , int m , int arr[][] ){ int prefixsum[][] = new int[n+1][m+1]; for( int i = 1 ;i <= n ;i++) { for( int j = 1 ; j<= m ; j++) { int toadd = 0; if( arr[i-1][j-1] == 1) { toadd = 1; } prefixsum[i][j] = toadd + prefixsum[i][j-1] + prefixsum[i-1][j] - prefixsum[i-1][j-1]; } } return prefixsum; } 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
1320
D
D. Reachable Stringstime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIn this problem; we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string ss starting from the ll-th character and ending with the rr-th character as s[l…r]s[l…r]. The characters of each string are numbered from 11.We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.Binary string aa is considered reachable from binary string bb if there exists a sequence s1s1, s2s2, ..., sksk such that s1=as1=a, sk=bsk=b, and for every i∈[1,k−1]i∈[1,k−1], sisi can be transformed into si+1si+1 using exactly one operation. Note that kk can be equal to 11, i. e., every string is reachable from itself.You are given a string tt and qq queries to it. Each query consists of three integers l1l1, l2l2 and lenlen. To answer each query, you have to determine whether t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1].InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of string tt.The second line contains one string tt (|t|=n|t|=n). Each character of tt is either 0 or 1.The third line contains one integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of queries.Then qq lines follow, each line represents a query. The ii-th line contains three integers l1l1, l2l2 and lenlen (1≤l1,l2≤|t|1≤l1,l2≤|t|, 1≤len≤|t|−max(l1,l2)+11≤len≤|t|−max(l1,l2)+1) for the ii-th query.OutputFor each query, print either YES if t[l1…l1+len−1]t[l1…l1+len−1] is reachable from t[l2…l2+len−1]t[l2…l2+len−1], or NO otherwise. You may print each letter in any register.ExampleInputCopy5 11011 3 1 3 3 1 4 2 1 2 3 OutputCopyYes Yes No
[ "data structures", "hashing", "strings" ]
//package round625; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Random; public class D { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); char[] s = ns(n); int[] cum = new int[n+1]; for(int i = 0;i < n;i++){ cum[i+1] = cum[i] + s[i]-'0'; } int[] one = new int[n+1]; for(int i = n-1;i >= 0;i--){ if(s[i] == '1'){ one[i] = one[i+1] + 1; }else{ one[i] = 0; } } boolean[] stands = new boolean[n]; Arrays.fill(stands, true); boolean[] first = new boolean[n]; for(int i = 0;i < n-1;i++){ if(s[i] == s[i+1] && s[i] == '1'){ first[i] = true; stands[i] = stands[i+1] = false; i++; } } Random gen = new Random(); long mul0 = BigInteger.probablePrime(61, gen).longValue(); SegmentTreeRSQHash st0 = new SegmentTreeRSQHash(s, stands, mul0); long mul1 = BigInteger.probablePrime(61, gen).longValue(); SegmentTreeRSQHash st1 = new SegmentTreeRSQHash(s, stands, mul1); for(int Q = ni();Q > 0;Q--){ int a = ni()-1, b = ni()-1, len = ni(); if(cum[b+len] - cum[b] != cum[a+len] - cum[a]){ out.println("No"); continue; } long[] HA0 = hash(a, len, st0, s, stands, first, one); long[] HA1 = hash(a, len, st1, s, stands, first, one); long[] HB0 = hash(b, len, st0, s, stands, first, one); long[] HB1 = hash(b, len, st1, s, stands, first, one); if(HA0[0] == HB0[0] && HA0[1] == HB0[1] && HA1[0] == HB1[0]){ out.println("Yes"); }else{ out.println("No"); } } } long[] addLast(long[] h, int x, SegmentTreeRSQHash st) { return new long[]{ SegmentTreeRSQHash.mod(SegmentTreeRSQHash.mul(h[0], st.MUL) + x), h[1]+1 }; } long[] addFirst(long[] h, int x, SegmentTreeRSQHash st) { return new long[]{ SegmentTreeRSQHash.mod(SegmentTreeRSQHash.mul(st.pows[(int)h[1]], x) + h[0]), h[1]+1 }; } long[] hash(int a, int len, SegmentTreeRSQHash st, char[] s, boolean[] stands, boolean[] first, int[] one) { if(one[a] >= len){ if(len % 2 == 1){ return new long[]{'1', 1}; }else{ return new long[]{0, 0}; } }else if(first[a] || stands[a]){ if(first[a+len-1]){ return addLast(st.sum(a, a+len), '1', st); }else{ return st.sum(a, a+len); } }else if(one[a] % 2 == 0){ if(first[a+len-1]){ return addLast(st.sum(a+one[a], a+len), '1', st); }else{ return st.sum(a+one[a], a+len); } }else{ if(first[a+len-1]){ return addFirst(addLast(st.sum(a, a+len), '1', st), '1', st); }else{ return addFirst(st.sum(a, a+len), '1', st); } } } public static class SegmentTreeRSQHash { public int M, H, N; public long[] st; public long MUL; public int[] stands; public long[] pows; // public long[] gas; static long mod = (1L<<61)-1; public static long mul(long a, long b) { long al = a&(1L<<31)-1, ah = a>>>31; long bl = b&(1L<<31)-1, bh = b>>>31; long low = al * bl; // <2^62 long mid = al * bh + bl * ah; // < 2^62 long high = ah * bh + (mid>>>31); // < 2^60 + 2^31 < 2^61 // high*2^62 = high*2 (mod 2^61-1) long ret = mod(mod(2*high + low) + ((mid&(1L<<31)-1)<<31)); return ret; } public static long mod(long a) { while(a >= mod)a -= mod; while(a < 0)a += mod; return a; } private static long[] makePows(long M, int n) { long[] ret = new long[n+1]; ret[0] = 1; for(int i = 1;i <= n;i++)ret[i] = mul(ret[i-1], M); return ret; } private void init() { pows = makePows(MUL, H+1); } public SegmentTreeRSQHash(char[] a, boolean[] stands, long MUL) { this.MUL = MUL; N = a.length; M = Integer.highestOneBit(Math.max(N-1, 1))<<2; H = M>>>1; st = new long[M]; this.stands = new int[M]; for(int i = 0;i < N;i++){ this.stands[H+i] = stands[i] ? 1 : 0; st[H+i] = stands[i] ? a[i] : 0; } init(); for(int i = (M>>1)-1;i >= 1;i--){ propagate(i); } } private void propagate(int i) { stands[i] = stands[2*i] + stands[2*i+1]; st[i] = mod(mul(st[2*i], pows[stands[2*i+1]])+st[2*i+1]); } public long[] sum(int l, int r) { return sum(l, r, 0, H, 1); } protected long[] sum(int l, int r, int cl, int cr, int cur) { if(l <= cl && cr <= r){ return new long[]{st[cur], stands[cur]}; }else{ long[] L = null, R = null; int mid = cl+cr>>>1; if(cl < r && l < mid){ L = sum(l, r, cl, mid, 2*cur); } if(mid < r && l < cr){ R = sum(l, r, mid, cr, 2*cur+1); } if(L == null)return R; if(R == null)return L; // trq(L, R); L[0] = mod(mul(L[0], pows[(int)R[1]]) + R[0]); L[1] += R[1]; // trq(L); return L; } } private static void trq(Object... o) { System.out.println(Arrays.deepToString(o)); } } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new D().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
java
1292
B
B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0 2 4 20 OutputCopy3InputCopy1 1 2 3 1 0 15 27 26 OutputCopy2InputCopy1 1 2 3 1 0 2 2 1 OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.
[ "brute force", "constructive algorithms", "geometry", "greedy", "implementation" ]
; import java.util.*; import java.io.*; import static java.lang.Long.max; import static java.lang.Math.abs; import static java.lang.Math.pow; public class Main { static FastReader in=new FastReader(); public static void main(String [] args) { long x=in.nextLong(),y=in.nextLong(),ax=in.nextLong(),ay=in.nextLong(),bx=in.nextLong(),by=in.nextLong(); long xs=in.nextLong(),ys=in.nextLong(),t=in.nextLong(); ArrayList<Long>xx=new ArrayList(),yy=new ArrayList(); xx.add(x);yy.add(y); for(;xx.get(xx.size()-1)<=(((Long.MAX_VALUE-1)/ax)-bx)&&yy.get(yy.size()-1)<=(((Long.MAX_VALUE-1)/ay)-by);){ xx.add(xx.get(xx.size()-1)*ax+bx); yy.add(yy.get(yy.size()-1)*ay+by); } long xl=xs,yl=ys,tt=t; for(int i=0;i<xx.size();i++){ if(tt>=abs(xl-xx.get(i))+abs(yl-yy.get(i))&&abs(xl-xx.get(i))+abs(yl-yy.get(i))>=0){an++;tt-=abs(xl-xx.get(i))+abs(yl-yy.get(i));xl=xx.get(i);yl=yy.get(i);} else {anl=max(ans,an);an=0; xl=xs;yl=ys;tt=t;} } xl=xs;yl=ys;tt=t; for(int i=xx.size()-1;i>=0;i--){ if(tt>=abs(xl-xx.get(i))+abs(yl-yy.get(i))&&abs(xl-xx.get(i))+abs(yl-yy.get(i))>=0){as++;tt-=abs(xl-xx.get(i))+abs(yl-yy.get(i));xl=xx.get(i);yl=yy.get(i);} else {anl=max(ans,as);as=0; xl=xs;yl=ys;tt=t;} } tryy(xx,yy,xs,ys,t); as=max(as,an); an=max(anl,an); System.out.println(max(ans,as)); } static long ans=0L,an,as=0,anl=0; static void tryy(ArrayList<Long> xx,ArrayList<Long> yy,long x,long y,long t){ int c=-1; long min =Long.MAX_VALUE-1,z=0,v=0; for(int i=0;i<xx.size();i++){ if(min> Math.abs(x-xx.get(i))+Math.abs(y-yy.get(i))&&Math.abs(x-xx.get(i))+Math.abs(y-yy.get(i))>=0){c=i;z=yy.get(i);v=xx.get(i);min= Math.abs(x-xx.get(i))+Math.abs(y-yy.get(i));} } if(min<=t){t-=min;ans++; xx.remove(c);yy.remove(c); tryy(xx,yy,v,z,t); } } static long gcd(long g,long x){ if(x<1)return g; else return gcd(x,g%x); } } 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; } } class Sorting{ public static int[] bucketSort(int[] array, int bucketCount) { if (bucketCount <= 0) throw new IllegalArgumentException("Invalid bucket count"); if (array.length <= 1) return array; //trivially sorted int high = array[0]; int low = array[0]; for (int i = 1; i < array.length; i++) { //find the range of input elements if (array[i] > high) high = array[i]; if (array[i] < low) low = array[i]; } double interval = ((double)(high - low + 1))/bucketCount; //range of one bucket ArrayList<Integer> buckets[] = new ArrayList[bucketCount]; for (int i = 0; i < bucketCount; i++) { //initialize buckets buckets[i] = new ArrayList(); } for (int i = 0; i < array.length; i++) { //partition the input array buckets[(int)((array[i] - low)/interval)].add(array[i]); } int pointer = 0; for (int i = 0; i < buckets.length; i++) { Collections.sort(buckets[i]); //mergeSort for (int j = 0; j < buckets[i].size(); j++) { //merge the buckets array[pointer] = buckets[i].get(j); pointer++; } } return array; } }
java
1296
F
F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values: his departure station ajaj; his arrival station bjbj; minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4 1 2 3 2 3 4 2 1 2 5 1 3 3 OutputCopy5 3 5 InputCopy6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 OutputCopy5 3 1 2 1 InputCopy6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 OutputCopy-1
[ "constructive algorithms", "dfs and similar", "greedy", "sortings", "trees" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.StringTokenizer; import java.util.stream.Collectors; import java.util.stream.IntStream; public class F { private static final FastReader in = new FastReader(); private static final FastWriter out = new FastWriter(); public static void main(String[] args) { new F().run(); } private void run() { var t = 1; while (t-- > 0) { solve(); } out.flush(); } private Graph<?>.Tree tree; private LCA lca; private int[] w; private void solve() { var n = in.nextInt(); var g = Graph.ofInt(n); var edges = new ArrayList<IntPair>(n - 1); for (var i = 1; i < n; i++) { var u = in.nextInt() - 1; var v = in.nextInt() - 1; g.addBidirectedEdges(u, v); edges.add(IntPair.of(u, v)); } tree = g.asTree(0); lca = new LCA(tree); var m = in.nextInt(); var queries = new ArrayList<IntTriple>(); for (var i = 0; i < m; i++) { var q = IntTriple.of(in.nextInt() - 1, in.nextInt() - 1, in.nextInt()); queries.add(q); } queries.sort(Comparator.comparing(IntTriple::getC).reversed()); w = new int[n]; for (var q : queries) { if (!mark(q)) { out.println(-1); return ; } } var f = edges.stream() .mapToInt(e -> { var u = e.a; var v = e.b; if (tree.parents[u] == v) { var t = u; u = v; v = t; } return w[v] > 0 ? w[v] : 1; }) .toArray(); out.println(f); } boolean mark(IntTriple q) { boolean valid = false; int ancestor = lca.query(q.a, q.b); int u = q.a; while (u != ancestor) { if (w[u] == 0) { w[u] = q.c; } valid |= w[u] == q.c; u = tree.parents[u]; } int v = q.b; while (v != ancestor) { if (w[v] == 0) { w[v] = q.c; } valid |= w[v] == q.c; v = tree.parents[v]; } return valid; } } class FastReader { private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static StringTokenizer in; public String next() { while (in == null || !in.hasMoreTokens()) { try { in = new StringTokenizer(br.readLine()); } catch (IOException e) { return null; } } return in.nextToken(); } public BigDecimal nextBigDecimal() { return new BigDecimal(next()); } public BigInteger nextBigInteger() { return new BigInteger(next()); } public boolean nextBoolean() { return Boolean.valueOf(next()); } public byte nextByte() { return Byte.valueOf(next()); } public double nextDouble() { return Double.valueOf(next()); } public double[] nextDoubleArray(int length) { var a = new double[length]; for (var i = 0; i < length; i++) { a[i] = nextDouble(); } return a; } public int nextInt() { return Integer.valueOf(next()); } public int[] nextIntArray(int length) { var a = new int[length]; for (var i = 0; i < length; i++) { a[i] = nextInt(); } return a; } public long nextLong() { return Long.valueOf(next()); } public long[] nextLongArray(int length) { var a = new long[length]; for (var i = 0; i < length; i++) { a[i] = nextLong(); } return a; } } class FastWriter extends PrintWriter { public FastWriter() { super(System.out); } public void println(boolean[] a) { for (var i = 0; i < a.length; i++) { print(a[i]); print(i + 1 < a.length ? ' ' : '\n'); } } public void println(double[] a) { for (var i = 0; i < a.length; i++) { print(a[i]); print(i + 1 < a.length ? ' ' : '\n'); } } public void println(int[] a) { for (var i = 0; i < a.length; i++) { print(a[i]); print(i + 1 < a.length ? ' ' : '\n'); } } public void println(long[] a) { for (var i = 0; i < a.length; i++) { print(a[i]); print(i + 1 < a.length ? ' ' : '\n'); } } public void println(Object... a) { for (var i = 0; i < a.length; i++) { print(a[i]); print(i + 1 < a.length ? ' ' : '\n'); } } public <T> void println(List<T> l) { println(l.toArray()); } public void debug(String name, Object o) { String value = Arrays.deepToString(new Object[] { o }); value = value.substring(1, value.length() - 1); System.err.println(name + " => " + value); } } class Graph<T> { public final int n; private final List<List<Edge<T>>> adjacencyList; private final T defaultWeight; Graph(int n, T defaultWeight) { this.n = n; this.adjacencyList = new ArrayList<>(n); this.defaultWeight = defaultWeight; for (var i = 0; i < n; i++) { this.adjacencyList.add(new ArrayList<>()); } } public static Graph<Integer> ofInt(int n) { return new Graph<Integer>(n, 1); } public static Graph<Long> ofLong(int n) { return new Graph<Long>(n, 1L); } public static Graph<Double> ofDouble(int n) { return new Graph<Double>(n, 1.0); } public void addEdge(int u, int v) { addEdge(u, v, defaultWeight); } public void addEdge(int u, int v, T w) { adjacencyList.get(u).add(Edge.of(v, w)); } public void addBidirectedEdges(int u, int v) { addBidirectedEdges(u, v, defaultWeight); } public void addBidirectedEdges(int u, int v, T w) { addEdge(u, v, w); addEdge(v, u, w); } public List<Edge<T>> neighbors(int u) { return adjacencyList.get(u); } public int degree(int u) { return neighbors(u).size(); } public Tree asTree(int root) { return new Tree(root); } @Override public String toString() { String adj = IntStream.range(0, n) .mapToObj(i -> " " + i + ": " + adjacencyList.get(i)) .collect(Collectors.joining(",\n")); return "Graph {\n" + " nodeCount: " + n + ",\n" + " adjacencyList: {\n" + adj + "\n" + " }\n" + "}"; } public class Tree { public final int root; public int[] parents; public int[] depths; public int[] subTreeSizes; public Tree(int root) { this.root = root; } public Tree saveParent() { this.parents = new int[n]; return this; } public Tree saveDepth() { this.depths = new int[n]; return this; } public Tree saveSubTreeSize() { this.subTreeSizes = new int[n]; return this; } public Tree build() { build(root, -1, 0); return this; } private void build(int u, int parent, int depth) { var children = neighbors(u).stream().filter(e -> e.v != parent).collect(Collectors.toList()); children.forEach(e -> build(e.v, u, depth + 1)); if (parents != null) { parents[u] = parent; } if (depths != null) { depths[u] = depth; } if (subTreeSizes != null) { subTreeSizes[u] = children.stream().mapToInt(e -> subTreeSizes[e.v]).sum() + 1; } } public int nodeCount() { return n; } public List<Edge<T>> children(int u) { return neighbors(u).stream().filter(e -> e.v != parents[u]).collect(Collectors.toList()); } public boolean isLeaf(int u) { return u == root ? false : neighbors(u).size() == 1; } } public static class Edge<T> { public final int v; public final T w; public Edge(int v, T w) { this.v = v; this.w = w; } public static <T> Edge<T> of(int v, T w) { return new Edge<>(v, w); } public int getV() { return v; } public T getW() { return w; } @Override public String toString() { return String.format("(%s, %s)", v, w); } } } class IntPair extends Pair<Integer, Integer> { IntPair(Integer a, Integer b) { super(a, b); } public static IntPair of(int a, int b) { return new IntPair(a, b); } } class IntTriple extends Triple<Integer, Integer, Integer> { IntTriple(Integer a, Integer b, Integer c) { super(a, b, c); } public static IntTriple of(int a, int b, int c) { return new IntTriple(a, b, c); } } class LCA { private final Graph<?>.Tree tree; private final List<Integer> eulerTour; private final int[] preOrderIds; private final int[] firstSeenInEulerTour; private final RMQ<Integer> rmq; public LCA(Graph<?>.Tree tree) { this.tree = tree .saveParent() .saveSubTreeSize() .build(); var n = tree.nodeCount(); this.eulerTour = new ArrayList<>(n * 2 - 1); this.preOrderIds = new int[n]; this.firstSeenInEulerTour = new int[n]; build(tree.root, 0); this.rmq = new RMQ<>(eulerTour, Comparator.comparing(u -> preOrderIds[u])); } private void build(int u, int preOrderId) { preOrderIds[u] = preOrderId++; firstSeenInEulerTour[u] = eulerTour.size(); eulerTour.add(u); for (var e : tree.children(u)) { build(e.v, preOrderId); preOrderId += tree.subTreeSizes[e.v]; eulerTour.add(u); } } public int query(int x, int y) { var l = firstSeenInEulerTour[x]; var r = firstSeenInEulerTour[y]; if (l > r) { var t = l; l = r; r = t; } return rmq.query(l, r + 1); } } class RMQ<T extends Comparable<T>> { private final int n; private final List<T> values; private final Comparator<T> comparator; private final int[][] ranges; public RMQ(List<T> values) { this(values, Comparator.naturalOrder()); } public RMQ(List<T> values, Comparator<T> comparator) { this.values = values; this.comparator = comparator; this.n = values.size(); this.ranges = new int[leftMostOneBit(n) + 1][]; build(); } private int leftMostOneBit(int x) { return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x); } private void build() { ranges[0] = new int[n]; for (var i = 0; i < n; i++) { ranges[0][i] = i; } for (var i = 1; 1 << i <= n; i++) { ranges[i] = new int[n - (1 << i) + 1]; for (var j = 0; j + (1 << i) <= n; j++) { ranges[i][j] = betterIndex(ranges[i - 1][j], ranges[i - 1][j + (1 << (i - 1))]); } } } private int betterIndex(int l, int r) { return comparator.compare(values.get(l), values.get(r)) < 0 ? l : r; } public int queryIndex(int l, int r) { var exponent = leftMostOneBit(r - l); return betterIndex(ranges[exponent][l], ranges[exponent][r - (1 << exponent)]); } public T query(int l, int r) { return values.get(queryIndex(l, r)); } } class Triple<T, U, V> { public T a; public U b; public V c; Triple(T a, U b, V c) { this.a = a; this.b = b; this.c = c; } public static <T, U, V> Triple<T, U, V> of(T a, U b, V c) { return new Triple<>(a, b, c); } public T getA() { return a; } public U getB() { return b; } public V getC() { return c; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof Triple)) return false; var other = (Triple<?, ?, ?>) obj; return Objects.equals(a, other.a) && Objects.equals(b, other.b) && Objects.equals(c, other.c); } @Override public String toString() { return String.format("(%s, %s, %s)", a, b, c); } } class Pair<T, U> { public T a; public U b; Pair(T a, U b) { this.a = a; this.b = b; } public static <T, U> Pair<T, U> of(T a, U b) { return new Pair<>(a, b); } public T getA() { return a; } public U getB() { return b; } @Override public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof Pair)) return false; var other = (Pair<?, ?>) obj; return Objects.equals(a, other.a) && Objects.equals(b, other.b); } @Override public String toString() { return String.format("(%s, %s)", a, b); } }
java
1305
A
A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100)  — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000)  — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000)  — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2 3 1 8 5 8 4 5 3 1 7 5 6 1 2 OutputCopy1 8 5 8 4 5 5 1 7 6 2 1 NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.
[ "brute force", "constructive algorithms", "greedy", "sortings" ]
import java.util.Arrays; import java.util.Scanner; public class KuroniAndTheGifts { public static void main(String[]args) { Scanner sn = new Scanner(System.in); int t = sn.nextInt(); for(int i=0; i<t; i++) { int n = sn.nextInt(); sn.nextLine(); String[] a = sn.nextLine().split(" "); String[] b = sn.nextLine().split(" "); int an[] = new int[a.length]; int bn[] = new int[b.length]; for(int j=0; j<a.length; j++) { an[j] = Integer.parseInt(a[j]); bn[j] = Integer.parseInt(b[j]); } Arrays.sort(an); Arrays.sort(bn); StringBuffer sb = new StringBuffer(); for(int j =0; j<a.length; j++) { sb.append(an[j]+" "); } sb.append("\n"); for(int j =0; j<b.length; j++) { sb.append(bn[j]+" "); } System.out.println(sb); } } }
java
1312
F
F. Attack on Red Kingdomtime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe Red Kingdom is attacked by the White King and the Black King!The Kingdom is guarded by nn castles, the ii-th castle is defended by aiai soldiers. To conquer the Red Kingdom, the Kings have to eliminate all the defenders. Each day the White King launches an attack on one of the castles. Then, at night, the forces of the Black King attack a castle (possibly the same one). Then the White King attacks a castle, then the Black King, and so on. The first attack is performed by the White King.Each attack must target a castle with at least one alive defender in it. There are three types of attacks: a mixed attack decreases the number of defenders in the targeted castle by xx (or sets it to 00 if there are already less than xx defenders); an infantry attack decreases the number of defenders in the targeted castle by yy (or sets it to 00 if there are already less than yy defenders); a cavalry attack decreases the number of defenders in the targeted castle by zz (or sets it to 00 if there are already less than zz defenders). The mixed attack can be launched at any valid target (at any castle with at least one soldier). However, the infantry attack cannot be launched if the previous attack on the targeted castle had the same type, no matter when and by whom it was launched. The same applies to the cavalry attack. A castle that was not attacked at all can be targeted by any type of attack.The King who launches the last attack will be glorified as the conqueror of the Red Kingdom, so both Kings want to launch the last attack (and they are wise enough to find a strategy that allows them to do it no matter what are the actions of their opponent, if such strategy exists). The White King is leading his first attack, and you are responsible for planning it. Can you calculate the number of possible options for the first attack that allow the White King to launch the last attack? Each option for the first attack is represented by the targeted castle and the type of attack, and two options are different if the targeted castles or the types of attack are different.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.Then, the test cases follow. Each test case is represented by two lines. The first line contains four integers nn, xx, yy and zz (1≤n≤3⋅1051≤n≤3⋅105, 1≤x,y,z≤51≤x,y,z≤5). The second line contains nn integers a1a1, a2a2, ..., anan (1≤ai≤10181≤ai≤1018).It is guaranteed that the sum of values of nn over all test cases in the input does not exceed 3⋅1053⋅105.OutputFor each test case, print the answer to it: the number of possible options for the first attack of the White King (or 00, if the Black King can launch the last attack no matter how the White King acts).ExamplesInputCopy3 2 1 3 4 7 6 1 1 2 3 1 1 1 2 2 3 OutputCopy2 3 0 InputCopy10 6 5 4 5 2 3 2 3 1 3 1 5 2 3 10 4 4 2 3 8 10 8 5 2 2 1 4 8 5 3 5 3 5 9 2 10 4 5 5 5 2 10 4 2 2 3 1 4 1 10 3 1 5 3 9 8 7 2 5 4 5 8 8 3 5 1 4 5 5 10 OutputCopy0 2 1 2 5 12 5 0 0 2
[ "games", "two pointers" ]
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.Set; import java.util.HashMap; import java.util.InputMismatchException; import java.io.IOException; import java.util.HashSet; import java.util.Map; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Rustam Musin (t.me/musin_acm) */ 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); FAtakaNaKrasnoeKorolevstvo solver = new FAtakaNaKrasnoeKorolevstvo(); solver.solve(1, in, out); out.close(); } static class FAtakaNaKrasnoeKorolevstvo { Map<IntIntPair, Integer> g; int x; int y; int z; public void solve(int testNumber, InputReader in, OutputWriter out) { if (false) { for (x = 1; x <= 5; x++) { for (y = 1; y <= 5; y++) { for (z = 1; z <= 5; z++) { int c = findCycleLen(x, y, z); System.err.println(x + " " + y + " " + z + " " + c); } } } return; } if (false) { test(); return; } int t = in.readInt(); while (t-- > 0) { int n = in.readInt(); int x = in.readInt(); int y = in.readInt(); int z = in.readInt(); int cycle = findCycleLen(x, y, z); // System.err.println(checkCycleLen(cycle, 100_000)); int[] a = new int[n]; for (int i = 0; i < n; i++) { long X = in.readLong(); if (X > 1000) { X = ((X - 1000) % cycle) + 1000; } a[i] = (int) X; } int fullXor = 0; for (int hp : a) { fullXor ^= getGrundy(hp, 0); } int answer = 0; for (int hp : a) { if ((fullXor ^ getGrundy(hp, 0) ^ getGrundy(hp - x, 0)) == 0) { answer++; } if ((fullXor ^ getGrundy(hp, 0) ^ getGrundy(hp - y, 1)) == 0) { answer++; } if ((fullXor ^ getGrundy(hp, 0) ^ getGrundy(hp - z, 2)) == 0) { answer++; } } // out.printLine(answer, checkCycleLen(cycle, 100_000)); out.printLine(answer); } } void test() { x = 1; y = 2; z = 3; test1(); } void test1() { g = new HashMap<>(); for (int hp = 0; hp <= 100; hp++) { System.err.print(hp); for (int last = 0; last <= 2; last++) { System.err.print(" " + getGrundy(hp, last)); } System.err.println(); } } int getGrundy(int hp, int last) { if (hp <= 0) { return 0; } IntIntPair p = IntIntPair.makePair(hp, last); if (g.containsKey(p)) { return g.get(p); } Set<Integer> res = new HashSet<>(); res.add(getGrundy(hp - x, 0)); if (last != 1) { res.add(getGrundy(hp - y, 1)); } if (last != 2) { res.add(getGrundy(hp - z, 2)); } for (int r = 0; ; r++) { if (!res.contains(r)) { g.put(p, r); return r; } } } int findCycleLen(int x, int y, int z) { this.x = x; this.y = y; this.z = z; this.g = new HashMap<>(); for (int cycleLen = 1; ; cycleLen++) { if (checkCycleLen(cycleLen, 1000)) { return cycleLen; } } } boolean checkCycleLen(int cycleLen, int iters) { for (int hp = 1000; hp < 1000 + iters; hp++) { for (int t = 0; t < 3; t++) { if (getGrundy(hp, t) != getGrundy(hp - cycleLen, t)) { return false; } } } return true; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void printLine(int i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { 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 isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class IntIntPair implements Comparable<IntIntPair> { public final int first; public final int second; public static IntIntPair makePair(int first, int second) { return new IntIntPair(first, second); } public IntIntPair(int first, int second) { this.first = first; this.second = second; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IntIntPair pair = (IntIntPair) o; return first == pair.first && second == pair.second; } public int hashCode() { int result = first; result = 31 * result + second; return result; } public String toString() { return "(" + first + "," + second + ")"; } public int compareTo(IntIntPair o) { int value = Integer.compare(first, o.first); if (value != 0) { return value; } return Integer.compare(second, o.second); } } }
java
1294
D
D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array; for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array; for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai−xai:=ai−x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,…,yj][y1,y2,…,yj].InputThe first line of the input contains two integers q,xq,x (1≤q,x≤4⋅1051≤q,x≤4⋅105) — the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0≤yj≤1090≤yj≤109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query — for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3 0 1 2 2 0 0 10 OutputCopy1 2 3 3 4 4 7 InputCopy4 3 1 2 1 2 OutputCopy0 0 0 0 NoteIn the first example: After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11. After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22. After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33. After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations). After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44. After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44. After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations: a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5, a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3, a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3, a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6, a[6]:=a[6]−3=10−3=7a[6]:=a[6]−3=10−3=7, a[6]:=a[6]−3=7−3=4a[6]:=a[6]−3=7−3=4. The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77.
[ "data structures", "greedy", "implementation", "math" ]
import java.util.*; import java.io.*; public class Main extends PrintWriter { Main() { super(System.out); } static boolean cases = false; // Solution void solve(int t) { int n = sc.nextInt(); int x = sc.nextInt(); int c[] = new int[n + 1]; int val[] = new int[n]; for (int i = 0; i < n; i++) { val[i] = i; } int ans = 0; for (int i = 0; i < n; i++) { int e = sc.nextInt(); e %= x; while (val[e] < n && c[val[e]] != 0) { val[e] += x; } if (val[e] < n) c[val[e]] = 1; while (c[ans] != 0) { ans++; } println(ans); } } public static void main(String[] args) { Main obj = new Main(); int c = 1; for (int t = (cases ? sc.nextInt() : 0); t > 1; t--, c++) obj.solve(c); obj.solve(c); obj.flush(); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } char[] readCharArray(int n) { char a[] = new char[n]; String s = sc.next(); for (int i = 0; i < n; i++) { a[i] = s.charAt(i); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } final int ima = Integer.MAX_VALUE; final int imi = Integer.MIN_VALUE; final long lma = Long.MAX_VALUE; final long lmi = Long.MIN_VALUE; static final long mod = (long) 1e9 + 7; private static final FastScanner sc = new FastScanner(); private PrintWriter out = new PrintWriter(System.out); }
java
1287
A
A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": "A" corresponds to an angry student "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt — the number of groups of students (1≤t≤1001≤t≤100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1≤ki≤1001≤ki≤100) — the number of students in the group, followed by a string sisi, consisting of kiki letters "A" and "P", which describes the ii-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInputCopy1 4 PPAP OutputCopy1 InputCopy3 12 APPAPPPAPPPP 3 AAP 3 PPA OutputCopy4 1 0 NoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after 11 minute — AAPAAPPAAPPP after 22 minutes — AAAAAAPAAAPP after 33 minutes — AAAAAAAAAAAP after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry.
[ "greedy", "implementation" ]
import java.util.Scanner; public class AngryStudents { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); int t=scanner.nextInt(); for (int i = 0; i < t; i++) { int n=scanner.nextInt(); scanner.nextLine(); String st=scanner.nextLine(); char[] x=st.toCharArray(); int r=-1; for (int i1 = 0; i1 < x.length; i1++) { if (x[i1]=='A') { r=i1; break; } } if (r==-1) { System.out.println(0); continue; } int num=0; int max=0; for (int i1 = r; i1 < x.length; i1++) { if (x[i1]=='P') num++; else if (num>max) {max=num;num=0;} else if (x[i1]=='A') num=0; if (i1==x.length-1 && num>max) max=num; } System.out.println(max); } } }
java
1284
A
A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12 sin im gye gap eul byeong jeong mu gi gyeong yu sul hae ja chuk in myo jin sa o mi sin 14 1 2 3 4 10 11 12 13 73 2016 2017 2018 2019 2020 OutputCopysinyu imsul gyehae gapja gyeongo sinmi imsin gyeyu gyeyu byeongsin jeongyu musul gihae gyeongja NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.
[ "implementation", "strings" ]
import java.util.Scanner; public class cf1284A { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); //num String n int m = sc.nextInt(); //num String m String[] s = new String[n]; String[] t = new String[m]; for(int i=0; i<n; i++) { s[i] = sc.next(); } for(int i=0; i<m; i++) { t[i] = sc.next(); } int q = sc.nextInt(); //numQueries while(q-- > 0) { int year = sc.nextInt(); System.out.println(s[(year-1) % n] + t[(year-1) % m]); } sc.close(); } }
java
1322
B
B. Presenttime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputCatherine received an array of integers as a gift for March 8. Eventually she grew bored with it; and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realized that she couldn't compute it for a very large array, thus she asked for your help. Can you do it? Formally, you need to compute(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)(a1+a2)⊕(a1+a3)⊕…⊕(a1+an)⊕(a2+a3)⊕…⊕(a2+an)…⊕(an−1+an)Here x⊕yx⊕y is a bitwise XOR operation (i.e. xx ^ yy in many modern programming languages). You can read about it in Wikipedia: https://en.wikipedia.org/wiki/Exclusive_or#Bitwise_operation.InputThe first line contains a single integer nn (2≤n≤4000002≤n≤400000) — the number of integers in the array.The second line contains integers a1,a2,…,ana1,a2,…,an (1≤ai≤1071≤ai≤107).OutputPrint a single integer — xor of all pairwise sums of integers in the given array.ExamplesInputCopy2 1 2 OutputCopy3InputCopy3 1 2 3 OutputCopy2NoteIn the first sample case there is only one sum 1+2=31+2=3.In the second sample case there are three sums: 1+2=31+2=3, 1+3=41+3=4, 2+3=52+3=5. In binary they are represented as 0112⊕1002⊕1012=01020112⊕1002⊕1012=0102, thus the answer is 2.⊕⊕ is the bitwise xor operation. To define x⊕yx⊕y, consider binary representations of integers xx and yy. We put the ii-th bit of the result to be 1 when exactly one of the ii-th bits of xx and yy is 1. Otherwise, the ii-th bit of the result is put to be 0. For example, 01012⊕00112=0110201012⊕00112=01102.
[ "binary search", "bitmasks", "constructive algorithms", "data structures", "math", "sortings" ]
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; // https://codeforces.com/contest/1322/submission/72635098 public class cf1322b_2 { public static void main(String[] args) throws IOException { int n = ri(), a[] = ria(n), ans = 0; if(n % 2 == 0){ for(int v : a){ ans ^= v; } } for (int i = 0; i < 25; ++i) { int tail[] = new int[n]; for (int j = 0; j < n; ++j) { tail[j] = a[j] % (1 << i); } tail = radix_sort(tail); int p = n - 1, x = 0; for (int j = 0; j < n - 1; ++j) { while (j < p && tail[j] + tail[p] >= 1 << i) { --p; } x ^= (n - 1) - max(j, p); } ans ^= (x & 1) << i; } prln(ans); close(); } public static int[] radix_sort(int[] f) { int n = f.length; int[] to = new int[n]; { int[] b = new int[65537]; for(int i = 0;i < n;i++)b[1+(f[i]&0xffff)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;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 < n;i++)b[1+(f[i]>>>16)]++; for(int i = 1;i <= 65536;i++)b[i]+=b[i-1]; for(int i = 0;i < n;i++)to[b[f[i]>>>16]++] = f[i]; int[] d = f; f = to; } return f; } /* static int[] radix_sort(int[] a) { int[] sorted = new int[a.length], cnt = new int[0x10001]; for (int i = 0; i < a.length; ++i) { ++cnt[1 + (a[i] & 0xffff)]; } for (int i = 0; i < 0xffff; ++i) { cnt[i + 1] += cnt[i]; } for (int i = 0; i < a.length; ++i) { sorted[cnt[a[i] & 0xffff]++] = a[i]; } a = sorted; fill(cnt, 0); for (int i = 0; i < a.length; ++i) { ++cnt[1 + (a[i] >>> 16)]; } for (int i = 0; i < 0xffff; ++i) { cnt[i + 1] += cnt[i]; } for (int i = 0; i < a.length; ++i) { sorted[cnt[a[i] >>> 16]++] = a[i]; } return sorted; } */ static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __rand = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e9 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int fli(double d) {return (int) d;} static int cei(double d) {return (int) ceil(d);} static long fll(double d) {return (long) d;} static long cel(double d) {return (long) ceil(d);} static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);} static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);} static int lcm(int a, int b) {return a * b / gcf(a, b);} static long lcm(long a, long b) {return a * b / gcf(a, b);} static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;} static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);} // array util static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static void rsort(double[] a) {shuffle(a); sort(a);} static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} // graph util static List<List<Integer>> g(int n) {List<List<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;} static List<Set<Integer>> sg(int n) {List<Set<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;} static void c(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);} static void cto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);} static void dc(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);} static void dcto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);} // input static void r() throws IOException {input = new StringTokenizer(rline());} static int ri() throws IOException {return Integer.parseInt(rline());} static long rl() throws IOException {return Long.parseLong(rline());} static double rd() throws IOException {return Double.parseDouble(rline());} static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;} static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;} static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;} static char[] rcha() throws IOException {return rline().toCharArray();} static String rline() throws IOException {return __in.readLine();} static String n() {return input.nextToken();} static int rni() throws IOException {r(); return ni();} static int ni() {return Integer.parseInt(n());} static long rnl() throws IOException {r(); return nl();} static long nl() {return Long.parseLong(n());} static double rnd() throws IOException {r(); return nd();} static double nd() {return Double.parseDouble(n());} static List<List<Integer>> rg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;} static void rg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);} static List<List<Integer>> rdg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;} static void rdg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);} static List<Set<Integer>> rsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;} static void rsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);} static List<Set<Integer>> rdsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;} static void rdsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {prln("yes");} static void pry() {prln("Yes");} static void prY() {prln("YES");} static void prno() {prln("no");} static void prn() {prln("No");} static void prN() {prln("NO");} static void pryesno(boolean b) {prln(b ? "yes" : "no");}; static void pryn(boolean b) {prln(b ? "Yes" : "No");} static void prYN(boolean b) {prln(b ? "YES" : "NO");} static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();} static void h() {prln("hlfd"); flush();} static void flush() {__out.flush();} static void close() {__out.close();}}
java
1310
A
A. Recommendationstime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputVK news recommendation system daily selects interesting publications of one of nn disjoint categories for each user. Each publication belongs to exactly one category. For each category ii batch algorithm selects aiai publications.The latest A/B test suggests that users are reading recommended publications more actively if each category has a different number of publications within daily recommendations. The targeted algorithm can find a single interesting publication of ii-th category within titi seconds. What is the minimum total time necessary to add publications to the result of batch algorithm execution, so all categories have a different number of publications? You can't remove publications recommended by the batch algorithm.InputThe first line of input consists of single integer nn — the number of news categories (1≤n≤2000001≤n≤200000).The second line of input consists of nn integers aiai — the number of publications of ii-th category selected by the batch algorithm (1≤ai≤1091≤ai≤109).The third line of input consists of nn integers titi — time it takes for targeted algorithm to find one new publication of category ii (1≤ti≤105)1≤ti≤105).OutputPrint one integer — the minimal required time for the targeted algorithm to get rid of categories with the same size.ExamplesInputCopy5 3 7 9 7 8 5 2 5 7 5 OutputCopy6 InputCopy5 1 2 3 4 5 1 1 1 1 1 OutputCopy0 NoteIn the first example; it is possible to find three publications of the second type; which will take 6 seconds.In the second example; all news categories contain a different number of publications.
[ "data structures", "greedy", "sortings" ]
/* ID: abdelra29 LANG: JAVA PROG: zerosum */ /* TO LEARN 2-euler tour */ /* TO SOLVE */ /* bit manipulation shit 1-Computer Systems: A Programmer's Perspective 2-hacker's delight */ /* TO WATCH */ import java.util.*; import java.math.*; import java.io.*; import java.text.DecimalFormat; import java.util.stream.Collectors; public class A{ static FastScanner scan=new FastScanner(); public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); static int BIT[]; static int BIT2[]; static int n; static int get(int x){ int res=0; x--; while(x>=1) { res+=BIT[x]; x-=(x&-x); } return res; } static void update(int x,int val) { //x++; while(x<=n) { BIT[x]+=val; x+=(x&-x); } } static int get2(int x) { int res=0; x++; while(x<=n) { res+=BIT2[x]; x+=(x&-x); } return res; } static void update2(int x,int val) { int res=0; //x--; while(x>=1) { //res+=BIT2[x]; BIT2[x]+=val; x-=(x&-x); } } public static void main(String[] args) throws Exception { /* very important tips 1-just fucking think backwards once in your shitty life 2-consider brute forcing and finding some patterns and observations 3-when you're in contest don't get out because you think there is no enough time 4-don't get stuck on one approach */ // scan=new FastScanner("D:\\usaco test data\\WW.txt"); // out = new PrintWriter("D:\\usaco test data\\WWW.txt"); /* READING 3-Introduction to DP with Bit-masking codeforces 4-Bit Manipulation hacker-earth 5-read more about mobious and inclusion-exclusion 6-read more about Fermat little theorem */ /* */ int tt=1; // tt=scan.nextInt(); int T=tt; outer:while(tt-->0) { int n=scan.nextInt(); Pair arr[]=new Pair[n]; Map<Integer,ArrayDeque<Integer>>map=new HashMap<Integer,ArrayDeque<Integer>>(); for(int i=0;i<n;i++){ arr[i]=new Pair(scan.nextInt(),0); } for(int i=0;i<n;i++) arr[i].y=scan.nextInt(); PriorityQueue<Long>pq=new PriorityQueue<Long>(Collections.reverseOrder()); Arrays.sort(arr); long sum=0,res=0; int i=0; for(int g=-100;pq.size()>0||i<n;g++) { while(i<n&&arr[i].x<=g) { sum+=arr[i].y; pq.add(arr[i].y); i++; } if(pq.size()>0) { sum-=pq.poll(); } else{ if(i<n) g=(int)arr[i].x-1; } res+=sum; } out.println(res); } out.close(); } static class special implements Comparable<special>{ int cnt,idx; String s; public special(int cnt,int idx,String s) { this.cnt=cnt; this.idx=idx; this.s=s; } @Override public int hashCode() { return (int)42; } @Override public boolean equals(Object o){ // System.out.println("FUCK"); if (o == this) return true; if (o.getClass() != getClass()) return false; special t = (special)o; return t.cnt == cnt && t.idx == idx; } public int compareTo(special o1) { if(o1.cnt==cnt) { return o1.idx-idx; } return o1.cnt-cnt; } } static long binexp(long a,long n) { if(n==0) return 1; long res=binexp(a,n/2); if(n%2==1) return res*res*a; else return res*res; } static long powMod(long base, long exp, long mod) { if (base == 0 || base == 1) return base; if (exp == 0) return 1; if (exp == 1) return (base % mod+mod)%mod; long R = (powMod(base, exp/2, mod) % mod+mod)%mod; R *= R; R %= mod; if ((exp & 1) == 1) { return (base * R % mod+mod)%mod; } else return (R %mod+mod)%mod; } static double dis(double x1,double y1,double x2,double y2) { return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); } static long mod(long x,long y) { if(x<0) x=x+(-x/y+1)*y; return x%y; } public static long pow(long b, long e) { long r = 1; while (e > 0) { if (e % 2 == 1) r = r * b ; b = b * b; e >>= 1; } return r; } private static void sort(int[] arr) { List<Integer> list = new ArrayList<>(); for (int object : arr) list.add(object); Collections.sort(list); //Collections.reverse(list); for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i); } private static void sort2(long[] arr) { List<Long> list = new ArrayList<>(); for (Long object : arr) list.add(object); Collections.sort(list); Collections.reverse(list); for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i); } 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 double[] nextDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } 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; } } } static class Pair implements Comparable<Pair>{ public long x, y,z; public Pair(long x1, long y1,long z1) { x=x1; y=y1; z=z1; } public Pair(long x1, long y1) { x=x1; y=y1; } @Override public int hashCode() { return (int)(x + 31 * y); } public String toString() { return x + " " + y+" "+z; } @Override public boolean equals(Object o){ if (o == this) return true; if (o.getClass() != getClass()) return false; Pair t = (Pair)o; return t.x == x && t.y == y&&t.z==z; } public int compareTo(Pair o) { return (int)(x-o.x); } } }
java
1305
E
E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,…,ana1,a2,…,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements: The score of each problem should be a positive integer not exceeding 109109. A harder problem should grant a strictly higher score than an easier problem. In other words, 1≤a1<a2<⋯<an≤1091≤a1<a2<⋯<an≤109. The balance of the score distribution, defined as the number of triples (i,j,k)(i,j,k) such that 1≤i<j<k≤n1≤i<j<k≤n and ai+aj=akai+aj=ak, should be exactly mm. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output −1−1.InputThe first and single line contains two integers nn and mm (1≤n≤50001≤n≤5000, 0≤m≤1090≤m≤109) — the number of problems and the required balance.OutputIf there is no solution, print a single integer −1−1.Otherwise, print a line containing nn integers a1,a2,…,ana1,a2,…,an, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInputCopy5 3 OutputCopy4 5 9 13 18InputCopy8 0 OutputCopy10 11 12 13 14 15 16 17 InputCopy4 10 OutputCopy-1 NoteIn the first example; there are 33 triples (i,j,k)(i,j,k) that contribute to the balance of the score distribution. (1,2,3)(1,2,3) (1,3,4)(1,3,4) (2,4,5)(2,4,5)
[ "constructive algorithms", "greedy", "implementation", "math" ]
//package round2020; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class E2 { InputStream is; PrintWriter out; String INPUT = ""; void solve() { // 5:4, 6:6 int n = ni(); int m = ni(); long max = (long)(n/2)*((n-1)/2); if(m > max){ out.println(-1); return; } for(int k = 1;k <= n;k++){ long lmax = (long)(k/2)*((k-1)/2); if(m <= lmax){ if(lmax == 0){ for(int i = 0;i < n;i++){ out.print(1000000000-n+i + " "); } out.println(); return; } long[] a = new long[n]; for(int i = 0;i < k-1;i++){ out.print(1+i + " "); a[i] = i+1; } long mm = k + (lmax-m)*2; out.print(k + (lmax-m)*2 + " "); a[k-1] = mm; for(int i = 0;i < n-k;i++){ a[k+i] = 1000000000 - (mm+1)*(n-k-1-i); out.print(1000000000 - (mm+1)*(n-k-1-i) + " "); } out.println(); check(a, m); return; } } } void check(long[] a, int K) { int n = a.length; for(int i = 0;i < n-1;i++){ assert a[i] < a[i+1]; } int ct = 0; for(int i = 0;i < n;i++){ for(int j = i+1;j < n;j++){ long x = a[i] + a[j]; if(Arrays.binarySearch(a, x) >= 0){ ct++; } } } assert ct == K; } public static boolean incAscending(int[] a, int base, boolean strict) { int n = a.length; for(int i = n-1;i >= 0;i--){ if(++a[i] + (strict ? n-1-i : 0) < base){ for(int j = i+1;j < n;j++)a[j] = a[j-1] + (strict ? 1 : 0); return true; } } return false; } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new E2().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
java
1296
A
A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5 2 2 3 4 2 2 8 8 3 3 3 3 4 5 5 5 5 4 1 1 1 1 OutputCopyYES NO YES NO NO
[ "math" ]
import java.util.*; import java.io.*; // import static java.lang.Math.max; //import static java.lang.Math.min; // import static java.lang.Math.abs; public class A_Array_with_Odd_Sum { static PrintWriter out; static void dbg(Object... o) { System.err.println(Arrays.deepToString(o)); } static final Scanner in = new Scanner(System.in); public static void main(String[] args) { out = new PrintWriter(System.out); int tcas = in.nextInt(); while (tcas-- > 0) { int n = in.nextInt(); int a[] = readIntArray(n); int sum=0; int ce=0; int co=0; for (int i = 0; i < n; i++) { if(a[i]%2==0){ ce++; } else{ co++; } sum+=a[i]; } if((ce>0 && co>0 && sum%2==0) || (sum%2!=0)){ out.println("YES"); } else{ out.println("NO"); } } in.close(); out.close(); } static long[] readLongArray(int n){ long b[] = new long[n]; for (int i = 0; i < n; i++) { b[i]= in.nextLong(); } return b; } static int[] readIntArray(int n){ int b[] = new int[n]; for (int i = 0; i < n; i++) { b[i]= in.nextInt(); } return b; } }
java
1307
B
B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109)  — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2 3 1 2 NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0).
[ "geometry", "greedy", "math" ]
import java.util.Scanner; import java.util.Arrays; import java.util.List; import java.util.ArrayList; public class Solution{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int kde = 0; kde < t; kde++){ int n = sc.nextInt(); int x = sc.nextInt(); int[] nums = new int[n]; for(int i = 0; i < n; i++){ nums[i] = sc.nextInt(); } Arrays.sort(nums); List<Integer> list = new ArrayList<>(); for(int a : nums){ list.add(a); } if(list.contains(x)){ System.out.println(1); continue; } else if(x < nums[n-1]) { System.out.println(2); continue; } int count = x / nums[n-1]; if(x % nums[n-1] != 0) count ++; System.out.println(count); } } }
java
1296
B
B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6 1 10 19 9876 12345 1000000000 OutputCopy1 11 21 10973 13716 1111111111
[ "math" ]
// package c1296; // // Codeforces Round #617 (Div. 3) 2020-02-04 06:35 // B. Food Buying // https://codeforces.com/contest/1296/problem/B // time limit per test 1 second; memory limit per test 256 megabytes // public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*' // // Mishka wants to buy some food in the nearby shop. Initially, he has s burles on his card. // // Mishka can perform the following operation any number of times (possibly, zero): choose some 1 <= // x <= s, buy food that costs exactly x burles and obtain \lfloor\frac{x}{10}\rfloor burles as a // cashback (in other words, Mishka spends x burles and obtains \lfloor\frac{x}{10}\rfloor back). // The operation \lfloor\frac{a}{b}\rfloor means a divided by b rounded down. // // It is guaranteed that you can always buy some food that costs x for any possible value of x. // // Your task is to say the maximum number of burles Mishka can spend if he buys food optimally. // // For example, if Mishka has s=19 burles then the maximum number of burles he can spend is 21. // Firstly, he can spend x=10 burles, obtain 1 burle as a cashback. Now he has s=10 burles, so can // spend x=10 burles, obtain 1 burle as a cashback and spend it too. // // You have to answer t independent test cases. // // Input // // The first line of the input contains one integer t (1 <= t <= 10^4) -- the number of test cases. // // The next t lines describe test cases. Each test case is given on a separate line and consists of // one integer s (1 <= s <= 10^9) -- the number of burles Mishka initially has. // // Output // // For each test case print the answer on it -- the maximum number of burles Mishka can spend if he // buys food optimally. // // Example /* input: 6 1 10 19 9876 12345 1000000000 output: 1 11 21 10973 13716 1111111111 */ // import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.lang.invoke.MethodHandles; import java.util.Random; import java.util.StringTokenizer; public class C1296B { static final int MOD = 998244353; static final Random RAND = new Random(); static int solve(int s) { int ans = 0; while (s >= 10) { int v = s / 10; ans += s - s % 10; s -= v * 9; } ans += s; return ans; } static boolean test = false; static void doTest() { if (!test) { return; } long t0 = System.currentTimeMillis(); System.out.format("%d msec\n", System.currentTimeMillis() - t0); System.exit(0); } public static void main(String[] args) { doTest(); MyScanner in = new MyScanner(); int T = in.nextInt(); for (int t = 1; t <= T; t++) { int s = in.nextInt(); int ans = solve(s); System.out.println(ans); } } static void output(int[] a) { if (a == null) { System.out.println("-1"); return; } StringBuilder sb = new StringBuilder(); for (int v : a) { sb.append(v); sb.append(' '); if (sb.length() > 4000) { System.out.print(sb.toString()); sb.setLength(0); } } System.out.println(sb.toString()); } static void myAssert(boolean cond) { if (!cond) { throw new RuntimeException("Unexpected"); } } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { try { final String USERDIR = System.getProperty("user.dir"); String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", ""); cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname; final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in"); br = new BufferedReader(new InputStreamReader(fin.exists() ? new FileInputStream(fin) : System.in)); } catch (Exception e) { br = new BufferedReader(new InputStreamReader(System.in)); } } public String next() { try { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
java
1311
F
F. Moving Pointstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn points on a coordinate axis OXOX. The ii-th point is located at the integer point xixi and has a speed vivi. It is guaranteed that no two points occupy the same coordinate. All nn points move with the constant speed, the coordinate of the ii-th point at the moment tt (tt can be non-integer) is calculated as xi+t⋅vixi+t⋅vi.Consider two points ii and jj. Let d(i,j)d(i,j) be the minimum possible distance between these two points over any possible moments of time (even non-integer). It means that if two points ii and jj coincide at some moment, the value d(i,j)d(i,j) will be 00.Your task is to calculate the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of points.The second line of the input contains nn integers x1,x2,…,xnx1,x2,…,xn (1≤xi≤1081≤xi≤108), where xixi is the initial coordinate of the ii-th point. It is guaranteed that all xixi are distinct.The third line of the input contains nn integers v1,v2,…,vnv1,v2,…,vn (−108≤vi≤108−108≤vi≤108), where vivi is the speed of the ii-th point.OutputPrint one integer — the value ∑1≤i<j≤n∑1≤i<j≤n d(i,j)d(i,j) (the sum of minimum distances over all pairs of points).ExamplesInputCopy3 1 3 2 -100 2 3 OutputCopy3 InputCopy5 2 1 4 3 5 2 2 2 3 4 OutputCopy19 InputCopy2 2 1 -3 0 OutputCopy0
[ "data structures", "divide and conquer", "implementation", "sortings" ]
// package c1311; // // Codeforces Round #624 (Div. 3) 2020-02-24 06:35 // F. Moving Points // https://codeforces.com/contest/1311/problem/F // time limit per test 2 seconds; memory limit per test 256 megabytes // public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*' // // There are n points on a coordinate axis OX. The i-th point is located at the integer point x_i // and has a speed v_i. It is guaranteed that no two points occupy the same coordinate. All n points // move with the constant speed, the coordinate of the i-th point at the moment t (t ) is calculated // as x_i + t * v_i. // // Consider two points i and j. Let d(i, j) be the minimum possible distance between these two // points over any possible moments of time (even ). It means that if two points i and j coincide at // some moment, the value d(i, j) will be 0. // // Your task is to calculate the value \sum\limits_{1 <= i < j <= n} d(i, j) (the sum of minimum // distances over all pairs of points). // // Input // // The first line of the input contains one integer n (2 <= n <= 2 * 10^5) -- the number of points. // // The second line of the input contains n integers x_1, x_2, ..., x_n (1 <= x_i <= 10^8), where x_i // is the initial coordinate of the i-th point. It is guaranteed that all x_i are distinct. // // The third line of the input contains n integers v_1, v_2, ..., v_n (-10^8 <= v_i <= 10^8), where // v_i is the speed of the i-th point. // // Output // // Print one integer -- the value \sum\limits_{1 <= i < j <= n} d(i, j) (the sum of minimum // distances over all pairs of points). // // Example /* input: 3 1 3 2 -100 2 3 output: 3 input: 5 2 1 4 3 5 2 2 2 3 4 output: 19 input: 2 2 1 -3 0 output: 0 */ // import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.StringTokenizer; public class C1311F { static final int MOD = 998244353; static final Random RAND = new Random(); static long solve(int[] x, int[] v) { int n = x.length; long ans = 0; List<int[]> points = new ArrayList<>(); for (int i = 0; i < n; i++) { points.add(new int[] {x[i], v[i]}); } Collections.sort(points, (y, z) -> y[1] - z[1]); // normalize and compact speed into [1,m) int m = 1; int b = 0; while (b < n) { int e = b + 1; while (e < n && points.get(e)[1] == points.get(b)[1]) { e++; } for (int i = b; i < e; i++) { points.get(i)[1] = m; } m++; b = e; } // Sort by ascending x Collections.sort(points, (y, z) -> y[0] - z[0]); // System.out.format(" points:%s\n", Utils.traceListIntArray(points)); FenwickTree ftCnt = new FenwickTree(m); FenwickTree ftX = new FenwickTree(m); long sumx = 0; for (int i = n-1; i >= 0; i--) { int xi = points.get(i)[0]; int vi = points.get(i)[1]; // . . . . . . . // ^ ^ // xi xj // how many points with speed >= vi long cnt = n-1-i - ftCnt.sum(vi - 1); long sum = sumx - ftX.sum(vi - 1); ans += sum - xi * cnt; sumx += xi; ftCnt.add(vi, 1); ftX.add(vi, xi); } return ans; } static class FenwickTree { private long[] arr; private final int n; public FenwickTree(int n) { this.n = n; // caller valid index range is [0,n-1] // the n + 1 here is for internal convenience this.arr = new long[n + 1]; } public FenwickTree(int[] nums) { this(nums.length); for (int i = 0; i < n; ++i) { this.add(i, nums[i]); } } static int next(int idx) { // round up the last section of 1s, for example: // 10110 -> 10110 + 11...101010 & 10110 = 10110 + 10 = 11000 return idx + (-idx & idx); } static int parent(int idx) { // Trim the last 1 return idx - (-idx & idx); } // Increase value at index by delta public void add(int index, int delta) { index++; while (index <= n) { arr[index] += delta; index = next(index); } } // get sum of elements arr[0..index], inclusive. index < n (size - 1) public long sum(int index) { index = Math.min(index + 1, n); long ans = 0; while (index > 0) { ans += arr[index]; index = parent(index); } return ans; } } static long solveB(int[] x, int[] v) { int n = x.length; long ans = 0; List<int[]> points = new ArrayList<>(); for (int i = 0; i < n; i++) { points.add(new int[] {x[i], v[i]}); } Collections.sort(points, (y, z)->y[0]-z[0]); // System.out.format(" points:%s\n", Utils.traceListIntArray(points)); for (int i = 0; i < n; i++) { int xi = points.get(i)[0]; int vi = points.get(i)[1]; for (int j = i + 1; j < n; j++) { int xj = points.get(j)[0]; int vj = points.get(j)[1]; // . . . . . . . // ^ ^ // xi xj if (vi <= vj) { ans += xj - xi; } } } return ans; } static long solveNaive(int[] x, int[] v) { int n = x.length; long ans = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (x[i] < x[j]) { // . . . . . . . // ^ ^ // xi xj if (v[i] <= v[j]) { ans += x[j] - x[i]; } } else if (x[i] == x[j]) { } else { // . . . . . . . // ^ ^ // xj xi if (v[j] <= v[i]) { ans += x[i] - x[j]; } } } } return ans; } static String trace(int[][] a) { return Arrays.deepToString(a).replace(" ", "").replace('[', '{').replace(']', '}'); } static String trace(int[] a) { return Arrays.toString(a).replace(" ", "").replace('[', '{').replace(']', '}'); } static void test(long exp, int[] x, int[] v) { long ans = solve(x, v); System.out.format("x:%s v:%s => %d %s\n", trace(x), trace(v), ans, ans == exp ? "":"Expected " + exp); myAssert(ans ==exp); } static boolean test = false; static void doTest() { if (!test) { return; } long t0 = System.currentTimeMillis(); test(3, new int[] {1,3,2}, new int[] {-100,2,3}); test(19, new int[] {2,1,4,3,5}, new int[] {2,2,2,3,4}); test(0, new int[] {2,1}, new int[] {-3,0}); System.out.format("%d msec\n", System.currentTimeMillis() - t0); System.exit(0); } public static void main(String[] args) { doTest(); MyScanner in = new MyScanner(); int n = in.nextInt(); int[] x = new int[n]; for (int i = 0; i < n; i++) { x[i] = in.nextInt(); } int[] v = new int[n]; for (int i = 0; i < n; i++) { v[i] = in.nextInt(); } long ans = solve(x, v); System.out.println(ans); } static void output(int[] a) { if (a == null) { System.out.println("-1"); return; } StringBuilder sb = new StringBuilder(); for (int v : a) { sb.append(v); sb.append(' '); if (sb.length() > 4000) { System.out.print(sb.toString()); sb.setLength(0); } } System.out.println(sb.toString()); } static void myAssert(boolean cond) { if (!cond) { throw new RuntimeException("Unexpected"); } } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { try { final String USERDIR = System.getProperty("user.dir"); String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", ""); cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname; final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in"); br = new BufferedReader(new InputStreamReader(fin.exists() ? new FileInputStream(fin) : System.in)); } catch (Exception e) { br = new BufferedReader(new InputStreamReader(System.in)); } } public String next() { try { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
java
1303
B
B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3 5 1 1 8 10 10 1000000 1 1000000 OutputCopy5 8 499999500000 NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good.
[ "math" ]
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; public class B_National_Project { static long mod = Long.MAX_VALUE; public static void main(String[] args) { OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); FastReader f = new FastReader(); int t = f.nextInt(); while(t-- > 0){ solve(f, out); } out.close(); } public static void solve(FastReader f, PrintWriter out) { long n = f.nextLong(); long g = f.nextLong(); long b = f.nextLong(); long total = g+b; // long goodRoad = (n/total)*g + min(g, n%total); // long badRoad = (n/total)*b + max(0, n%total - g); // if(goodRoad >= badRoad) { // out.println(n); // return; // } // long reqGoodRoad = (badRoad-goodRoad+1)/2; // long reqExtraDay = (reqGoodRoad/g)*total + reqGoodRoad%g; // if(reqGoodRoad%g == 0) { // reqExtraDay -= b; // } // out.println(n + reqExtraDay); long req = (n+1)/2; long ans = (req/g)*total + req%g; if(req%g == 0) { ans -= b; } out.println(max(n, ans)); } // Sort an array public static void sort(int arr[]) { ArrayList<Integer> al = new ArrayList<>(); for(int i: arr) { al.add(i); } Collections.sort(al); for(int i = 0; i < arr.length; i++) { arr[i] = al.get(i); } } // Find all divisors of n public static void allDivisors(int n) { for(int i = 1; i*i <= n; i++) { if(n%i == 0) { System.out.println(i + " "); if(i != n/i) { System.out.println(n/i + " "); } } } } // Check if n is prime or not public static boolean isPrime(int n) { if(n < 1) return false; if(n == 2 || n == 3) return true; if(n % 2 == 0 || n % 3 == 0) return false; for(int i = 5; i*i <= n; i += 6) { if(n % i == 0 || n % (i+2) == 0) { return false; } } return true; } // Find gcd of a and b public static long gcd(long a, long b) { long dividend = a > b ? a : b; long divisor = a < b ? a : b; while(divisor > 0) { long reminder = dividend % divisor; dividend = divisor; divisor = reminder; } return dividend; } // Find lcm of a and b public static long lcm(long a, long b) { long lcm = gcd(a, b); long hcf = (a * b) / lcm; return hcf; } // Find factorial in O(n) time public static long fact(int n) { long res = 1; for(int i = 2; i <= n; i++) { res = res * i; } return res; } // Find power in O(logb) time public static long power(long a, long b) { long res = 1; while(b > 0) { if((b&1) == 1) { res = (res * a)%mod; } a = (a * a)%mod; b >>= 1; } return res; } // Find nCr public static long nCr(int n, int r) { if(r < 0 || r > n) { return 0; } long ans = fact(n) / (fact(r) * fact(n-r)); return ans; } // Find nPr public static long nPr(int n, int r) { if(r < 0 || r > n) { return 0; } long ans = fact(n) / fact(r); return ans; } // sort all characters of a string public static String sortString(String inputString) { char tempArray[] = inputString.toCharArray(); Arrays.sort(tempArray); return new String(tempArray); } // User defined class for fast I/O 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(); } boolean hasNext() { if (st != null && st.hasMoreTokens()) { return true; } String tmp; try { br.mark(1000); tmp = br.readLine(); if (tmp == null) { return false; } br.reset(); } catch (IOException e) { return false; } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } boolean nextBoolean() { return Boolean.parseBoolean(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextArray(int n) { int[] a = new int[n]; for(int i=0; i<n; i++) { a[i] = nextInt(); } return a; } } } /** Dec Char Dec Char Dec Char Dec Char --------- --------- --------- ---------- 0 NUL (null) 32 SPACE 64 @ 96 ` 1 SOH (start of heading) 33 ! 65 A 97 a 2 STX (start of text) 34 " 66 B 98 b 3 ETX (end of text) 35 # 67 C 99 c 4 EOT (end of transmission) 36 $ 68 D 100 d 5 ENQ (enquiry) 37 % 69 E 101 e 6 ACK (acknowledge) 38 & 70 F 102 f 7 BEL (bell) 39 ' 71 G 103 g 8 BS (backspace) 40 ( 72 H 104 h 9 TAB (horizontal tab) 41 ) 73 I 105 i 10 LF (NL line feed, new line) 42 * 74 J 106 j 11 VT (vertical tab) 43 + 75 K 107 k 12 FF (NP form feed, new page) 44 , 76 L 108 l 13 CR (carriage return) 45 - 77 M 109 m 14 SO (shift out) 46 . 78 N 110 n 15 SI (shift in) 47 / 79 O 111 o 16 DLE (data link escape) 48 0 80 P 112 p 17 DC1 (device control 1) 49 1 81 Q 113 q 18 DC2 (device control 2) 50 2 82 R 114 r 19 DC3 (device control 3) 51 3 83 S 115 s 20 DC4 (device control 4) 52 4 84 T 116 t 21 NAK (negative acknowledge) 53 5 85 U 117 u 22 SYN (synchronous idle) 54 6 86 V 118 v 23 ETB (end of trans. block) 55 7 87 W 119 w 24 CAN (cancel) 56 8 88 X 120 x 25 EM (end of medium) 57 9 89 Y 121 y 26 SUB (substitute) 58 : 90 Z 122 z 27 ESC (escape) 59 ; 91 [ 123 { 28 FS (file separator) 60 < 92 \ 124 | 29 GS (group separator) 61 = 93 ] 125 } 30 RS (record separator) 62 > 94 ^ 126 ~ 31 US (unit separator) 63 ? 95 _ 127 DEL */ // (a/b)%mod == (a * moduloInverse(b)) % mod; // moduloInverse(b) = power(b, mod-2);
java
1290
B
B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions: If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss; If we write the strings t1,t2,…,tkt1,t2,…,tk in order, the resulting string will be equal to tt; For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= "gamegame". Then the string t=t= "megamage" is a reducible anagram of ss, we may choose for example s1=s1= "game", s2=s2= "gam", s3=s3= "e" and t1=t1= "mega", t2=t2= "mag", t3=t3= "e": On the other hand, we can prove that t=t= "memegaga" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105)  — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.ExamplesInputCopyaaaaa 3 1 1 2 4 5 5 OutputCopyYes No Yes InputCopyaabbbbbbc 6 1 2 2 4 2 2 1 9 5 7 3 5 OutputCopyNo Yes Yes Yes No No NoteIn the first sample; in the first and third queries; the substring is "a"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand; in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= "a", s2=s2= "aa", t1=t1= "a", t2=t2= "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram.
[ "binary search", "constructive algorithms", "data structures", "strings", "two pointers" ]
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1290b { public static void main(String[] args) throws IOException { char[] s = rcha(); int q = ri(), n = s.length, cnt[][] = new int[26][n + 1]; for(int i = 0; i < n; ++i) { for(int j = 0; j < 26; ++j) { cnt[j][i + 1] = cnt[j][i]; } ++cnt[s[i] - 'a'][i + 1]; } while(q --> 0) { int l = rni() - 1, r = ni() - 1; if(l == r || s[l] != s[r]) { pry(); } else { int diffcnt = 0, totcnt = 0; for(int i = 0; i < 26; ++i) { if(i != s[l] - 'a') { int segcnt = cnt[i][r + 1] - cnt[i][l]; if(segcnt > 0) { ++diffcnt; totcnt += segcnt; } } } pryn(diffcnt >= 2/* && totcnt >= 3*/); } } close(); } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random rand = new Random(); // references // IBIG = 1e9 + 7 // IRAND ~= 3e8 // IMAX ~= 2e10 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IRAND = 327859546; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int floori(double d) {return (int)d;} static int ceili(double d) {return (int)ceil(d);} static long floorl(double d) {return (long)d;} static long ceill(double d) {return (long)ceil(d);} static void reverse(int[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(double[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static <T> void reverse(T[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {T swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(char[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); char swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static <T> void shuffle(T[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); T swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); Arrays.sort(a);} static void rsort(long[] a) {shuffle(a); Arrays.sort(a);} static void rsort(double[] a) {shuffle(a); Arrays.sort(a);} static void rsort(char[] a) {shuffle(a); Arrays.sort(a);} static <T> void rsort(T[] a) {shuffle(a); Arrays.sort(a);} static int randInt(int min, int max) {return rand.nextInt(max - min + 1) + min;} // input static void r() throws IOException {input = new StringTokenizer(__in.readLine());} static int ri() throws IOException {return Integer.parseInt(__in.readLine());} static long rl() throws IOException {return Long.parseLong(__in.readLine());} static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;} static char[] rcha() throws IOException {return __in.readLine().toCharArray();} static String rline() throws IOException {return __in.readLine();} static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());} static int ni() {return Integer.parseInt(input.nextToken());} static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());} static long nl() {return Long.parseLong(input.nextToken());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {__out.println("yes");} static void pry() {__out.println("Yes");} static void prY() {__out.println("YES");} static void prno() {__out.println("no");} static void prn() {__out.println("No");} static void prN() {__out.println("NO");} static void pryesno(boolean b) {__out.println(b ? "yes" : "no");}; static void pryn(boolean b) {__out.println(b ? "Yes" : "No");} static void prYN(boolean b) {__out.println(b ? "YES" : "NO");} static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next());} static void h() {__out.println("hlfd");} static void flush() {__out.flush();} static void close() {__out.close();} }
java
1325
D
D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0≤u,v≤1018)(0≤u,v≤1018).OutputIf there's no array that satisfies the condition, print "-1". Otherwise:The first line should contain one integer, nn, representing the length of the desired array. The next line should contain nn positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInputCopy2 4 OutputCopy2 3 1InputCopy1 3 OutputCopy3 1 1 1InputCopy8 5 OutputCopy-1InputCopy0 0 OutputCopy0NoteIn the first sample; 3⊕1=23⊕1=2 and 3+1=43+1=4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty.
[ "bitmasks", "constructive algorithms", "greedy", "number theory" ]
import java.io.*; import java.util.*; public class Main { static long u, v; static Scanner sc = new Scanner(System.in); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { u = sc.nextLong(); v = sc.nextLong(); solve(); out.close(); } /* 1. 不可行 1.1 u > v, 相加的值必然大于等于所有数异或 1.2 u 和 v 奇偶不同, 所有数相加和所有数相异或奇偶应该相同。 2. 可行 长度为3: [u, x, x] u ^ x ^ x = u, u + x + x = v, x = (v-u)/2 长度为2: [a, b] a ^ b = u, a + b = v, 已知 a + b = a ^ b + 2(a&b),可得 a&b = (v-u)/2 = x x有一位为1,u对应二进制位为0 x有一位为0,u对应二进制位任意 那么可知道若存在这样的a,b, 那么x & u = 0,即 x ^ u = x + u 那么数组位[u + x, x] 长度为1: [u], u = v != 0 */ static void solve() { if (u > v || (u % 2 != v % 2)) { out.println("-1"); return; } long x = (v - u) / 2; // 由于u,v奇偶相同,那么必然能被2整除 if (u == v) { if (u == 0) { out.println(0); } else { out.println(1); out.println(u); } } else { if ((x & u) == 0) { out.println(2); out.println((u + x) + " " + x); } else { out.println(3); out.println(u + " " + x + " " + x); } } } }
java
1300
A
A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4 3 2 -1 -1 4 -1 0 0 1 2 -1 2 3 0 -2 1 OutputCopy1 2 0 2 NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4.
[ "implementation", "math" ]
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.math.BigInteger; import java.util.*; import java.util.stream.Collectors; public class coding { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while(st == null || !st.hasMoreElements()) { try { String str = br.readLine(); if(str == null) throw new InputMismatchException(); st = new StringTokenizer(str); } 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(); } if(str == null) throw new InputMismatchException(); return str; } public BigInteger nextBigInteger() { // TODO Auto-generated method stub return null; } } public static <K, V> K getKey(Map<K, V> map, V value) { for (Map.Entry<K, V> entry: map.entrySet()) { if (value.equals(entry.getValue())) { return entry.getKey(); } } return null; } public static void main(String args[] ) throws Exception { // FastReader sc = new FastReader(); // PrintWriter out = new PrintWriter(System.out); Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0) { Integer n=sc.nextInt(); int arr[]=new int[n]; int s=0; int c=0; int x=0; for(int i=0;i<n;i++) { arr[i]=sc.nextInt(); s=s+arr[i]; if(arr[i]==0) { c++; } } Arrays.sort(arr); if(s==0 && c==0) { x=1; } if(s==0 && c>0) { x=c; } if(s!=0 && c==0) { x=0; } if(s!=0 && c>0) { x=c; s=s+c; if(s==0) { x++; } } System.out.println(x); } } }
java
1307
D
D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n)  — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n)  — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3 1 3 5 1 2 2 3 3 4 3 5 2 4 OutputCopy3 InputCopy5 4 2 2 4 1 2 2 3 3 4 4 5 OutputCopy3 NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33. The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33.
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "shortest paths", "sortings" ]
//package round621; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Comparator; import java.util.InputMismatchException; import java.util.Queue; public class D { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(), m = ni(), K = ni(); int[] a = na(K); int[] from = new int[m]; int[] to = new int[m]; for (int i = 0; i < m; i++) { from[i] = ni() - 1; to[i] = ni() - 1; } int[][] g = packU(n, from, to); for(int i = 0;i < K;i++)a[i]--; int[] pre = bfs2(g, 0); int[] suf = bfs2(g, n-1); int[][] ds = new int[K][]; for(int i = 0;i < K;i++){ ds[i] = new int[]{pre[a[i]], suf[a[i]]}; } Arrays.sort(ds, new Comparator<int[]>() { public int compare(int[] a, int[] b) { return (a[0] - a[1]) - (b[0] - b[1]); } }); int maxpre = Integer.MIN_VALUE / 2; int ans = 0; for(int i = 0;i < K;i++){ ans = Math.max(ans, ds[i][1] + maxpre + 1); maxpre = Math.max(maxpre, ds[i][0]); } int maxsuf = Integer.MIN_VALUE / 2; for(int i = K-1;i >= 0;i--){ ans = Math.max(ans, ds[i][0] + maxsuf + 1); maxsuf = Math.max(maxsuf, ds[i][1]); } if(ans > pre[n-1]){ ans = pre[n-1]; } out.println(ans); // maximize min(pres[i]+sufs[j]+1, pres[j]+sufs[i]+1) } public static int[] bfs2(int[][] g, int s) { int n = g.length; Queue<Integer> q = new ArrayDeque<>(); int[] ds = new int[n]; Arrays.fill(ds, Integer.MAX_VALUE / 2); q.add(s); ds[s] = 0; while(!q.isEmpty()){ int cur = q.poll(); for(int e : g[cur]){ if(ds[e] > ds[cur] + 1){ ds[e] = ds[cur] + 1; q.add(e); } } } return ds; } static int[][] packU(int n, int[] from, int[] to) { int[][] g = new int[n][]; int[] p = new int[n]; for (int f : from) p[f]++; for (int t : to) p[t]++; for (int i = 0; i < n; i++) g[i] = new int[p[i]]; for (int i = 0; i < from.length; i++) { g[from[i]][--p[from[i]]] = to[i]; g[to[i]][--p[to[i]]] = from[i]; } return g; } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new D().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
java
1321
A
A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5 1 1 1 0 0 0 1 1 1 1 OutputCopy3 InputCopy3 0 0 0 0 0 0 OutputCopy-1 InputCopy4 1 1 1 1 1 1 1 1 OutputCopy-1 InputCopy9 1 0 0 0 0 0 0 0 1 0 1 1 0 1 1 1 1 0 OutputCopy4 NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal.
[ "greedy" ]
import java.util.*; import static java.lang.Math.*; import static java.lang.Character.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int i, n = in.nextInt(),arr1[]=new int[n],arr2[]=new int[n],x=0,y=0; for( i =0;i<n;i++){ arr1[i]=in.nextInt(); } for( i =0;i<n;i++){ arr2[i]=in.nextInt(); } for(i=0;i<n;i++) { if(arr1[i]==1 && arr2[i]==0) x++; else if(arr1[i]==0 && arr2[i]==1) y++; } if(x==0) System.out.println(-1); else System.out.println((int) ceil((y+1.0)/x)); } }
java
1292
A
A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1,1)(1,1) to the gate at (2,n)(2,n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only qq such moments: the ii-th moment toggles the state of cell (ri,ci)(ri,ci) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the qq moments, whether it is still possible to move from cell (1,1)(1,1) to cell (2,n)(2,n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers nn, qq (2≤n≤1052≤n≤105, 1≤q≤1051≤q≤105).The ii-th of qq following lines contains two integers riri, cici (1≤ri≤21≤ri≤2, 1≤ci≤n1≤ci≤n), denoting the coordinates of the cell to be flipped at the ii-th moment.It is guaranteed that cells (1,1)(1,1) and (2,n)(2,n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1,1)(1,1) to cell (2,n)(2,n), print "Yes", otherwise print "No". There should be exactly qq answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInputCopy5 5 2 3 1 4 2 4 2 3 1 4 OutputCopyYes No No No Yes NoteWe'll crack down the example test here: After the first query; the girl still able to reach the goal. One of the shortest path ways should be: (1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5)(1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5). After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1,3)(1,3). After the fourth query, the (2,3)(2,3) is not blocked, but now all the 44-th column is blocked, so she still can't reach the goal. After the fifth query, the column barrier has been lifted, thus she can go to the final goal again.
[ "data structures", "dsu", "implementation" ]
import java.io.*; import java.util.*; public class Solution{ public static void main(String arg[])throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n,q; String str[]=br.readLine().split(" "); n=Integer.parseInt(str[0]); q=Integer.parseInt(str[1]); int flippedCells[][] = new int[q][2]; boolean maze[][] = new boolean[2][n]; //maze - valcony ==true //maze - ground ==false for(int i=0;i<q;i++) flippedCells[i] = Arrays.stream(br.readLine(). split("\\s+")).mapToInt(Integer::valueOf).toArray(); int count=0; for(int i=0;i<q;i++) { int x=flippedCells[i][0]-1,y=flippedCells[i][1]-1; if(!maze[x][y]){ if(maze[x^1][y])count++; if(y-1>=0 && maze[x^1][y-1])count++; if(y+1<n &&maze[x^1][y+1])count++; }else{ if(maze[x^1][y])count--; if(y-1>=0 && maze[x^1][y-1])count--; if(y+1<n && maze[x^1][y+1])count--; } maze[x][y]^=true; if(count==0) System.out.println("Yes"); else System.out.println("No"); //break; } } }
java
1305
D
D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6 1 4 4 2 5 3 6 3 2 3 3 4 4 OutputCopy ? 5 6 ? 3 1 ? 1 2 ! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test:
[ "constructive algorithms", "dfs and similar", "interactive", "trees" ]
import java.io.*; import java.util.*; public class ozontechD { 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; } } // long start = System.currentTimeMillis(); // long end = System.currentTimeMillis(); // System.out.println((end - start) + "ms"); static FastReader io; public static void main(String[] args) { io = new FastReader(); int n = io.nextInt(); ArrayList<Integer>[] adjL = new ArrayList[n+1]; for(int i=0;i<=n;i++){ adjL[i] = new ArrayList<>(); } for(int i=0;i<n-1;i++){ int u = io.nextInt(); int v = io.nextInt(); adjL[u].add(v); adjL[v].add(u); } //now add all leaves TreeSet<Integer> hs = new TreeSet<>(); for(int i=1;i<=n;i++){ if(adjL[i].size()==1){ hs.add(i); } } while (hs.size()>=2){ int u =hs.pollFirst(); int v = hs.pollFirst(); int lca = query(u,v); if(lca==u||lca==v){ answer(lca); } else { for(int parent:adjL[u]){ adjL[parent].remove(Integer.valueOf(u)); if(adjL[parent].size()==1){ hs.add(parent); } } for(int parent:adjL[v]){ adjL[parent].remove(Integer.valueOf(v)); if(adjL[parent].size()==1){ hs.add(parent); } } } } answer(hs.pollFirst()); } public static int query(int u,int v){ System.out.println("? "+u+" "+v);System.out.flush(); return (io.nextInt()); } public static void answer(int u){ System.out.println("! "+u);System.out.flush(); System.exit(0); } public static void print(String str,int val){ System.out.println(str+" "+val); } public static void print(Object[] obj){ for(Object a:obj){ System.out.println(a); } } public static void print(Object[][] obj){ for(Object[] a:obj){ System.out.println(a); } } public static void debug(long[][] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.println(Arrays.toString(arr[i])); } } public static void debug(int[][] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.println(Arrays.toString(arr[i])); } } public static void debug(String[] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.println(arr[i]); } } public static void print(int[] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.print(arr[i]+" "); } System.out.print('\n'); } public static void print(String[] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.print(arr[i]+" "); } System.out.print('\n'); } public static void print(long[] arr){ int len = arr.length; for(int i=0;i<len;i++){ System.out.print(arr[i]+" "); } System.out.print('\n'); } // OutputStream out = new BufferedOutputStream( System.out ); // for(int i=1;i<n;i++){ // out.write((max_divisor[i]+" ").getBytes()); //} // out.flush(); }
java
1141
F2
F2. Same Sum Blocks (Hard)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤15001≤n≤1500) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7 4 1 2 2 1 5 3 OutputCopy3 7 7 2 3 4 5 InputCopy11 -5 -4 -3 -2 -1 0 1 2 3 4 5 OutputCopy2 3 4 1 1 InputCopy4 1 1 1 1 OutputCopy4 4 4 1 1 2 2 3 3
[ "data structures", "greedy" ]
// Problem: F2. Same Sum Blocks (Hard) // Contest: Codeforces - Codeforces Round #547 (Div. 3) // URL: https://codeforces.com/problemset/problem/1141/F2 // Memory Limit: 256 MB // Time Limit: 3000 ms // author: zdkk import java.io.*; import java.util.*; public class Main { static IntReader in; static FastWriter out; static String INPUT = ""; static final int N = 1510; static int[] a = new int[N]; static int n; static void solve() { n = ni(); for (int i = 1; i <= n; i++) a[i] = ni(); Map<Integer, List<int[]>> map = new HashMap<>(); for (int i = 1; i <= n; i++) { int s = 0; for (int j = i; j <= n; j++) { s += a[j]; map.computeIfAbsent(s, key -> new ArrayList<>()).add(new int[]{i, j}); } } List<int[]> res = new ArrayList<>(); for (int key : map.keySet()) { List<int[]> t = map.get(key); if (t.size() <= res.size()) continue; Collections.sort(t, (o1, o2) -> (o1[1] - o2[1])); int pre = Integer.MIN_VALUE; List<int[]> list = new ArrayList<>(); for (int[] p : t) { if (p[0] > pre) { list.add(p); pre = p[1]; } } if (list.size() > res.size()) { res = list; } } out.println(res.size()); for (int[] p : res) { out.println(p[0] + " " + p[1]); } } public static void main(String[] args) throws Exception { in = INPUT.isEmpty() ? new IntReader(System.in) : new IntReader(new ByteArrayInputStream(INPUT.getBytes())); out = new FastWriter(System.out); solve(); out.flush(); } public static class IntReader { private InputStream is; private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; public IntReader(InputStream is) { this.is = is; } 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 int ni() { return (int) nl(); } 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(); } } } public static class FastWriter { private static final int BUF_SIZE = 1 << 13; private final byte[] buf = new byte[BUF_SIZE]; private final OutputStream out; private int ptr = 0; private FastWriter() { out = null; } public FastWriter(OutputStream os) { this.out = os; } public FastWriter(String path) { try { this.out = new FileOutputStream(path); } catch (FileNotFoundException e) { throw new RuntimeException("FastWriter"); } } public FastWriter write(byte b) { buf[ptr++] = b; if (ptr == BUF_SIZE) innerflush(); return this; } public FastWriter write(char c) { return write((byte) c); } public FastWriter write(char[] s) { for (char c : s) { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) innerflush(); } return this; } public FastWriter write(String s) { s.chars().forEach(c -> { buf[ptr++] = (byte) c; if (ptr == BUF_SIZE) innerflush(); }); return this; } private static int countDigits(int l) { if (l >= 1000000000) return 10; if (l >= 100000000) return 9; if (l >= 10000000) return 8; if (l >= 1000000) return 7; if (l >= 100000) return 6; if (l >= 10000) return 5; if (l >= 1000) return 4; if (l >= 100) return 3; if (l >= 10) return 2; return 1; } public FastWriter write(int x) { if (x == Integer.MIN_VALUE) { return write((long) x); } if (ptr + 12 >= BUF_SIZE) innerflush(); if (x < 0) { write((byte) '-'); x = -x; } int d = countDigits(x); for (int i = ptr + d - 1; i >= ptr; i--) { buf[i] = (byte) ('0' + x % 10); x /= 10; } ptr += d; return this; } private static int countDigits(long l) { if (l >= 1000000000000000000L) return 19; if (l >= 100000000000000000L) return 18; if (l >= 10000000000000000L) return 17; if (l >= 1000000000000000L) return 16; if (l >= 100000000000000L) return 15; if (l >= 10000000000000L) return 14; if (l >= 1000000000000L) return 13; if (l >= 100000000000L) return 12; if (l >= 10000000000L) return 11; if (l >= 1000000000L) return 10; if (l >= 100000000L) return 9; if (l >= 10000000L) return 8; if (l >= 1000000L) return 7; if (l >= 100000L) return 6; if (l >= 10000L) return 5; if (l >= 1000L) return 4; if (l >= 100L) return 3; if (l >= 10L) return 2; return 1; } public FastWriter write(long x) { if (x == Long.MIN_VALUE) { return write("" + x); } if (ptr + 21 >= BUF_SIZE) innerflush(); if (x < 0) { write((byte) '-'); x = -x; } int d = countDigits(x); for (int i = ptr + d - 1; i >= ptr; i--) { buf[i] = (byte) ('0' + x % 10); x /= 10; } ptr += d; return this; } public FastWriter write(double x, int precision) { if (x < 0) { write('-'); x = -x; } x += Math.pow(10, -precision) / 2; // if(x < 0){ x = 0; } write((long) x).write("."); x -= (long) x; for (int i = 0; i < precision; i++) { x *= 10; write((char) ('0' + (int) x)); x -= (int) x; } return this; } public FastWriter writeln(char c) { return write(c).writeln(); } public FastWriter writeln(int x) { return write(x).writeln(); } public FastWriter writeln(long x) { return write(x).writeln(); } public FastWriter writeln(double x, int precision) { return write(x, precision).writeln(); } public FastWriter write(int... xs) { boolean first = true; for (int x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter write(long... xs) { boolean first = true; for (long x : xs) { if (!first) write(' '); first = false; write(x); } return this; } public FastWriter writeln() { return write((byte) '\n'); } public FastWriter writeln(int... xs) { return write(xs).writeln(); } public FastWriter writeln(long... xs) { return write(xs).writeln(); } public FastWriter writeln(char[] line) { return write(line).writeln(); } public FastWriter writeln(char[]... map) { for (char[] line : map) write(line).writeln(); return this; } public FastWriter writeln(String s) { return write(s).writeln(); } private void innerflush() { try { out.write(buf, 0, ptr); ptr = 0; } catch (IOException e) { throw new RuntimeException("innerflush"); } } public void flush() { innerflush(); try { out.flush(); } catch (IOException e) { throw new RuntimeException("flush"); } } public FastWriter print(byte b) { return write(b); } public FastWriter print(char c) { return write(c); } public FastWriter print(char[] s) { return write(s); } public FastWriter print(String s) { return write(s); } public FastWriter print(int x) { return write(x); } public FastWriter print(long x) { return write(x); } public FastWriter print(double x, int precision) { return write(x, precision); } public FastWriter println(char c) { return writeln(c); } public FastWriter println(int x) { return writeln(x); } public FastWriter println(long x) { return writeln(x); } public FastWriter println(double x, int precision) { return writeln(x, precision); } public FastWriter print(int... xs) { return write(xs); } public FastWriter print(long... xs) { return write(xs); } public FastWriter println(int... xs) { return writeln(xs); } public FastWriter println(long... xs) { return writeln(xs); } public FastWriter println(char[] line) { return writeln(line); } public FastWriter println(char[]... map) { return writeln(map); } public FastWriter println(String s) { return writeln(s); } public FastWriter println() { return writeln(); } } static int ni() { return in.ni(); } static long nl() { return in.nl(); } static String ns() { return in.ns(); } static double nd() { return Double.parseDouble(in.ns()); } }
java
1291
B
B. Array Sharpeningtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou're given an array a1,…,ana1,…,an of nn non-negative integers.Let's call it sharpened if and only if there exists an integer 1≤k≤n1≤k≤n such that a1<a2<…<aka1<a2<…<ak and ak>ak+1>…>anak>ak+1>…>an. In particular, any strictly increasing or strictly decreasing array is sharpened. For example: The arrays [4][4], [0,1][0,1], [12,10,8][12,10,8] and [3,11,15,9,7,4][3,11,15,9,7,4] are sharpened; The arrays [2,8,2,8,6,5][2,8,2,8,6,5], [0,1,1,0][0,1,1,0] and [2,5,6,9,8,8][2,5,6,9,8,8] are not sharpened. You can do the following operation as many times as you want: choose any strictly positive element of the array, and decrease it by one. Formally, you can choose any ii (1≤i≤n1≤i≤n) such that ai>0ai>0 and assign ai:=ai−1ai:=ai−1.Tell if it's possible to make the given array sharpened using some number (possibly zero) of these operations.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤15 0001≤t≤15 000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤3⋅1051≤n≤3⋅105).The second line of each test case contains a sequence of nn non-negative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.OutputFor each test case, output a single line containing "Yes" (without quotes) if it's possible to make the given array sharpened using the described operations, or "No" (without quotes) otherwise.ExampleInputCopy10 1 248618 3 12 10 8 6 100 11 15 9 7 8 4 0 1 1 0 2 0 0 2 0 1 2 1 0 2 1 1 3 0 1 0 3 1 0 1 OutputCopyYes Yes Yes No No Yes Yes Yes Yes No NoteIn the first and the second test case of the first test; the given array is already sharpened.In the third test case of the first test; we can transform the array into [3,11,15,9,7,4][3,11,15,9,7,4] (decrease the first element 9797 times and decrease the last element 44 times). It is sharpened because 3<11<153<11<15 and 15>9>7>415>9>7>4.In the fourth test case of the first test, it's impossible to make the given array sharpened.
[ "greedy", "implementation" ]
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Problem1676H1 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); long t = scanner.nextInt(); while(t-- > 0){ long n = scanner.nextLong(); List<Long> list = new ArrayList<>(); for (int i = 0; i < n; i++) { list.add(scanner.nextLong()); } int preff = -1; int suff = list.size(); for (int i = 0; i < list.size(); i++) { if (list.get(i) < i) break; preff = i; } for (int i = list.size() - 1; i >= 0; i--) { if (list.get(i) < list.size() - 1 - i) break; suff = i; } if (preff >= suff) System.out.println("Yes"); else System.out.println("No"); } } }
java
1284
C
C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853 OutputCopy1 InputCopy2 993244853 OutputCopy6 InputCopy3 993244853 OutputCopy32 InputCopy2019 993244853 OutputCopy923958830 InputCopy2020 437122297 OutputCopy265955509 NoteFor sample input n=3n=3; let's consider all permutations of length 33: [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66. [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32.
[ "combinatorics", "math" ]
import java.util.*; import java.lang.*; import java.io.*; public class feb20 { public static void main(String[] srgs) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] scn = (br.readLine()).trim().split(" "); int n = Integer.parseInt(scn[0]); long mod = Integer.parseInt(scn[1]); long[] fact = new long[n + 1]; fact[1] = 1; for (int i = 2; i <= n; i++) { fact[i] = fact[i - 1] * i; fact[i] %= mod; } long ans = 0; for (int len = 1; len <= n; len++) { long curr = (((fact[len] * fact[n - len + 1]) % mod) * (n - len + 1)) % mod; ans = (ans + curr) % mod; } System.out.println(ans); return; } public static void sec() throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); while (t-- > 0) { String[] scn = (br.readLine()).trim().split(" "); int n = Integer.parseInt(scn[0]); long[] arr = new long[n]; scn = (br.readLine()).trim().split(" "); for (int i = 0; i < n; i++) { arr[i] = Long.parseLong(scn[i]); } sb.append("\n"); } System.out.println(sb); return; } public static void third() throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); String[] scn = (br.readLine()).trim().split(" "); int n = Integer.parseInt(scn[0]); long[] arr = new long[n]; scn = (br.readLine()).trim().split(" "); for (int i = 0; i < n; i++) { arr[i] = Long.parseLong(scn[i]); } System.out.println(sb); return; } public static void debug() { System.out.println("working.."); } public static void debug(int i) { System.out.println("working on " + i); } public static void sort(long[] arr) { int n = arr.length; for (int i = 0; i < n; i++) { int idx = (int) Math.random() * n; long temp = arr[i]; arr[i] = arr[idx]; arr[idx] = temp; } Arrays.sort(arr); } public static void sort(int[] arr) { int n = arr.length; for (int i = 0; i < n; i++) { int idx = (int) Math.random() * n; int temp = arr[i]; arr[i] = arr[idx]; arr[idx] = temp; } Arrays.sort(arr); } public static void print(long[][] dp) { for (long[] a : dp) { for (long ele : a) { System.out.print(ele + " "); } System.out.println(); } } public static void print(int[][] dp) { for (int[] a : dp) { for (int ele : a) { System.out.print(ele + " "); } System.out.println(); } } public static void print(boolean[] dp) { for (boolean ele : dp) { System.out.print(ele + " "); } System.out.println(); } public static void print(long[] dp) { for (long ele : dp) { System.out.print(ele + " "); } System.out.println(); } }
java
1322
A
A. Unusual Competitionstime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputA bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example; sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.The teacher gave Dmitry's class a very strange task — she asked every student to come up with a sequence of arbitrary length, consisting only of opening and closing brackets. After that all the students took turns naming the sequences they had invented. When Dima's turn came, he suddenly realized that all his classmates got the correct bracketed sequence, and whether he got the correct bracketed sequence, he did not know.Dima suspects now that he simply missed the word "correct" in the task statement, so now he wants to save the situation by modifying his sequence slightly. More precisely, he can the arbitrary number of times (possibly zero) perform the reorder operation.The reorder operation consists of choosing an arbitrary consecutive subsegment (substring) of the sequence and then reordering all the characters in it in an arbitrary way. Such operation takes ll nanoseconds, where ll is the length of the subsegment being reordered. It's easy to see that reorder operation doesn't change the number of opening and closing brackets. For example for "))((" he can choose the substring ")(" and do reorder ")()(" (this operation will take 22 nanoseconds).Since Dima will soon have to answer, he wants to make his sequence correct as fast as possible. Help him to do this, or determine that it's impossible.InputThe first line contains a single integer nn (1≤n≤1061≤n≤106) — the length of Dima's sequence.The second line contains string of length nn, consisting of characters "(" and ")" only.OutputPrint a single integer — the minimum number of nanoseconds to make the sequence correct or "-1" if it is impossible to do so.ExamplesInputCopy8 ))((())( OutputCopy6 InputCopy3 (() OutputCopy-1 NoteIn the first example we can firstly reorder the segment from first to the fourth character; replacing it with "()()"; the whole sequence will be "()()())(". And then reorder the segment from the seventh to eighth character; replacing it with "()". In the end the sequence will be "()()()()"; while the total time spent is 4+2=64+2=6 nanoseconds.
[ "greedy" ]
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; public class A_Unusual_Competitions { public static void main(String[] args) { OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); FastReader f = new FastReader(); int t = 1; while(t-- > 0){ solve(f, out); } out.close(); } public static void solve(FastReader f, PrintWriter out) { int n = f.nextInt(); String s = f.nextLine(); int count = 0; for(int i = 0; i < n; i++) { if(s.charAt(i) == '(') { count++; } else { count--; } } if(count != 0) { out.println(-1); return; } boolean flag = true; int i = 0; int ans = 0; while(i < n) { int j = i+1; int check = (s.charAt(i) == '(') ? 1 : -1; if(check < 0) { flag = false; } while(check != 0) { if(s.charAt(j) == '(') { check++; } else { check--; } if(check < 0) { flag = false; } j++; } if(!flag) { ans += j - i; } flag = true; i = j; } out.println(ans); } public static void sort(int arr[]) { ArrayList<Integer> al = new ArrayList<>(); for(int i: arr) { al.add(i); } Collections.sort(al); for(int i = 0; i < arr.length; i++) { arr[i] = al.get(i); } } public static void allDivisors(int n) { for(int i = 1; i*i <= n; i++) { if(n%i == 0) { System.out.println(i + " "); if(i != n/i) { System.out.println(n/i + " "); } } } } public static boolean isPrime(int n) { if(n < 1) return false; if(n == 2 || n == 3) return true; if(n % 2 == 0 || n % 3 == 0) return false; for(int i = 5; i*i <= n; i += 6) { if(n % i == 0 || n % (i+2) == 0) { return false; } } return true; } public static int gcd(int a, int b) { int dividend = a > b ? a : b; int divisor = a < b ? a : b; while(divisor > 0) { int reminder = dividend % divisor; dividend = divisor; divisor = reminder; } return dividend; } public static int lcm(int a, int b) { int lcm = gcd(a, b); int hcf = (a * b) / lcm; return hcf; } public static String sortString(String inputString) { char tempArray[] = inputString.toCharArray(); Arrays.sort(tempArray); return new String(tempArray); } 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()); } float nextFloat() { return Float.parseFloat(next()); } boolean nextBoolean() { return Boolean.parseBoolean(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextArray(int n) { int[] a = new int[n]; for(int i=0; i<n; i++) { a[i] = nextInt(); } return a; } } } /** Dec Char Dec Char Dec Char Dec Char --------- --------- --------- ---------- 0 NUL (null) 32 SPACE 64 @ 96 ` 1 SOH (start of heading) 33 ! 65 A 97 a 2 STX (start of text) 34 " 66 B 98 b 3 ETX (end of text) 35 # 67 C 99 c 4 EOT (end of transmission) 36 $ 68 D 100 d 5 ENQ (enquiry) 37 % 69 E 101 e 6 ACK (acknowledge) 38 & 70 F 102 f 7 BEL (bell) 39 ' 71 G 103 g 8 BS (backspace) 40 ( 72 H 104 h 9 TAB (horizontal tab) 41 ) 73 I 105 i 10 LF (NL line feed, new line) 42 * 74 J 106 j 11 VT (vertical tab) 43 + 75 K 107 k 12 FF (NP form feed, new page) 44 , 76 L 108 l 13 CR (carriage return) 45 - 77 M 109 m 14 SO (shift out) 46 . 78 N 110 n 15 SI (shift in) 47 / 79 O 111 o 16 DLE (data link escape) 48 0 80 P 112 p 17 DC1 (device control 1) 49 1 81 Q 113 q 18 DC2 (device control 2) 50 2 82 R 114 r 19 DC3 (device control 3) 51 3 83 S 115 s 20 DC4 (device control 4) 52 4 84 T 116 t 21 NAK (negative acknowledge) 53 5 85 U 117 u 22 SYN (synchronous idle) 54 6 86 V 118 v 23 ETB (end of trans. block) 55 7 87 W 119 w 24 CAN (cancel) 56 8 88 X 120 x 25 EM (end of medium) 57 9 89 Y 121 y 26 SUB (substitute) 58 : 90 Z 122 z 27 ESC (escape) 59 ; 91 [ 123 { 28 FS (file separator) 60 < 92 \ 124 | 29 GS (group separator) 61 = 93 ] 125 } 30 RS (record separator) 62 > 94 ^ 126 ~ 31 US (unit separator) 63 ? 95 _ 127 DEL */
java
1320
B
B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection vv to another intersection uu is the path that starts in vv, ends in uu and has the minimum length among all such paths.Polycarp lives near the intersection ss and works in a building near the intersection tt. Every day he gets from ss to tt by car. Today he has chosen the following path to his workplace: p1p1, p2p2, ..., pkpk, where p1=sp1=s, pk=tpk=t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from ss to tt.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection ss, the system chooses some shortest path from ss to tt and shows it to Polycarp. Let's denote the next intersection in the chosen path as vv. If Polycarp chooses to drive along the road from ss to vv, then the navigator shows him the same shortest path (obviously, starting from vv as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection ww instead, the navigator rebuilds the path: as soon as Polycarp arrives at ww, the navigation system chooses some shortest path from ww to tt and shows it to Polycarp. The same process continues until Polycarp arrives at tt: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1,2,3,4][1,2,3,4] (s=1s=1, t=4t=4): Check the picture by the link http://tk.codeforces.com/a.png When Polycarp starts at 11, the system chooses some shortest path from 11 to 44. There is only one such path, it is [1,5,4][1,5,4]; Polycarp chooses to drive to 22, which is not along the path chosen by the system. When Polycarp arrives at 22, the navigator rebuilds the path by choosing some shortest path from 22 to 44, for example, [2,6,4][2,6,4] (note that it could choose [2,3,4][2,3,4]); Polycarp chooses to drive to 33, which is not along the path chosen by the system. When Polycarp arrives at 33, the navigator rebuilds the path by choosing the only shortest path from 33 to 44, which is [3,4][3,4]; Polycarp arrives at 44 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 22 rebuilds in this scenario. Note that if the system chose [2,3,4][2,3,4] instead of [2,6,4][2,6,4] during the second step, there would be only 11 rebuild (since Polycarp goes along the path, so the system maintains the path [3,4][3,4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105) — the number of intersections and one-way roads in Bertown, respectively.Then mm lines follow, each describing a road. Each line contains two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) denoting a road from intersection uu to intersection vv. All roads in Bertown are pairwise distinct, which means that each ordered pair (u,v)(u,v) appears at most once in these mm lines (but if there is a road (u,v)(u,v), the road (v,u)(v,u) can also appear).The following line contains one integer kk (2≤k≤n2≤k≤n) — the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1≤pi≤n1≤pi≤n, all these integers are pairwise distinct) — the intersections along Polycarp's path in the order he arrived at them. p1p1 is the intersection where Polycarp lives (s=p1s=p1), and pkpk is the intersection where Polycarp's workplace is situated (t=pkt=pk). It is guaranteed that for every i∈[1,k−1]i∈[1,k−1] the road from pipi to pi+1pi+1 exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInputCopy6 9 1 5 5 4 1 2 2 3 3 4 4 1 2 6 6 4 4 2 4 1 2 3 4 OutputCopy1 2 InputCopy7 7 1 2 2 3 3 4 4 5 5 6 6 7 7 1 7 1 2 3 4 5 6 7 OutputCopy0 0 InputCopy8 13 8 7 8 6 7 5 7 4 6 5 6 4 5 3 5 2 4 3 4 2 3 1 2 1 1 8 5 8 7 5 2 1 OutputCopy0 3
[ "dfs and similar", "graphs", "shortest paths" ]
//package navigationsystem; import java.util.*; import java.io.*; public class navigationsystem { public static void main(String[] args) throws IOException { BufferedReader fin = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(fin.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); ArrayList<ArrayList<Integer>> c = new ArrayList<ArrayList<Integer>>(); ArrayList<ArrayList<Integer>> cReverse = new ArrayList<ArrayList<Integer>>(); //use this one for dijkstra for(int i = 0; i < n; i++) { c.add(new ArrayList<Integer>()); cReverse.add(new ArrayList<Integer>()); } for(int i = 0; i < m; i++) { st = new StringTokenizer(fin.readLine()); int a = Integer.parseInt(st.nextToken()) - 1; int b = Integer.parseInt(st.nextToken()) - 1; c.get(a).add(b); cReverse.get(b).add(a); } PriorityQueue<int[]> q = new PriorityQueue<int[]>((a, b) -> a[1] - b[1]); int k = Integer.parseInt(fin.readLine()); int[] path = new int[k]; st = new StringTokenizer(fin.readLine()); for(int i = 0; i < k; i++) { path[i] = Integer.parseInt(st.nextToken()) - 1; } int[] minCost = new int[n]; Arrays.fill(minCost, Integer.MAX_VALUE); minCost[path[k - 1]] = 0; q.add(new int[] {path[k - 1], 0}); while(q.size() != 0) { int[] cur = q.poll(); if(cur[1] > minCost[cur[0]]) { continue; } int nextCost = cur[1] + 1; int id = cur[0]; for(int i = 0; i < cReverse.get(id).size(); i++) { int nextId = cReverse.get(id).get(i); if(minCost[nextId] > nextCost) { minCost[nextId] = nextCost; q.add(new int[] {nextId, nextCost}); } } } int ansMin = 0; int ansMax = 0; for(int i = 0; i < k - 1; i++) { int cur = path[i]; int min = Integer.MAX_VALUE; for(int j = 0; j < c.get(cur).size(); j++) { int next = c.get(cur).get(j); min = Math.min(min, minCost[next]); } for(int j = 0; j < c.get(cur).size(); j++) { int next = c.get(cur).get(j); if(next != path[i + 1] && minCost[next] == min) { ansMax ++; break; } } if(min != minCost[path[i + 1]]) { ansMin ++; } } System.out.println(ansMin + " " + ansMax); } }
java
1293
B
B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1 OutputCopy1.000000000000 InputCopy2 OutputCopy1.500000000000 NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars.
[ "combinatorics", "greedy", "math" ]
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); // int t=sc.nextInt(); // while(t>0){ // t--; int n=sc.nextInt(); double sum=0; while(n>0){ sum+=(double)(1/(double)n); n--; } System.out.println(sum); // } } }
java
1296
B
B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6 1 10 19 9876 12345 1000000000 OutputCopy1 11 21 10973 13716 1111111111
[ "math" ]
import java.util.Scanner; public class food_buying { public static void main(String[] args) { Scanner s = new Scanner(System.in); int t = s.nextInt(); for(int i = 0 ; i < t ; i ++){ int n = s.nextInt(); int max = 0 ; int e = 0; while(true){ while(n!=0) { e += n % 10; max += (n - n % 10); n = (n - n % 10) / 10; } if(e<10){ System.out.println(max + e); break; } n = e; e = 0 ; } } } }
java
1305
C
C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10 8 5 OutputCopy3InputCopy3 12 1 4 5 OutputCopy0InputCopy3 7 1 4 9 OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7.
[ "brute force", "combinatorics", "math", "number theory" ]
import java.io.*; import java.util.*; public class Kuroni_and_Impossible_Calculation { static FastScanner fs; static FastWriter fw; static boolean checkOnlineJudge = System.getProperty("ONLINE_JUDGE") == null; private static final int[][] kdir = new int[][]{{-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}, {1, -2}, {2, -1}, {2, 1}, {1, 2}}; private static final int[][] dir = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}}; private static final int iMax = (int) (1e9 + 100), iMin = (int) (-1e9 - 100); private static final long lMax = (long) (1e18 + 100), lMin = (long) (-1e18 - 100); private static final int mod1 = (int) (1e9 + 7); private static final int mod2 = 998244353; public static void main(String[] args) throws IOException { fs = new FastScanner(); fw = new FastWriter(); int t = 1; //t = fs.nextInt(); while (t-- > 0) { solve(); } fw.out.close(); } private static void solve() { int n = fs.nextInt(), m = fs.nextInt(); int[] arr = readIntArray(n); if (n > m) { fw.out.println(0); return; } long ans = 1; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { ans = ans * ((long) Math.abs(arr[i] - arr[j])) % m; } } fw.out.println(ans); } private static class UnionFind { private final int[] parent; private final int[] rank; UnionFind(int n) { parent = new int[n + 5]; rank = new int[n + 5]; for (int i = 0; i <= n; i++) { parent[i] = i; rank[i] = 0; } } private int find(int i) { if (parent[i] == i) return i; return parent[i] = find(parent[i]); } private void union(int a, int b) { a = find(a); b = find(b); if (a != b) { if (rank[a] < rank[b]) { int temp = a; a = b; b = temp; } parent[b] = a; if (rank[a] == rank[b]) rank[a]++; } } } private static class Calc_nCr { private final long[] fact; private final long[] invfact; private final int p; Calc_nCr(int n, int prime) { fact = new long[n + 5]; invfact = new long[n + 5]; p = prime; fact[0] = 1; for (int i = 1; i <= n; i++) { fact[i] = (i * fact[i - 1]) % p; } invfact[n] = pow(fact[n], p - 2, p); for (int i = n - 1; i >= 0; i--) { invfact[i] = (invfact[i + 1] * (i + 1)) % p; } } private long nCr(int n, int r) { if (r > n || n < 0 || r < 0) return 0; return (((fact[n] * invfact[r]) % p) * invfact[n - r]) % p; } } private static long gcd(long a, long b) { return (b == 0 ? a : gcd(b, a % b)); } private static long lcm(long a, long b) { return ((a * b) / gcd(a, b)); } private static long pow(long a, long b, int mod) { long result = 1; while (b > 0) { if ((b & 1L) == 1) { result = (result * a) % mod; } a = (a * a) % mod; b >>= 1; } return result; } private static long ceilDiv(long a, long b) { return ((a + b - 1) / b); } private static long getMin(long... args) { long min = lMax; for (long arg : args) min = Math.min(min, arg); return min; } private static long getMax(long... args) { long max = lMin; for (long arg : args) max = Math.max(max, arg); return max; } private static boolean isPalindrome(String s, int l, int r) { int i = l, j = r; while (j - i >= 1) { if (s.charAt(i) != s.charAt(j)) return false; i++; j--; } return true; } private static List<Integer> primes(int n) { boolean[] primeArr = new boolean[n + 5]; Arrays.fill(primeArr, true); for (int i = 2; (i * i) <= n; i++) { if (primeArr[i]) { for (int j = i * i; j <= n; j += i) { primeArr[j] = false; } } } List<Integer> primeList = new ArrayList<>(); for (int i = 2; i <= n; i++) { if (primeArr[i]) primeList.add(i); } return primeList; } private static int noOfSetBits(long x) { int cnt = 0; while (x != 0) { x = x & (x - 1); cnt++; } return cnt; } private static boolean isPerfectSquare(long num) { long sqrt = (long) Math.sqrt(num); return ((sqrt * sqrt) == num); } private static class Pair<U, V> { private final U first; private final V second; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; return first.equals(pair.first) && second.equals(pair.second); } @Override public int hashCode() { return Objects.hash(first, second); } @Override public String toString() { return "(" + first + ", " + second + ")"; } private Pair(U ff, V ss) { this.first = ff; this.second = ss; } } private static void randomizeIntArr(int[] arr, int n) { Random r = new Random(); for (int i = (n - 1); i > 0; i--) { int j = r.nextInt(i + 1); swapInIntArr(arr, i, j); } } private static void randomizeLongArr(long[] arr, int n) { Random r = new Random(); for (int i = (n - 1); i > 0; i--) { int j = r.nextInt(i + 1); swapInLongArr(arr, i, j); } } private static void swapInIntArr(int[] arr, int a, int b) { int temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } private static void swapInLongArr(long[] arr, int a, int b) { long temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } private static int[] readIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = fs.nextInt(); return arr; } private static long[] readLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = fs.nextLong(); return arr; } private static List<Integer> readIntList(int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(fs.nextInt()); return list; } private static List<Long> readLongList(int n) { List<Long> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(fs.nextLong()); return list; } private static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() throws IOException { if (checkOnlineJudge) this.br = new BufferedReader(new FileReader("src/input.txt")); else this.br = new BufferedReader(new InputStreamReader(System.in)); this.st = new StringTokenizer(""); } public String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException err) { err.printStackTrace(); } } return st.nextToken(); } public String nextLine() { if (st.hasMoreTokens()) { return st.nextToken("").trim(); } try { return br.readLine().trim(); } catch (IOException err) { err.printStackTrace(); } return ""; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } private static class FastWriter { PrintWriter out; FastWriter() throws IOException { if (checkOnlineJudge) out = new PrintWriter(new FileWriter("src/output.txt")); else out = new PrintWriter(System.out); } } }
java
1286
C2
C2. Madhouse (Hard version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with easy version only by constraints on total answers lengthIt is an interactive problemVenya joined a tour to the madhouse; in which orderlies play with patients the following game. Orderlies pick a string ss of length nn, consisting only of lowercase English letters. The player can ask two types of queries: ? l r – ask to list all substrings of s[l..r]s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 33 queries of the first type.To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ (⌈x⌉⌈x⌉ is xx rounded up).Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules.Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer.Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive.InputFirst line contains number nn (1≤n≤1001≤n≤100) — the length of the picked string.InteractionYou start the interaction by reading the number nn.To ask a query about a substring from ll to rr inclusively (1≤l≤r≤n1≤l≤r≤n), you should output? l ron a separate line. After this, all substrings of s[l..r]s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled.In the case, if you ask an incorrect query, ask more than 33 queries of the first type or there will be more than ⌈0.777(n+1)2⌉⌈0.777(n+1)2⌉ substrings returned in total, you will receive verdict Wrong answer.To guess the string ss, you should output! son a separate line.After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict. Hack formatTo hack a solution, use the following format:The first line should contain one integer nn (1≤n≤1001≤n≤100) — the length of the string, and the following line should contain the string ss.ExampleInputCopy4 a aa a cb b c cOutputCopy? 1 2 ? 3 4 ? 4 4 ! aabc
[ "brute force", "constructive algorithms", "hashing", "interactive", "math" ]
//package com.company; import java.io.*; import java.math.*; import java.util.*; public class Main { public static class Task { Scanner sc; String sor(String s) { char[] cc = new char[s.length()]; for (int i = 0; i < s.length(); i++) { cc[i] = s.charAt(i); } Arrays.sort(cc); StringBuilder sb = new StringBuilder(); for (int i = 0; i < cc.length; i++) { sb.append(cc[i]); } return sb.toString(); } Map<String, Integer> get(int l, int r) throws IOException { System.out.println("? " + l + " " + r); System.out.flush(); Map<String, Integer> mp = new HashMap<>(); int n = (r - l) + 1; for (int i = 0; i < n * (n + 1) / 2; i++) { String s = sc.next(); s = sor(s); mp.put(s, mp.getOrDefault(s, 0) + 1); } return mp; } String solveLen(int n) throws IOException { Map<String, Integer> mp = get(1, n); if (n == 1) { for (String s: mp.keySet()) { System.out.println("! " + s); System.exit(0); } } Map<String, Integer> mp2 = get(2, n); for (Map.Entry<String, Integer> en: mp2.entrySet()) { mp.put(en.getKey(), mp.get(en.getKey())-en.getValue()); } List<String> ss = new ArrayList<>(); for (Map.Entry<String, Integer> en: mp.entrySet()) { if (en.getValue() == 1) { ss.add(en.getKey()); } } StringBuilder sol = new StringBuilder(); int[] con = new int[255]; Collections.sort(ss, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.length() - o2.length(); } }); for (int i = 0; i < ss.size(); i++) { for (int j = 0; j < ss.get(i).length(); j++) { con[ss.get(i).charAt(j)]--; } for (int j = 0; j < 255; j++) { if (con[j] < 0) sol.append((char) j); } Arrays.fill(con, 0); for (int j = 0; j < ss.get(i).length(); j++) { con[ss.get(i).charAt(j)]++; } } return sol.toString(); } void update(int[] cnt, String s, int p) { for (char c: s.toCharArray())cnt[c]+=p; } public void solve(Scanner sc) throws IOException { this.sc = sc; int n = sc.nextInt(); if (n <= 2) { String s = solveLen(n); System.out.println("! " + s);return; } String s = solveLen(n / 2 + 1); Map<String, Integer> countMap = get(1, n); StringBuilder inv = new StringBuilder(); for (int i = n - 1; i > n / 2; i--) { int[] cnt = new int[255]; int searchLen = i; int maxRep = Math.min(searchLen, n - searchLen + 1); for (int j = n - 1; j >= i; j--) { char c = s.charAt(n - 1 - j); int kt = Math.min(maxRep, n - j); cnt[c] += (maxRep - kt); if (j > i) { c = inv.charAt(n - 1 - j); cnt[c] += (maxRep - kt); } } for (Map.Entry<String, Integer> en: countMap.entrySet()) { if (en.getKey().length() == n) update(cnt, en.getKey(), -en.getValue() * maxRep); if (en.getKey().length() == searchLen) update(cnt, en.getKey(), en.getValue()); } int on = -1; for (int j = 0; j < 255; j++) { if (cnt[j] > 0) throw new RuntimeException(); if (cnt[j] == -1 && on != -1) throw new RuntimeException(); if (cnt[j] == -1) on = j; } if (on == -1) throw new RuntimeException(); inv.append((char) on); } System.out.println("! " + s + inv.reverse().toString()); } } static long TIME_START, TIME_END; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); // Scanner sc = new Scanner(new FileInputStream("nondec.in")); // PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out)); // PrintWriter pw = new PrintWriter(new FileOutputStream("nondec.out")); Runtime runtime = Runtime.getRuntime(); long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory(); TIME_START = System.currentTimeMillis(); Task t = new Task(); t.solve(sc); TIME_END = System.currentTimeMillis(); long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory(); // pw.close(); System.err.println("Memory increased: " + (usedMemoryAfter - usedMemoryBefore) / 1000000); System.err.println("Time used: " + (TIME_END - TIME_START) + "."); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader s) throws FileNotFoundException { br = new BufferedReader(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
1296
D
D. Fight with Monsterstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn monsters standing in a row numbered from 11 to nn. The ii-th monster has hihi health points (hp). You have your attack power equal to aa hp and your opponent has his attack power equal to bb hp.You and your opponent are fighting these monsters. Firstly, you and your opponent go to the first monster and fight it till his death, then you and your opponent go the second monster and fight it till his death, and so on. A monster is considered dead if its hp is less than or equal to 00.The fight with a monster happens in turns. You hit the monster by aa hp. If it is dead after your hit, you gain one point and you both proceed to the next monster. Your opponent hits the monster by bb hp. If it is dead after his hit, nobody gains a point and you both proceed to the next monster. You have some secret technique to force your opponent to skip his turn. You can use this technique at most kk times in total (for example, if there are two monsters and k=4k=4, then you can use the technique 22 times on the first monster and 11 time on the second monster, but not 22 times on the first monster and 33 times on the second monster).Your task is to determine the maximum number of points you can gain if you use the secret technique optimally.InputThe first line of the input contains four integers n,a,bn,a,b and kk (1≤n≤2⋅105,1≤a,b,k≤1091≤n≤2⋅105,1≤a,b,k≤109) — the number of monsters, your attack power, the opponent's attack power and the number of times you can use the secret technique.The second line of the input contains nn integers h1,h2,…,hnh1,h2,…,hn (1≤hi≤1091≤hi≤109), where hihi is the health points of the ii-th monster.OutputPrint one integer — the maximum number of points you can gain if you use the secret technique optimally.ExamplesInputCopy6 2 3 3 7 10 50 12 1 8 OutputCopy5 InputCopy1 1 100 99 100 OutputCopy1 InputCopy7 4 2 1 1 3 5 4 2 7 6 OutputCopy6
[ "greedy", "sortings" ]
//package com.company;//Read minute details if coming wrong for no idea questions import java.math.BigInteger; import java.util.*; import java.io.*; public class Main { public static class Suffix implements Comparable<Suffix> { int index; int rank; int next; public Suffix(int ind, int r, int nr) { index = ind; rank = r; next = nr; } public int compareTo(Suffix s) { if (rank != s.rank) return Integer.compare(rank, s.rank); return Integer.compare(next, s.next); } } public static int[] suffixArray(String s) { int n = s.length(); Suffix[] su = new Suffix[n]; for (int i = 0; i < n; i++) { su[i] = new Suffix(i, s.charAt(i) - '$', 0); } for (int i = 0; i < n; i++) su[i].next = (i + 1 < n ? su[i + 1].rank : -1); Arrays.sort(su); int[] ind = new int[n]; for (int length = 4; length < 2 * n; length <<= 1) { int rank = 0, prev = su[0].rank; su[0].rank = rank; ind[su[0].index] = 0; for (int i = 1; i < n; i++) { if (su[i].rank == prev && su[i].next == su[i - 1].next) { prev = su[i].rank; su[i].rank = rank; } else { prev = su[i].rank; su[i].rank = ++rank; } ind[su[i].index] = i; } for (int i = 0; i < n; i++) { int nextP = su[i].index + length / 2; su[i].next = nextP < n ? su[ind[nextP]].rank : -1; } Arrays.sort(su); } int[] suf = new int[n]; for (int i = 0; i < n; i++) suf[i] = su[i].index; return suf; } static class pair implements Comparable<pair> { long a = 0; long b = 0; // int cnt; pair(long b, long a) { this.a = b; this.b = a; // cnt = x; } @Override public int compareTo(pair o) { if(this.a != o.a) return (int) (this.a - o.a); else return (int) (this.b - o.b); } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair) o; return p.a == a && p.b == b; } return false; } public int hashCode() { return (Long.valueOf(a).hashCode()) * 31 + (Long.valueOf(b).hashCode()); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } 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()); } String nextLine() { String str = ""; try { str = br.readLine().trim(); } catch (Exception e) { e.printStackTrace(); } return str; } } static class FastWriter { private final BufferedWriter bw; public FastWriter() { this.bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void prlong(Object object) throws IOException { bw.append("" + object); } public void prlongln(Object object) throws IOException { prlong(object); bw.append("\n"); } public void close() throws IOException { bw.close(); } } public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } //HASHsET COLLISION AVOIDING CODE FOR STORING STRINGS // HashSet<Long> set = new HashSet<>(); // for(int i = 0; i < s.length(); i++){ // int b = 0; // long h = 1; // for(int j=i; j<s.length(); j++){ // h = 131*h + (int)s.charAt(j); // b += bad[(int)(s.charAt(j)-'a')]; // if(b<=k){ // set.add(h); // } // } // } // System.out.println(set.size()); //dsu static int[] par, rank; public static void dsu(int n) { par = new int[n]; rank = new int[n]; for (int i = 0; i < n; i++) { par[i] = i; rank[i] = 1; } } static int find(int u) { return par[u] == -1 ? -1 : par[u] == u ? u : (par[u] = find(par[u])); } static void union(int u, int v) { int a = find(u), b = find(v); if (a != b && a != -1 && b != -1) { par[b] = a; rank[a] += rank[b]; } } static void disunion(int u, int v) { int a = find(u), b = find(v); if (a != -1 && a == b) { par[a] = -1; } } static class Calc_nCr { private final long[] fact; private final long[] invfact; private final int p; Calc_nCr(int n, int prime) { fact = new long[n + 5]; invfact = new long[n + 5]; p = prime; fact[0] = 1; for (int i = 1; i <= n; i++) { fact[i] = (i * fact[i - 1]) % p; } invfact[n] = pow(fact[n], p - 2, p); for (int i = n - 1; i >= 0; i--) { invfact[i] = (invfact[i + 1] * (i + 1)) % p; } } private long nCr(int n, int r) { if (r > n || n < 0 || r < 0) return 0; return (((fact[n] * invfact[r]) % p) * invfact[n - r]) % p; } private static long pow(long a, long b, int mod) { long result = 1; while (b > 0) { if ((b & 1L) == 1) { result = (result * a) % mod; } a = (a * a) % mod; b >>= 1; } return result; } } static void sort(long[] a ) { ArrayList<Long> l = new ArrayList<>(); for(long i: a) { l.add(i); } Collections.sort(l); for(int i =0;i<a.length;++i) { a[i] = l.get(i); } } public static void buildtreemin( long a[], long tr[],int st , int end , int node,int yo,int x ) { if(st==end) { tr[node]=a[st]; return ;} int mid =(st+end)/2; buildtreemin(a,tr,st,mid,2*node,1+yo,x); buildtreemin(a,tr,mid+1,end,2*node+1,1+yo,x); tr[node] = Math.min(tr[2 * node] ,tr[2 * node + 1]); } public static void buildtreemax( long a[], long tr[],int st , int end , int node,int yo,int x ) { if(st==end) { tr[node]=a[st]; return ;} int mid =(st+end)/2; buildtreemax(a,tr,st,mid,2*node,1+yo,x); buildtreemax(a,tr,mid+1,end,2*node+1,1+yo,x); tr[node] = Math.max(tr[2 * node] ,tr[2 * node + 1]); } public static long qtreemin(long tr[],int node , int l , int r , int beg ,int end ) { if(l>end||r<beg) return Integer.MAX_VALUE; if(l<=beg&&end<=r) return tr[node]; int mid =(beg+end)/2; long op1 =qtreemin(tr,2*node,l,r,beg,mid); long op2 =qtreemin(tr,2*node+1,l,r,mid+1,end); return Math.min(op1,op2); } public static long qtreemax(long tr[],int node , int l , int r , int beg ,int end ) { if(l>end||r<beg) return Integer.MIN_VALUE; if(l<=beg&&end<=r) return tr[node]; int mid =(beg+end)/2; long op1 =qtreemax(tr,2*node,l,r,beg,mid); long op2 =qtreemax(tr,2*node+1,l,r,mid+1,end); return Math.max(op1,op2); } public static int sumof(long a) { String s =a+""; int x =0; for(int i =0;i<s.length();i++) x=x+(s.charAt(i)-'0'); return x; } public static void upd(long a[],long tr[], int node ,int beg , int end , int idx, long val,int yo,int x) { if(beg==end) { a[beg]=sumof(a[beg]); tr[node]=sumof(a[beg]); return ; } int mid =(beg+end)/2; if(idx>mid) { upd(a,tr,2*node+1,mid+1,end,idx,val,1+yo,x); } else { upd(a,tr,2*node,beg,mid,idx,val,1+yo,x); } { tr[node] = (tr[2 * node] + tr[2 * node + 1]); } } public static int upper_bound(long arr[], int key) { int mid, N = arr.length; int low = 0; int high = N; while (low < high && low != N) { mid = low + (high - low) / 2; if (key > arr[mid]) { low = mid + 1; } else { high = mid; } } if (low == N ) { return -1; } return low ; } public static void main(String[] args) { try { FastReader in = new FastReader(); FastWriter out = new FastWriter(); // int mx=1000000; // boolean isPrime[] = new boolean[mx+5]; int primeDiv[] = new int[mx+5]; // for (int i = 0; i <= mx; i++) { // isPrime[i] = true; // } // for(int i =0;i<primeDiv.length;i++) // primeDiv[i]=i; // isPrime[0] = isPrime[1] = false; // for (long i = 2; i <= mx; i++) { // if (isPrime[(int)i]) { // for (long j = i*i; j <= mx; j += i) { // if (primeDiv[(int)j] == j) { // primeDiv[(int)j] = (int)i; // } // isPrime[(int)j] = false; // } // } // } // // ArrayList<Integer>[] divisors = new ArrayList[(int) 1e5 + 5]; // for (int i = 0; i < divisors.length; i++) { // divisors[i] = new ArrayList<>(); // } // for (int i = 1; i < divisors.length; i++) { // for (int j = 1; j <= Math.sqrt(i); j++) { // if (i % j == 0) { // divisors[i].add(j); // if (i / j != j) // divisors[i].add(i / j); // } // } // } // System.out.println( // String.format("%.12f", x)); int testCases=1; long mod =1000000007; // System.out.println(c); long fact[]=new long[300001]; fact[0]=1; for(int i =1;i<fact.length;i++) { fact[i]=fact[i-1]*(long) i; fact[i]=fact[i]%998244353; } fl: while (testCases-- > 0) { int n =in.nextInt(); long pa=in.nextLong(); long pb=in.nextLong(); long k =in.nextLong(); long a[]=new long[n]; for(int i =0;i<n;i++) a[i]=in.nextLong(); long pq[]=new long[n]; for(int i =0;i<n;i++) { long curr =a[i]; long yo =0; //System.out.println(curr%(pa+pb)); long x =curr%(pa+pb); if(x==0) x+=pa+pb; yo=(x+pa-1)/pa-1; // System.out.println(); // System.out.println(yo); pq[i]=yo; } sort(pq); long sum =0; int ans =0; for(long i :pq) { sum+=i; if(sum>k) { System.out.println(ans); continue fl; } ans++; } System.out.println(ans); } out.close(); } catch (Exception e) { return; } } // ///DFS To calculate the number of child nodes and depth in tree kind of structure // public static int dfs(ArrayList<ArrayList<Integer>> adj, int s, int d, int child[], int depth[]) { // depth[s] = d; // for(int v: adj.get(s)) { // if(depth[v] == -1) { // child[s] += dfs(adj, v, d+1, child, depth); // } // } // return child[s]+1; // } public static int dfs(ArrayList<ArrayList<Integer>> adj , int node,int dp[],int vis[]) { int ans=1; vis[node]=-1; if(dp[node]!=-1) return ans; for(int i :adj.get(node)) { if(vis[i]==-1) { return Integer.MIN_VALUE; } else ans = ans +dfs(adj, i, dp,vis); } return dp[node]= ans ; } public static void sortby(int arr[][]) { Arrays.sort(arr, new Comparator<int[]>() { @Override // Compare values according to columns public int compare(final int[] entry1, final int[] entry2) { // To sort in descending order revert // the '>' Operator if (entry1[1] >entry2[1]) return 1; else if(entry1[1]<entry2[1]) return -1; else if(entry1[2]>entry2[2]) return 1; else return -1; } }); // End of function call sort(). } static long comb(int r, int n) { long result; result = factorial(n)/(factorial(r)*factorial(n-r)); return result; } static long factorial(int n) { int c; long result = 1; for (c = 1; c <= n; c++) result = result*c; return result; } static void LongestPalindromicPrefix(String str,int lps[]){ // String temp = str + '/'; // str = reverse(str); // temp += str; String temp =str; int n = temp.length(); for(int i = 1; i < n; i++) { int len = lps[i - 1]; while (len > 0 && temp.charAt(len) != temp.charAt(i)) { len = lps[len - 1]; } if (temp.charAt(i) == temp.charAt(len)) { len++; } lps[i] = len; } // return temp.substring(0, lps[n - 1]); } static String reverse(String input) { char[] a = input.toCharArray(); int l, r = a.length - 1; for(l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.valueOf(a); } } /* * *  ┏┓   ┏┓+ + * ┏┛┻━━━┛┻┓ + + * ┃       ┃ * ┃   ━   ┃ ++ + + + * ████━████+ * ◥██◤ ◥██◤ + * ┃   ┻   ┃ * ┃       ┃ + + * ┗━┓   ┏━┛ *   ┃  ┃ JACKS PET FROM ANOTHER WORLD *   ┃  ┃ *   ┃    ┗━━━┓ *   ┃        ┣┓------- *   ┃        ┏┛------- *  ┗┓┓┏━┳┓┏┛ + + + + *    ┃┫┫ ┃┫┫ *    ┗┻┛ ┗┻┛+ + + + */ //RULES //TAKE INPUT AS LONG IN CASE OF SUM OR MULITPLICATION OR CHECK THE CONTSRaint of the array //Always use stringbuilder of out.println for strinof out.println for string or high level output // IMPORTANT TRs1 TO USE BRUTE FORCE TECHNIQUE TO SOLVE THE PROs1 OTHER CERTAIN LIMIT IS GIVENIT IS GIVEN //Read minute details if coming wrong for no idea questions
java
1320
B
B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection vv to another intersection uu is the path that starts in vv, ends in uu and has the minimum length among all such paths.Polycarp lives near the intersection ss and works in a building near the intersection tt. Every day he gets from ss to tt by car. Today he has chosen the following path to his workplace: p1p1, p2p2, ..., pkpk, where p1=sp1=s, pk=tpk=t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from ss to tt.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection ss, the system chooses some shortest path from ss to tt and shows it to Polycarp. Let's denote the next intersection in the chosen path as vv. If Polycarp chooses to drive along the road from ss to vv, then the navigator shows him the same shortest path (obviously, starting from vv as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection ww instead, the navigator rebuilds the path: as soon as Polycarp arrives at ww, the navigation system chooses some shortest path from ww to tt and shows it to Polycarp. The same process continues until Polycarp arrives at tt: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1,2,3,4][1,2,3,4] (s=1s=1, t=4t=4): Check the picture by the link http://tk.codeforces.com/a.png When Polycarp starts at 11, the system chooses some shortest path from 11 to 44. There is only one such path, it is [1,5,4][1,5,4]; Polycarp chooses to drive to 22, which is not along the path chosen by the system. When Polycarp arrives at 22, the navigator rebuilds the path by choosing some shortest path from 22 to 44, for example, [2,6,4][2,6,4] (note that it could choose [2,3,4][2,3,4]); Polycarp chooses to drive to 33, which is not along the path chosen by the system. When Polycarp arrives at 33, the navigator rebuilds the path by choosing the only shortest path from 33 to 44, which is [3,4][3,4]; Polycarp arrives at 44 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 22 rebuilds in this scenario. Note that if the system chose [2,3,4][2,3,4] instead of [2,6,4][2,6,4] during the second step, there would be only 11 rebuild (since Polycarp goes along the path, so the system maintains the path [3,4][3,4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105) — the number of intersections and one-way roads in Bertown, respectively.Then mm lines follow, each describing a road. Each line contains two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) denoting a road from intersection uu to intersection vv. All roads in Bertown are pairwise distinct, which means that each ordered pair (u,v)(u,v) appears at most once in these mm lines (but if there is a road (u,v)(u,v), the road (v,u)(v,u) can also appear).The following line contains one integer kk (2≤k≤n2≤k≤n) — the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1≤pi≤n1≤pi≤n, all these integers are pairwise distinct) — the intersections along Polycarp's path in the order he arrived at them. p1p1 is the intersection where Polycarp lives (s=p1s=p1), and pkpk is the intersection where Polycarp's workplace is situated (t=pkt=pk). It is guaranteed that for every i∈[1,k−1]i∈[1,k−1] the road from pipi to pi+1pi+1 exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInputCopy6 9 1 5 5 4 1 2 2 3 3 4 4 1 2 6 6 4 4 2 4 1 2 3 4 OutputCopy1 2 InputCopy7 7 1 2 2 3 3 4 4 5 5 6 6 7 7 1 7 1 2 3 4 5 6 7 OutputCopy0 0 InputCopy8 13 8 7 8 6 7 5 7 4 6 5 6 4 5 3 5 2 4 3 4 2 3 1 2 1 1 8 5 8 7 5 2 1 OutputCopy0 3
[ "dfs and similar", "graphs", "shortest paths" ]
/* 6 9 1 5 5 4 1 2 2 3 3 4 4 1 2 6 6 4 4 2 4 1 2 3 4 8 13 8 7 8 6 7 5 7 4 6 5 6 4 5 3 5 2 4 3 4 2 3 1 2 1 1 8 5 8 7 5 2 1 */ import java.util.*; import java.io.*; public class Main{ public static int n; //n intersections public static int m; //m paths public static ArrayList<Integer>[] edges; //edges, directed, for the purposes of calculating # of rebuilds that may occur throughout Polycarp's journey public static ArrayList<Integer>[] reversed; //edges, directed, reversed for the purposes of finding shortest public static int[] shortest; //shortest[i] = shortest distance between i and the place where Polycarp's workplace is situated public static int k; //# of intersections on Polycarp's path public static int[] path; //Polycarp's path public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer details = new StringTokenizer(br.readLine()); n = Integer.parseInt(details.nextToken()); m = Integer.parseInt(details.nextToken()); edges = new ArrayList[n]; reversed = new ArrayList[n]; for(int a = 0; a < n; a++){ edges[a] = new ArrayList<Integer>(); reversed[a] = new ArrayList<Integer>(); } for(int a = 0; a < m; a++){ StringTokenizer ed = new StringTokenizer(br.readLine()); int f = Integer.parseInt(ed.nextToken()) - 1; int s = Integer.parseInt(ed.nextToken()) - 1; edges[f].add(s); reversed[s].add(f); } k = Integer.parseInt(br.readLine()); path = new int[k]; StringTokenizer pt = new StringTokenizer(br.readLine()); for(int a = 0; a < k; a++){ path[a] = Integer.parseInt(pt.nextToken()) - 1; } //find shortest run(path[k - 1]); int least = 0; //least # of rebuilds int most = 0; //most # of rebuilds //System.out.println(Arrays.toString(shortest)); for(int cur = 0; cur < k-1; cur++){ HashSet<Integer> s = new HashSet<Integer>(); int st = 1000000000; for(int edge : edges[path[cur]]){ if(shortest[edge] < st){ s.clear(); s.add(edge); st = shortest[edge]; } else if(shortest[edge] == st){ s.add(edge); } } //System.out.println(edges[path[cur]] + " " + path[cur + 1]); //System.out.println(s); //three cases: //multiple shortest paths, polycarp follows one --> add one to most (can project shortest path that polycarp is following or some other shortest path) if(s.contains(path[cur+1]) && s.size() > 1){ most++; } //polycarp does not follow a shortest path --> must add one to least and most (rebuilds no matter what) else if(!s.contains(path[cur+1])){ most++; least++; } //only one shortest path, polycarp follows it --> cannot add to least or most (no rebuilds no matter what) } System.out.println(least + " " + most); br.close(); } public static void run(int start){ shortest = new int[n]; boolean[] seen = new boolean[n]; Arrays.fill(shortest, 1000000000); shortest[start] = 0; Queue<Integer> q = new LinkedList<Integer>(); q.add(start); while(!q.isEmpty()){ int cur = q.poll(); if(!seen[cur]){ seen[cur] = true; for(int edge : reversed[cur]){ if(shortest[edge] > shortest[cur] + 1){ shortest[edge] = shortest[cur] + 1; q.add(edge); } } } } } }
java
1303
E
E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times: choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i2<⋯<ik≤|s|; erase the chosen subsequence from ss (ss can become empty); concatenate chosen subsequence to the right of the string pp (in other words, p=p+si1si2…sikp=p+si1si2…sik). Of course, initially the string pp is empty. For example, let s=ababcds=ababcd. At first, let's choose subsequence s1s4s5=abcs1s4s5=abc — we will get s=bads=bad and p=abcp=abc. At second, let's choose s1s2=bas1s2=ba — we will get s=ds=d and p=abcbap=abcba. So we can build abcbaabcba from ababcdababcd.Can you build a given string tt using the algorithm above?InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain test cases — two per test case. The first line contains string ss consisting of lowercase Latin letters (1≤|s|≤4001≤|s|≤400) — the initial string.The second line contains string tt consisting of lowercase Latin letters (1≤|t|≤|s|1≤|t|≤|s|) — the string you'd like to build.It's guaranteed that the total length of strings ss doesn't exceed 400400.OutputPrint TT answers — one per test case. Print YES (case insensitive) if it's possible to build tt and NO (case insensitive) otherwise.ExampleInputCopy4 ababcd abcba a b defi fed xyz x OutputCopyYES NO NO YES
[ "dp", "strings" ]
import java.util.*; import java.io.*; public class e { public static PrintWriter out; public static FS sc; public static void main(String[] Args) throws Exception { sc = new FS(System.in); out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(System.out))); int t = sc.nextInt(); while (t-->0) { String s = sc.next(); String a = sc.next(); out.println((!defNo(s,a) && defYes(s,a)) ? "YES" : "NO"); } out.close(); } public static boolean defNo(String s, String a) { s = s + s; int n = s.length(); int m = a.length(); int fptr = 0; int i; for (i = 0; i < m; i++) { while (fptr < n && s.charAt(fptr) != a.charAt(i)) fptr++; if (fptr == n) break; fptr++; } return i!= m; } public static int[][] tried = new int[401][401]; public static int n, m, split; public static char[] ss, aa; public static boolean defYes(String s, String a) { n = s.length(); m = a.length(); ss = new char[n]; aa = new char[m]; int[] count = new int[26]; for (int i = 0; i < n; i++) count[(ss[i] = s.charAt(i))-'a']++; for (int i = 0; i < m; i++){ count[(aa[i] = a.charAt(i))-'a']++; } for (int i = 0; i < 26; i++) if (count[i] < 0) return false; for (int j = 0; j <= m; j++) { split = j; for (int[] x : tried) Arrays.fill(x, n); if (rec(0,split,0)) return true; } return false; } public static boolean rec(int a, int b, int c) { if (a == split && b == m) return true; if (tried[a][b] <= c) return false; if (a < split && ss[c] == aa[a] && rec(a+1,b,c+1)) return true; if (b < m && ss[c] == aa[b] && rec(a, b+1, c+1)) return true; if ((a < split && ss[c] == aa[a]) || (b < m && ss[c] == aa[b])){ tried[a][b] = c; return false; } if (rec(a,b,c+1)) return true; tried[a][b] = c; return false; } public static int getCurPow(long cap) { int curPow = 0; while (((1l<<curPow)&cap) == 0) curPow++; return curPow; } public static class FS { BufferedReader br; StringTokenizer st; FS(InputStream in) throws Exception { br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(br.readLine()); } String next() throws Exception { if (st.hasMoreTokens()) return st.nextToken(); st = new StringTokenizer(br.readLine()); return next(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } double nextDouble() throws Exception { return Double.parseDouble(next()); } } }
java
1304
C
C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4 3 0 5 1 2 7 3 5 10 -1 0 2 12 5 7 10 10 16 20 3 -100 100 0 0 100 -50 50 200 100 100 1 100 99 -100 0 OutputCopyYES NO YES NO NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way: At 00-th minute, change the state to heating (the temperature is 0). At 22-nd minute, change the state to off (the temperature is 2). At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied). At 66-th minute, change the state to off (the temperature is 3). At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied). At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
[ "dp", "greedy", "implementation", "sortings", "two pointers" ]
import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main { public static void main(String[] args) { new MainClass().execute(); } } class MainClass extends PrintWriter { MainClass() { super(System.out, true); } boolean cases = true; // Solution void solveIt(int testCaseNo) { int n = sc.nextInt(); long m = sc.nextLong(); List<long[]> al = new ArrayList<>(); for(int i=0;i<n;i++){ long time = sc.nextLong(); long lb = sc.nextLong(); long rb = sc.nextLong(); al.add(new long[]{time,lb,rb}); } long max = m, min = m, prev = 0; for(long x[] : al){ max += (x[0]-prev); min -= (x[0]-prev); if(max < x[1] || min > x[2]) { println("NO"); return; } max = min(max,x[2]); min = max(min,x[1]); prev = x[0]; } println("YES"); } void solve() { int caseNo = 1; if (cases) for (int T = sc.nextInt(); T > 1; T--, caseNo++) { solveIt(caseNo); } solveIt(caseNo); } void execute() { long S = System.currentTimeMillis(); is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); this.sc = new FastIO(); solve(); out.flush(); long G = System.currentTimeMillis(); sc.tr(G - S + "ms"); } class FastIO { private boolean endOfFile() { if (bufferLength == -1) return true; int lptr = ptrbuf; while (lptr < bufferLength) { // __ if (!spaceChar(inputBuffer[lptr++])) return false; } try { is.mark(1000); while (true) { int b = is.read(); if (b == -1) { is.reset(); return true; } else if (!spaceChar(b)) { is.reset(); return false; } } } catch (IOException e) { return true; } } private byte[] inputBuffer = new byte[1024]; int bufferLength = 0, ptrbuf = 0; private int readByte() { if (bufferLength == -1) throw new InputMismatchException(); if (ptrbuf >= bufferLength) { ptrbuf = 0; try { bufferLength = is.read(inputBuffer); } catch (IOException e) { throw new InputMismatchException(); } if (bufferLength <= 0) return -1; } return inputBuffer[ptrbuf++]; } private boolean spaceChar(int c) { return !(c >= 33 && c <= 126); } private int skipIt() { int b; while ((b = readByte()) != -1 && spaceChar(b)); return b; } private double nextDouble() { return Double.parseDouble(next()); } private char nextChar() { return (char) skipIt(); } private String next() { int b = skipIt(); StringBuilder sb = new StringBuilder(); while (!(spaceChar(b))) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] readCharArray(int n) { char[] buf = new char[n]; int b = skipIt(), p = 0; while (p < n && !(spaceChar(b))) { buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] readCharMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = readCharArray(m); return map; } private int[] readIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } private long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } private int nextInt() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nextLong() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private void tr(Object... o) { if (INPUT.length() != 0) System.out.println(Arrays.deepToString(o)); } } InputStream is; PrintWriter out; String INPUT = ""; final int ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE; final long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE; final long mod = (long) 1e9 + 7; FastIO sc; }
java
1299
C
C. Water Balancetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn water tanks in a row, ii-th of them contains aiai liters of water. The tanks are numbered from 11 to nn from left to right.You can perform the following operation: choose some subsegment [l,r][l,r] (1≤l≤r≤n1≤l≤r≤n), and redistribute water in tanks l,l+1,…,rl,l+1,…,r evenly. In other words, replace each of al,al+1,…,aral,al+1,…,ar by al+al+1+⋯+arr−l+1al+al+1+⋯+arr−l+1. For example, if for volumes [1,3,6,7][1,3,6,7] you choose l=2,r=3l=2,r=3, new volumes of water will be [1,4.5,4.5,7][1,4.5,4.5,7]. You can perform this operation any number of times.What is the lexicographically smallest sequence of volumes of water that you can achieve?As a reminder:A sequence aa is lexicographically smaller than a sequence bb of the same length if and only if the following holds: in the first (leftmost) position where aa and bb differ, the sequence aa has a smaller element than the corresponding element in bb.InputThe first line contains an integer nn (1≤n≤1061≤n≤106) — the number of water tanks.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1061≤ai≤106) — initial volumes of water in the water tanks, in liters.Because of large input, reading input as doubles is not recommended.OutputPrint the lexicographically smallest sequence you can get. In the ii-th line print the final volume of water in the ii-th tank.Your answer is considered correct if the absolute or relative error of each aiai does not exceed 10−910−9.Formally, let your answer be a1,a2,…,ana1,a2,…,an, and the jury's answer be b1,b2,…,bnb1,b2,…,bn. Your answer is accepted if and only if |ai−bi|max(1,|bi|)≤10−9|ai−bi|max(1,|bi|)≤10−9 for each ii.ExamplesInputCopy4 7 5 5 7 OutputCopy5.666666667 5.666666667 5.666666667 7.000000000 InputCopy5 7 8 8 10 12 OutputCopy7.000000000 8.000000000 8.000000000 10.000000000 12.000000000 InputCopy10 3 9 5 5 1 7 5 3 8 7 OutputCopy3.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 5.000000000 7.500000000 7.500000000 NoteIn the first sample; you can get the sequence by applying the operation for subsegment [1,3][1,3].In the second sample, you can't get any lexicographically smaller sequence.
[ "data structures", "geometry", "greedy" ]
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1299c_2 { public static void main(String[] args) throws IOException { int n = ri(), a[] = ria(n), hull[] = new int[n + 1], p = 0; long[] pre = new long[n + 1]; for (int i = 0; i < n; ++i) { pre[i + 1] = pre[i] + a[i]; } hull[p++] = 0; for (int i = 1; i <= n; ++i) { // slope(hull[-1] - hull[-2]) > slope(i - hull[-2]) // slope(b - a) = (pre[b] - pre[a]) / (b - a) // (pre[hull[-1]] - pre[hull[-2]]) / (hull[-1] - hull[-2]) > (pre[i] - pre[hull[-1]]) / (i - hull[-1]) // (pre[hull[-1]] - pre[hull[-2]]) * (i - hull[-1]) > (pre[i] - pre[hull[-1]]) * (hull[-1] - hull[-2]) while (p >= 2 && (pre[hull[p - 1]] - pre[hull[p - 2]]) * (i - hull[p - 1]) > (pre[i] - pre[hull[p - 1]]) * (hull[p - 1] - hull[p - 2])) { --p; } hull[p++] = i; } for (int i = 1; i < p; ++i) { double val = (double) (pre[hull[i]] - pre[hull[i - 1]]) / (hull[i] - hull[i - 1]); for (int j = hull[i - 1]; j < hull[i]; ++j) { prln(val); } } close(); } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __rand = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e9 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int fli(double d) {return (int) d;} static int cei(double d) {return (int) ceil(d);} static long fll(double d) {return (long) d;} static long cel(double d) {return (long) ceil(d);} static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);} static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);} static int lcm(int a, int b) {return a * b / gcf(a, b);} static long lcm(long a, long b) {return a * b / gcf(a, b);} static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;} static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);} // array util static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static void rsort(double[] a) {shuffle(a); sort(a);} static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} // graph util static List<List<Integer>> g(int n) {List<List<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;} static List<Set<Integer>> sg(int n) {List<Set<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;} static void c(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);} static void cto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);} static void dc(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);} static void dcto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);} // input static void r() throws IOException {input = new StringTokenizer(rline());} static int ri() throws IOException {return Integer.parseInt(rline());} static long rl() throws IOException {return Long.parseLong(rline());} static double rd() throws IOException {return Double.parseDouble(rline());} static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;} static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;} static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;} static char[] rcha() throws IOException {return rline().toCharArray();} static String rline() throws IOException {return __in.readLine();} static String n() {return input.nextToken();} static int rni() throws IOException {r(); return ni();} static int ni() {return Integer.parseInt(n());} static long rnl() throws IOException {r(); return nl();} static long nl() {return Long.parseLong(n());} static double rnd() throws IOException {r(); return nd();} static double nd() {return Double.parseDouble(n());} static List<List<Integer>> rg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;} static void rg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);} static List<List<Integer>> rdg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;} static void rdg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);} static List<Set<Integer>> rsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;} static void rsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);} static List<Set<Integer>> rdsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;} static void rdsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {prln("yes");} static void pry() {prln("Yes");} static void prY() {prln("YES");} static void prno() {prln("no");} static void prn() {prln("No");} static void prN() {prln("NO");} static void pryesno(boolean b) {prln(b ? "yes" : "no");}; static void pryn(boolean b) {prln(b ? "Yes" : "No");} static void prYN(boolean b) {prln(b ? "YES" : "NO");} static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();} static void h() {prln("hlfd"); flush();} static void flush() {__out.flush();} static void close() {__out.close();}}
java
13
A
A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3 ≤ A ≤ 1000).OutputOutput should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7/3InputCopy3OutputCopy2/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively.
[ "implementation", "math" ]
import java.math.*; import java.util.*; public class Test { static class convertBases{ public static int convertBase(int n, int b){ int p = 0; int fn = n; int pow = 0; while(fn/b != 0){ fn = fn/b; pow++; } while(n != 0){ int d = n/(int)(Math.pow(b, pow)); n -= d * (int)Math.pow(b, pow); pow--; p += d; } return p; } } static class reduceFrac{ public static String reduceFrac(int n, int d){ BigInteger n1 = new BigInteger("" + n); BigInteger d1 = new BigInteger("" + d); BigInteger gcd = n1.gcd(d1); n1 = n1.divide(gcd); d1 = d1.divide(gcd); return n1 + "/" + d1; } } public static void main(String[] args){ Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int t = 0; for(int i = 2; i <= n-1; i++){ t += convertBases.convertBase(n, i); } System.out.print(reduceFrac.reduceFrac(t, n-2)); } }
java
1304
A
A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb. For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5 0 10 2 3 0 10 3 3 900000000 1000000000 1 9999999 1 2 1 1 1 3 1 1 OutputCopy2 -1 10 -1 1 NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward.
[ "math" ]
import java.util.Scanner; public class template { static Scanner sc = new Scanner(System.in); public static void main(String[] args) { int t = sc.nextInt(); for (int i = 0; i < t; i++) { solve(); } } public static void solve() { long a = sc.nextLong(); long b = sc.nextLong(); long x = sc.nextLong(); long y = sc.nextLong(); long c = b-a; long d = x+y; if (c % d == 0) { System.out.println(c/d); } else System.out.println(-1); } }
java
1285
C
C. Fadi and LCMtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Osama gave Fadi an integer XX, and Fadi was wondering about the minimum possible value of max(a,b)max(a,b) such that LCM(a,b)LCM(a,b) equals XX. Both aa and bb should be positive integers.LCM(a,b)LCM(a,b) is the smallest positive integer that is divisible by both aa and bb. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.Of course, Fadi immediately knew the answer. Can you be just like Fadi and find any such pair?InputThe first and only line contains an integer XX (1≤X≤10121≤X≤1012).OutputPrint two positive integers, aa and bb, such that the value of max(a,b)max(a,b) is minimum possible and LCM(a,b)LCM(a,b) equals XX. If there are several possible such pairs, you can print any.ExamplesInputCopy2 OutputCopy1 2 InputCopy6 OutputCopy2 3 InputCopy4 OutputCopy1 4 InputCopy1 OutputCopy1 1
[ "brute force", "math", "number theory" ]
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.*; public class weird_algrithm { static BufferedWriter output = new BufferedWriter( new OutputStreamWriter(System.out)); static BufferedReader sc = new BufferedReader(new InputStreamReader(System.in)); static int mod = 1000000007; static String toReturn = ""; static int steps = Integer.MAX_VALUE; static int maxlen = 1000005; /*MATHEMATICS FUNCTIONS START HERE MATHS MATHS MATHS MATHS*/ static long gcd(long a, long b) { if(b == 0) return a; else return gcd(b, a % b); } static long powerMod(long x, long y, int mod) { if(y == 0) return 1; long temp = powerMod(x, y / 2, mod); temp = ((temp % mod) * (temp % mod)) % mod; if(y % 2 == 0) return temp; else return ((x % mod) * (temp % mod)) % mod; } static long modInverse(long n, int p) { return powerMod(n, p - 2, p); } static long nCr(int n, int r, int mod, long [] fact, long [] ifact) { return ((fact[n] % mod) * ((ifact[r] * ifact[n - r]) % mod)) % mod; } static boolean isPrime(long a) { if(a == 1) return false; else if(a == 2 || a == 3 || a== 5) return true; else if(a % 2 == 0 || a % 3 == 0) return false; for(int i = 5; i * i <= a; i = i + 6) { if(a % i == 0 || a % (i + 2) == 0) return false; } return true; } static int [] seive(int a) { int [] toReturn = new int [a + 1]; for(int i = 0; i < a; i++) toReturn[i] = 1; toReturn[0] = 0; toReturn[1] = 0; toReturn[2] = 1; for(int i = 2; i * i <= a; i++) { if(toReturn[i] == 0) continue; for(int j = 2 * i; j <= a; j += i) toReturn[j] = 0; } return toReturn; } static long [] fact(int a) { long [] arr = new long[a + 1]; arr[0] = 1; for(int i = 1; i < a + 1; i++) { arr[i] = (arr[i - 1] * i) % mod; } return arr; } static ArrayList<Integer> divisors(int n) { ArrayList<Integer> arr = new ArrayList<Integer>(); for(int i = 2; i * i <= n; i++) { if(n % i == 0) { while(n % i == 0) { n /= i; arr.add(i); } } } if(n > 1) arr.add(n); return arr; } static int euler(int n) { int ans = n; for(int i = 2; i * i <= n; i++) { if(n % i == 0) { while(n % i == 0) { n /= i; } ans -= ans / i; } } if(n > 1) ans -= ans / n; return ans; } /*MATHS MATHS MATHS MATHS MATHEMATICS FUNCTIONS END HERE */ /*SWAP FUNCTION START HERE SWAP SWAP SWAP SWAP */ static void swap(int i, int j, long[] arr) { long temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static void swap(int i, int j, int[] arr) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static void swap(int i, int j, String [] arr) { String temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static void swap(int i, int j, char [] arr) { char temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } /*SWAP SWAP SWAP SWAP SWAP FUNCTION END HERE*/ /*BINARY SEARCH METHODS START HERE * BINARY SEARCH * BINARY SEARCH * BINARY SEARCH * BINARY SEARCH */ static boolean BinaryCheck(long test, long [] arr, long health) { for(int i = 0; i <= arr.length - 1; i++) { if(i == arr.length - 1) health -= test; else if(arr[i + 1] - arr[i] > test) { health = health - test; }else { health = health - (arr[i + 1] - arr[i]); } if(health <= 0) return true; } return false; } static long binarySearchModified(long start1, long n, ArrayList<Integer> arr, int val) { long start = start1, end = n, ans = -1; while(start <= end) { long mid = (start + end) / 2; if(arr.get((int)mid) >= val) { if(arr.get((int)mid) == val && mid + 1 < arr.size() && arr.get((int)mid + 1) == val) { start = mid + 1; }else if(arr.get((int)mid) == val) { return mid; }else end = mid - 1; }else { start = mid + 1; } } //System.out.println(); return start; } static int upper(int start, int end, ArrayList<Integer> pairs, long val) { while(start < end) { int mid = (start + end) / 2; if(pairs.get(mid) <= val) start = mid + 1; else end = mid; } return start; } static int lower(int start, int end, ArrayList<Long> arr, long val) { while(start < end) { int mid = (start + end) / 2; if(arr.get(mid) >= val) end = mid; else start = mid + 1; } return start; } /*BINARY SEARCH * BINARY SEARCH * BINARY SEARCH * BINARY SEARCH * BINARY SEARCH BINARY SEARCH METHODS END HERE*/ /*RECURSIVE FUNCTION START HERE * RECURSIVE * RECURSIVE * RECURSIVE * RECURSIVE */ static int recurse(int x, int y, int n, int steps1, Integer [][] dp) { if(x > n || y > n) return 0; if(dp[x][y] != null) { return dp[x][y]; } else if(x == n || y == n) { return steps1; } return dp[x][y] = Math.max(recurse(x + y, y, n, steps1 + 1, dp), recurse(x, x + y, n, steps1 + 1, dp)); } /*RECURSIVE * RECURSIVE * RECURSIVE * RECURSIVE * RECURSIVE RECURSIVE FUNCTION END HERE*/ /*GRAPH FUNCTIONS START HERE * GRAPH * GRAPH * GRAPH * GRAPH * */ static class edge{ int from, to; long weight; public edge(int x, int y, long weight2) { this.from = x; this.to = y; this.weight = weight2; } } static class sort implements Comparator<TreeNode>{ @Override public int compare(TreeNode a, TreeNode b) { // TODO Auto-generated method stub return 0; } } static void addEdge(ArrayList<ArrayList<edge>> graph, int from, int to, long weight) { edge temp = new edge(from, to, weight); edge temp1 = new edge(to, from, weight); graph.get(from).add(temp); //graph.get(to).add(temp1); } static int ans = 0; static void topoSort(ArrayList<ArrayList<Integer>> graph, int vertex, boolean [] visited, ArrayList<Integer> toReturn) { if(visited[vertex]) return; visited[vertex] = true; for(int i = 0; i < graph.get(vertex).size(); i++) { if(!visited[graph.get(vertex).get(i)]) topoSort(graph, graph.get(vertex).get(i), visited, toReturn); } toReturn.add(vertex); } static boolean isCyclicDirected(ArrayList<ArrayList<Integer>> graph, int vertex, boolean [] visited, boolean [] reStack) { if(reStack[vertex]) return true; if(visited[vertex]) return false; reStack[vertex] = true; visited[vertex] = true; for(int i = 0; i < graph.get(vertex).size(); i++) { if(isCyclicDirected(graph, graph.get(vertex).get(i), visited, reStack)) return true; } reStack[vertex] = false; return false; } static int e = 0; static long mst(PriorityQueue<edge> pq, int nodes) { long weight = 0; int [] size = new int[nodes + 1]; Arrays.fill(size, 1); while(!pq.isEmpty()) { edge temp = pq.poll(); int x = parent(parent, temp.to); int y = parent(parent, temp.from); if(x != y) { //System.out.println(temp.weight); union(x, y, rank, parent, size); weight += temp.weight; e++; } } return weight; } static void floyd(long [][] dist) { // to find min distance between two nodes for(int k = 0; k < dist.length; k++) { for(int i = 0; i < dist.length; i++) { for(int j = 0; j < dist.length; j++) { if(dist[i][j] > dist[i][k] + dist[k][j]) { dist[i][j] = dist[i][k] + dist[k][j]; } } } } } static void dijkstra(ArrayList<ArrayList<edge>> graph, long [] dist, int src) { for(int i = 0; i < dist.length; i++) dist[i] = Long.MAX_VALUE / 2; dist[src] = 0; boolean visited[] = new boolean[dist.length]; PriorityQueue<pair> pq = new PriorityQueue<>(); pq.add(new pair(src, 0)); while(!pq.isEmpty()) { pair temp = pq.poll(); int index = (int)temp.a; for(int i = 0; i < graph.get(index).size(); i++) { if(dist[graph.get(index).get(i).to] > dist[index] + graph.get(index).get(i).weight) { dist[graph.get(index).get(i).to] = dist[index] + graph.get(index).get(i).weight; pq.add(new pair(graph.get(index).get(i).to, graph.get(index).get(i).weight)); } } } } static int parent1 = -1; static boolean ford(ArrayList<ArrayList<edge>> graph1, ArrayList<edge> graph, long [] dist, int src, int [] parent) { for(int i = 0; i < dist.length; i++) dist[i] = Long.MIN_VALUE / 2; dist[src] = 0; boolean hasNeg = false; for(int i = 0; i < dist.length - 1; i++) { for(int j = 0; j < graph.size(); j++) { int from = graph.get(j).from; int to = graph.get(j).to; long weight = graph.get(j).weight; if(dist[to] < dist[from] + weight) { dist[to] = dist[from] + weight; parent[to] = from; } } } for(int i = 0; i < graph.size(); i++) { int from = graph.get(i).from; int to = graph.get(i).to; long weight = graph.get(i).weight; if(dist[to] < dist[from] + weight) { parent1 = from; hasNeg = true; /* * dfs(graph1, parent1, new boolean[dist.length], dist.length - 1); * //System.out.println(ans); dfs(graph1, 0, new boolean[dist.length], parent1); */ //System.out.println(ans); if(ans == 2) break; else ans = 0; } } return hasNeg; } /*GRAPH FUNCTIONS END HERE * GRAPH * GRAPH * GRAPH * GRAPH */ /*disjoint Set START HERE * disjoint Set * disjoint Set * disjoint Set * disjoint Set */ static int [] rank; static int [] parent; static int parent(int [] parent, int x) { if(parent[x] == x) return x; else return parent[x] = parent(parent, parent[x]); } static boolean union(int x, int y, int [] rank, int [] parent, int [] setSize) { if(parent(parent, x) == parent(parent, y)) { return true; } if (rank[x] > rank[y]) { parent[y] = x; setSize[x] += setSize[y]; } else { parent[x] = y; setSize[y] += setSize[x]; if (rank[x] == rank[y]) rank[y]++; } return false; } /*disjoint Set END HERE * disjoint Set * disjoint Set * disjoint Set * disjoint Set */ /*INPUT START HERE * INPUT * INPUT * INPUT * INPUT * INPUT */ static int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(sc.readLine()); } static long nextLong() throws NumberFormatException, IOException { return Long.parseLong(sc.readLine()); } static long [] inputLongArr() throws NumberFormatException, IOException{ String [] s = sc.readLine().split(" "); long [] toReturn = new long[s.length]; for(int i = 0; i < s.length; i++) { toReturn[i] = Long.parseLong(s[i]); } return toReturn; } static int max = 0; static int [] inputIntArr() throws NumberFormatException, IOException{ String [] s = sc.readLine().split(" "); //System.out.println(s.length); int [] toReturn = new int[s.length]; for(int i = 0; i < s.length; i++) { toReturn[i] = Integer.parseInt(s[i]); } return toReturn; } /*INPUT * INPUT * INPUT * INPUT * INPUT * INPUT END HERE */ static long [] preCompute(int level) { long [] toReturn = new long[level]; toReturn[0] = 1; toReturn[1] = 16; for(int i = 2; i < level; i++) { toReturn[i] = ((toReturn[i - 1] % mod) * (toReturn[i - 1] % mod)) % mod; } return toReturn; } static class pair{ long a; long b; long d; public pair(long in, long y) { this.a = in; this.b = y; this.d = 0; } } static int [] nextGreaterBack(char [] s) { Stack<Integer> stack = new Stack<>(); int [] toReturn = new int[s.length]; for(int i = 0; i < s.length; i++) { if(!stack.isEmpty() && s[stack.peek()] >= s[i]) { stack.pop(); } if(stack.isEmpty()) { stack.push(i); toReturn[i] = -1; }else { toReturn[i] = stack.peek(); stack.push(i); } } return toReturn; } static int [] nextGreaterFront(char [] s) { Stack<Integer> stack = new Stack<>(); int [] toReturn = new int[s.length]; for(int i = s.length - 1; i >= 0; i--) { if(!stack.isEmpty() && s[stack.peek()] >= s[i]) { stack.pop(); } if(stack.isEmpty()) { stack.push(i); toReturn[i] = -1; }else { toReturn[i] = stack.peek(); stack.push(i); } } return toReturn; } static int [] lps(String s) { int [] lps = new int[s.length()]; lps[0] = 0; int j = 0; for(int i = 1; i < lps.length; i++) { j = lps[i - 1]; while(j > 0 && s.charAt(i) != s.charAt(j)) j = lps[j - 1]; if(s.charAt(i) == s.charAt(j)) { lps[i] = j + 1; } } return lps; } static int [][] vectors = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; static String dir = "DRUL"; static boolean check(int i, int j, boolean [][] visited) { if(i >= visited.length || j >= visited[0].length) return false; if(i < 0 || j < 0) return false; return true; } static void selectionSort(long arr[], long [] arr1, ArrayList<ArrayList<Integer>> ans) { int n = arr.length; for (int i = 0; i < n-1; i++) { int min_idx = i; for (int j = i+1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; else if(arr[j] == arr[min_idx]) { if(arr1[j] < arr1[min_idx]) min_idx = j; } if(i == min_idx) { continue; } ArrayList<Integer> p = new ArrayList<Integer>(); p.add(min_idx + 1); p.add(i + 1); ans.add(new ArrayList<Integer>(p)); swap(i, min_idx, arr); swap(i, min_idx, arr1); } } static int saved = Integer.MAX_VALUE; static String ans1 = ""; public static boolean isValid(int x, int y, String [] mat) { if(x >= mat.length || x < 0) return false; if(y >= mat[0].length() || y < 0) return false; return true; } public static void recurse3(ArrayList<Character> arr, int index, String s, int max, ArrayList<String> toReturn) { if(s.length() == max) { toReturn.add(s); return; } if(index == arr.size()) return; recurse3(arr, index + 1, s + arr.get(index), max, toReturn); recurse3(arr, index + 1, s, max, toReturn); } /* if(arr[i] > q) return Math.max(f(i + 1, q - 1) + 1, f(i + 1, q); else return f(i + 1, q) + 1 */ static void dfsDP(ArrayList<ArrayList<Integer>> graph, int src, int [] dp1, int [] dp2, int parent) { int sum1 = 0; int sum2 = 0; for(int x : graph.get(src)) { if(x == parent) continue; dfsDP(graph, x, dp1, dp2, src); sum1 += Math.min(dp1[x], dp2[x]); sum2 += dp1[x]; } dp1[src] = 1 + sum1; dp2[src] = sum2; System.out.println(src + " " + dp1[src] + " " + dp2[src]); } static int balanced = 0; static void dfs(ArrayList<ArrayList<ArrayList<Long>>> graph, long src, int [] dist, long sum1, long sum2, long parent, ArrayList<Long> arr, int index) { index = 0;//binarySearch(index, arr.size() - 1, arr, sum1); if(index < arr.size() && arr.get(index) <= sum1) { dist[(int)src] = index + 1; } else dist[(int)src] = index; for(ArrayList<Long> x : graph.get((int)src)) { if(x.get(0) == parent) continue; if(arr.size() != 0) arr.add(arr.get(arr.size() - 1) + x.get(2)); else arr.add(x.get(2)); dfs(graph, x.get(0), dist, sum1 + x.get(1), sum2, src, arr, index); arr.remove(arr.size() - 1); } } static int compare(String s1, String s2) { Queue<Character> q1 = new LinkedList<>(); Queue<Character> q2 = new LinkedList<Character>(); for(int i = 0; i < s1.length(); i++) { q1.add(s1.charAt(i)); q2.add(s2.charAt(i)); } int k = 0; while(k < s1.length()) { if(q1.equals(q2)) { break; } q2.add(q2.poll()); k++; } return k; } static long pro = 0; public static int len(ArrayList<ArrayList<Integer>> graph, int src, boolean [] visited ) { visited[src] = true; int max = 0; for(int x : graph.get(src)) { if(!visited[x]) { visited[x] = true; int len = len(graph, x, visited) + 1; //System.out.println(len); pro = Math.max(max * (len - 1), pro); max = Math.max(len, max); } } return max; } public static void recurse(int l, int [] ans) { if(l < 0) return; int r = (int)Math.sqrt(l * 2); int s = r * r; r = s - l; recurse(r - 1, ans); while(r <= l) { ans[r] = l; ans[l] = r; r++; l--; } } static boolean isSmaller(String str1, String str2) { // Calculate lengths of both string int n1 = str1.length(), n2 = str2.length(); if (n1 < n2) return true; if (n2 < n1) return false; for (int i = 0; i < n1; i++) if (str1.charAt(i) < str2.charAt(i)) return true; else if (str1.charAt(i) > str2.charAt(i)) return false; return false; } // Function for find difference of larger numbers static String findDiff(String str1, String str2) { // Before proceeding further, make sure str1 // is not smaller if (isSmaller(str1, str2)) { String t = str1; str1 = str2; str2 = t; } // Take an empty string for storing result String str = ""; // Calculate length of both string int n1 = str1.length(), n2 = str2.length(); // Reverse both of strings str1 = new StringBuilder(str1).reverse().toString(); str2 = new StringBuilder(str2).reverse().toString(); int carry = 0; // Run loop till small string length // and subtract digit of str1 to str2 for (int i = 0; i < n2; i++) { // Do school mathematics, compute difference of // current digits int sub = ((int)(str1.charAt(i) - '0') - (int)(str2.charAt(i) - '0') - carry); // If subtraction is less than zero // we add then we add 10 into sub and // take carry as 1 for calculating next step if (sub < 0) { sub = sub + 10; carry = 1; } else carry = 0; str += (char)(sub + '0'); } // subtract remaining digits of larger number for (int i = n2; i < n1; i++) { int sub = ((int)(str1.charAt(i) - '0') - carry); // if the sub value is -ve, then make it // positive if (sub < 0) { sub = sub + 10; carry = 1; } else carry = 0; str += (char)(sub + '0'); } // reverse resultant string return new StringBuilder(str).reverse().toString(); } static void solve() throws IOException { long n = nextLong(); long [] ans = new long [2]; Arrays.fill(ans, Long.MAX_VALUE); for(long i = 1; i * i <= n; i++) { if(n % i == 0) { if(gcd(n / i, i) == (long)1) { if(Math.max(ans[0], ans[1]) > Math.max(i, n / i)) { ans[0] = i; ans[1] = n / i; } } } } output.write(ans[0] + " " + ans[1] + "\n"); } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub //int t = Integer.parseInt(sc.readLine()); for(int i = 0; i < t; i++) solve(); output.flush(); } } class TreeNode { int val; int index; public TreeNode(int val, int index) { this.val = val; this.index = index; } public String toString() { return val + " " + index; } } /* 1 10 6 10 7 9 11 99 45 20 88 31 */
java
1322
C
C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset SS of vertices of the left half we define N(S)N(S) as the set of all vertices of the right half adjacent to at least one vertex in SS, and f(S)f(S) as the sum of all numbers in vertices of N(S)N(S). Find the greatest common divisor of f(S)f(S) for all possible non-empty subsets SS (assume that GCD of empty set is 00).Wu is too tired after his training to solve this problem. Help him!InputThe first line contains a single integer tt (1≤t≤5000001≤t≤500000) — the number of test cases in the given test set. Test case descriptions follow.The first line of each case description contains two integers nn and mm (1 ≤ n, m ≤ 5000001 ≤ n, m ≤ 500000) — the number of vertices in either half of the graph, and the number of edges respectively.The second line contains nn integers cici (1≤ci≤10121≤ci≤1012). The ii-th number describes the integer in the vertex ii of the right half of the graph.Each of the following mm lines contains a pair of integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n), describing an edge between the vertex uiui of the left half and the vertex vivi of the right half. It is guaranteed that the graph does not contain multiple edges.Test case descriptions are separated with empty lines. The total value of nn across all test cases does not exceed 500000500000, and the total value of mm across all test cases does not exceed 500000500000 as well.OutputFor each test case print a single integer — the required greatest common divisor.ExampleInputCopy3 2 4 1 1 1 1 1 2 2 1 2 2 3 4 1 1 1 1 1 1 2 2 2 2 3 4 7 36 31 96 29 1 2 1 3 1 4 2 2 2 4 3 1 4 3 OutputCopy2 1 12 NoteThe greatest common divisor of a set of integers is the largest integer gg such that all elements of the set are divisible by gg.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S)f(S) for any non-empty subset is 22, thus the greatest common divisor of these values if also equal to 22.In the second sample case the subset {1}{1} in the left half is connected to vertices {1,2}{1,2} of the right half, with the sum of numbers equal to 22, and the subset {1,2}{1,2} in the left half is connected to vertices {1,2,3}{1,2,3} of the right half, with the sum of numbers equal to 33. Thus, f({1})=2f({1})=2, f({1,2})=3f({1,2})=3, which means that the greatest common divisor of all values of f(S)f(S) is 11.
[ "graphs", "hashing", "math", "number theory" ]
import java.io.*; import java.util.*; import java.util.Map.Entry; public class gym{ static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static class set implements Comparable<set>{ int[]nodes; set(TreeSet<Integer>t){ nodes=new int[t.size()]; int idx=0; for(int n:t) { nodes[idx++]=n; } } @Override public int compareTo(set o) { int idx=0; while(true) { if(idx>=nodes.length && idx>=o.nodes.length)return 0; if(idx>=nodes.length)return -1; if(idx>=o.nodes.length)return 1; if(nodes[idx]<o.nodes[idx])return -1; if(nodes[idx]>o.nodes[idx])return 1; idx++; } } } public static void main(String[] args) throws Exception{ MScanner sc=new MScanner(System.in); PrintWriter pw=new PrintWriter(System.out); int tc=sc.nextInt(); while(tc-->0) { int n=sc.nextInt(),m=sc.nextInt(); long[]vals=sc.takearrl(n); TreeSet<Integer>[]adj=new TreeSet[n]; for(int i=0;i<n;i++) { adj[i]=new TreeSet<Integer>(); } for(int i=0;i<m;i++) { int left=sc.nextInt()-1,right=sc.nextInt()-1; adj[right].add(left); } TreeMap<set,Long>map=new TreeMap<set, Long>(); for(int i=0;i<n;i++) { if(adj[i].size()==0)continue; set Set=new set(adj[i]); map.put(Set, map.getOrDefault(Set, 0l)+vals[i]); } long ans=0; for(Entry<set, Long>e:map.entrySet()) { ans=gcd(ans, e.getValue()); } pw.println(ans); } pw.flush(); } static class MScanner { StringTokenizer st; BufferedReader br; public MScanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public MScanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int[] takearr(int n) throws IOException { int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public long[] takearrl(int n) throws IOException { long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public Integer[] takearrobj(int n) throws IOException { Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt(); return in; } public Long[] takearrlobj(int n) throws IOException { Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong(); return in; } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
java
1301
D
D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to: in the case 'U' to the cell (i−1,j)(i−1,j); in the case 'D' to the cell (i+1,j)(i+1,j); in the case 'L' to the cell (i,j−1)(i,j−1); in the case 'R' to the cell (i,j+1)(i,j+1); He wants to run exactly kk kilometers, so he wants to make exactly kk moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4 OutputCopyYES 2 2 R 2 L InputCopy3 3 1000000000 OutputCopyNO InputCopy3 3 8 OutputCopyYES 3 2 R 2 D 1 LLRR InputCopy4 4 9 OutputCopyYES 1 3 RLD InputCopy3 4 16 OutputCopyYES 8 3 R 3 L 1 D 3 R 1 D 1 U 3 L 1 D NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
[ "constructive algorithms", "graphs", "implementation" ]
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1301d { public static void main(String[] args) throws IOException { int n = rni(), m = ni(), k = ni(); if (k > 4 * n * m - 2 * n - 2 * m) { prN(); } else { prY(); List<step> ans = new ArrayList<>(); if (m > 1) { if (k > m - 1) { ans.add(new step(m - 1, "R")); k -= m - 1; } else if(k > 0) { ans.add(new step(k, "R")); k = 0; } if (k > m - 1) { ans.add(new step(m - 1, "L")); k -= m - 1; } else if(k > 0) { ans.add(new step(k, "L")); k = 0; } } if (k >= 1) { ans.add(new step(1, "D")); k -= 1; } for (int i = 1; i < n; ++i) { if (m > 1) { if (k > 3 * (m - 1)) { ans.add(new step(m - 1, "RUD")); k -= 3 * (m - 1); } else { if (k > 3) { ans.add(new step(k / 3, "RUD")); k %= 3; } if (k > 0) { ans.add(new step(1, "RUD".substring(0, k))); k = 0; } } if (k > m - 1) { ans.add(new step(m - 1, "L")); k -= m - 1; } else if (k > 0) { ans.add(new step(k, "L")); k = 0; } } if (i < n - 1 && k >= 1) { ans.add(new step(1, "D")); k -= 1; } } if (k > n - 1) { assert false; ans.add(new step(n - 1, "U")); k -= n - 1; } else if (k > 0) { ans.add(new step(k, "U")); } prln(ans.size()); for (step s : ans) { pr(s.n); pr(' '); prln(s.op); } } close(); } static class step { int n; String op; step(int n_, String op_) { n = n_; op = op_; } } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __rand = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e9 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int fli(double d) {return (int)d;} static int cei(double d) {return (int)ceil(d);} static long fll(double d) {return (long)d;} static long cel(double d) {return (long)ceil(d);} static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);} static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);} static int lcm(int a, int b) {return a * b / gcf(a, b);} static long lcm(long a, long b) {return a * b / gcf(a, b);} static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;} static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);} // array util static void reverse(int[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(double[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static void rsort(double[] a) {shuffle(a); sort(a);} static int[] copy(int[] a) {int[] ans = new int[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static long[] copy(long[] a) {long[] ans = new long[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static double[] copy(double[] a) {double[] ans = new double[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static char[] copy(char[] a) {char[] ans = new char[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} // graph util static List<List<Integer>> g(int n) {List<List<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;} static List<Set<Integer>> sg(int n) {List<Set<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;} static void c(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);} static void cto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);} static void dc(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);} static void dcto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);} // input static void r() throws IOException {input = new StringTokenizer(rline());} static int ri() throws IOException {return Integer.parseInt(rline());} static long rl() throws IOException {return Long.parseLong(rline());} static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for(int i = 0; i < n; ++i) a[i] = ni(); return a;} static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for(int i = 0; i < n; ++i) a[i] = ni() - 1; return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for(int i = 0; i < n; ++i) a[i] = nl(); return a;} static char[] rcha() throws IOException {return rline().toCharArray();} static String rline() throws IOException {return __in.readLine();} static String n() {return input.nextToken();} static int rni() throws IOException {r(); return ni();} static int ni() {return Integer.parseInt(n());} static long rnl() throws IOException {r(); return nl();} static long nl() {return Long.parseLong(n());} static double rnd() throws IOException {r(); return nd();} static double nd() {return Double.parseDouble(n());} static List<List<Integer>> rg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;} static void rg(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);} static List<List<Integer>> rdg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;} static void rdg(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);} static List<Set<Integer>> rsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;} static void rsg(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);} static List<Set<Integer>> rdsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;} static void rdsg(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {__out.println("yes");} static void pry() {__out.println("Yes");} static void prY() {__out.println("YES");} static void prno() {__out.println("no");} static void prn() {__out.println("No");} static void prN() {__out.println("NO");} static void pryesno(boolean b) {__out.println(b ? "yes" : "no");}; static void pryn(boolean b) {__out.println(b ? "Yes" : "No");} static void prYN(boolean b) {__out.println(b ? "YES" : "NO");} static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(double... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next()); else __out.println();} static void h() {__out.println("hlfd"); flush();} static void flush() {__out.flush();} static void close() {__out.close();} }
java
1300
B
B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3 1 1 1 3 6 5 4 1 2 3 5 13 4 20 13 2 5 8 3 17 16 OutputCopy0 1 5 NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference.
[ "greedy", "implementation", "sortings" ]
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); int testCases = input.nextInt(); for(int index = 0; index < testCases; index++) { int studentsHalved = input.nextInt(); int students[] = new int[studentsHalved*2]; int lowestDiff = Integer.MAX_VALUE; for(int counter = 0; counter < students.length; counter++) { students[counter] = input.nextInt(); } Arrays.sort(students); System.out.println(Math.abs(students[studentsHalved - 1] - students[studentsHalved])); } } }
java
1322
C
C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset SS of vertices of the left half we define N(S)N(S) as the set of all vertices of the right half adjacent to at least one vertex in SS, and f(S)f(S) as the sum of all numbers in vertices of N(S)N(S). Find the greatest common divisor of f(S)f(S) for all possible non-empty subsets SS (assume that GCD of empty set is 00).Wu is too tired after his training to solve this problem. Help him!InputThe first line contains a single integer tt (1≤t≤5000001≤t≤500000) — the number of test cases in the given test set. Test case descriptions follow.The first line of each case description contains two integers nn and mm (1 ≤ n, m ≤ 5000001 ≤ n, m ≤ 500000) — the number of vertices in either half of the graph, and the number of edges respectively.The second line contains nn integers cici (1≤ci≤10121≤ci≤1012). The ii-th number describes the integer in the vertex ii of the right half of the graph.Each of the following mm lines contains a pair of integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n), describing an edge between the vertex uiui of the left half and the vertex vivi of the right half. It is guaranteed that the graph does not contain multiple edges.Test case descriptions are separated with empty lines. The total value of nn across all test cases does not exceed 500000500000, and the total value of mm across all test cases does not exceed 500000500000 as well.OutputFor each test case print a single integer — the required greatest common divisor.ExampleInputCopy3 2 4 1 1 1 1 1 2 2 1 2 2 3 4 1 1 1 1 1 1 2 2 2 2 3 4 7 36 31 96 29 1 2 1 3 1 4 2 2 2 4 3 1 4 3 OutputCopy2 1 12 NoteThe greatest common divisor of a set of integers is the largest integer gg such that all elements of the set are divisible by gg.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S)f(S) for any non-empty subset is 22, thus the greatest common divisor of these values if also equal to 22.In the second sample case the subset {1}{1} in the left half is connected to vertices {1,2}{1,2} of the right half, with the sum of numbers equal to 22, and the subset {1,2}{1,2} in the left half is connected to vertices {1,2,3}{1,2,3} of the right half, with the sum of numbers equal to 33. Thus, f({1})=2f({1})=2, f({1,2})=3f({1,2})=3, which means that the greatest common divisor of all values of f(S)f(S) is 11.
[ "graphs", "hashing", "math", "number theory" ]
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.util.Random; import java.util.HashMap; import java.util.Collections; import java.util.ArrayList; 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; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); CInstantNoodles solver = new CInstantNoodles(); solver.solve(1, in, out); out.close(); } static class CInstantNoodles { long[] random; public void solve(int testNumber, ScanReader in, PrintWriter out) { int t = in.scanInt(); random = new long[500005]; for (int i = 0; i < random.length; i++) random[i] = new Random().nextInt(1000000000) + 234792734l; while (t-- > 0) { int n = in.scanInt(); int m = in.scanInt(); long cost[] = new long[n + 1]; for (int i = 1; i <= n; i++) cost[i] = in.scanLong(); ArrayList<Integer> arrayList[] = new ArrayList[n + 1]; for (int i = 1; i <= n; i++) arrayList[i] = new ArrayList<>(); HashMap<Long, Long> hashMap = new HashMap<>(); for (int i = 0; i < m; i++) { int a = in.scanInt(); int b = in.scanInt(); arrayList[b].add(a); } for (int i = 1; i <= n; i++) { if (arrayList[i].size() == 0) continue; Collections.sort(arrayList[i]); long hash = CodeX.compute_hash(arrayList[i]); hashMap.put(hash, cost[i] + hashMap.getOrDefault(hash, 0l)); } long gcd = 0; for (long kkk : hashMap.values()) { gcd = CodeX.GCD(gcd, kkk); } out.println(gcd); } } } static class CodeX { public static long compute_hash(ArrayList<Integer> arrayList) { long p = 31; long m = 1000000000l + 9; long hash_value = 0; long p_pow = 1; for (int c : arrayList) { hash_value = (hash_value + (c + 1) * p_pow) % m; p_pow = (p_pow * p) % m; } return hash_value; } public static long GCD(long A, long B) { if (B == 0) return A; else return GCD(B, A % B); } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int INDEX; private BufferedInputStream in; private int TOTAL; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (INDEX >= TOTAL) { INDEX = 0; try { TOTAL = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (TOTAL <= 0) return -1; } return buf[INDEX++]; } public int scanInt() { int I = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { I *= 10; I += n - '0'; n = scan(); } } return neg * I; } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } public long scanLong() { long I = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { I *= 10; I += n - '0'; n = scan(); } } return neg * I; } } }
java
1324
C
C. Frog Jumpstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a frog staying to the left of the string s=s1s2…sns=s1s2…sn consisting of nn characters (to be more precise, the frog initially stays at the cell 00). Each character of ss is either 'L' or 'R'. It means that if the frog is staying at the ii-th cell and the ii-th character is 'L', the frog can jump only to the left. If the frog is staying at the ii-th cell and the ii-th character is 'R', the frog can jump only to the right. The frog can jump only to the right from the cell 00.Note that the frog can jump into the same cell twice and can perform as many jumps as it needs.The frog wants to reach the n+1n+1-th cell. The frog chooses some positive integer value dd before the first jump (and cannot change it later) and jumps by no more than dd cells at once. I.e. if the ii-th character is 'L' then the frog can jump to any cell in a range [max(0,i−d);i−1][max(0,i−d);i−1], and if the ii-th character is 'R' then the frog can jump to any cell in a range [i+1;min(n+1;i+d)][i+1;min(n+1;i+d)].The frog doesn't want to jump far, so your task is to find the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it can jump by no more than dd cells at once. It is guaranteed that it is always possible to reach n+1n+1 from 00.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. The ii-th test case is described as a string ss consisting of at least 11 and at most 2⋅1052⋅105 characters 'L' and 'R'.It is guaranteed that the sum of lengths of strings over all test cases does not exceed 2⋅1052⋅105 (∑|s|≤2⋅105∑|s|≤2⋅105).OutputFor each test case, print the answer — the minimum possible value of dd such that the frog can reach the cell n+1n+1 from the cell 00 if it jumps by no more than dd at once.ExampleInputCopy6 LRLRRLL L LLR RRRR LLLLLL R OutputCopy3 2 3 1 7 1 NoteThe picture describing the first test case of the example and one of the possible answers:In the second test case of the example; the frog can only jump directly from 00 to n+1n+1.In the third test case of the example, the frog can choose d=3d=3, jump to the cell 33 from the cell 00 and then to the cell 44 from the cell 33.In the fourth test case of the example, the frog can choose d=1d=1 and jump 55 times to the right.In the fifth test case of the example, the frog can only jump directly from 00 to n+1n+1.In the sixth test case of the example, the frog can choose d=1d=1 and jump 22 times to the right.
[ "binary search", "data structures", "dfs and similar", "greedy", "implementation" ]
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; 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.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.StringTokenizer; import java.util.function.Supplier; import java.util.stream.Collectors; public class cf { //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; public static int cnt; //-----------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; } public void close() { // TODO Auto-generated method stub } } static boolean pal(String s) { StringBuilder sb=new StringBuilder(); sb.append(s); sb.reverse(); String s1=sb.toString(); if(s1.contentEquals(s)) { return true; } else { return false; } } static boolean isPrime(long arr) { // Corner cases if (arr <= 1) return false; if (arr <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (arr % 2 == 0 || arr % 3 == 0) return false; for (int i = 5; i * i <= arr; i = i + 6) if (arr % i == 0 || arr % (i + 2) == 0) return false; return true; } public static int reverseBits(int n) { int rev = 0; // traversing bits of 'n' // from the right while (n > 0) { // bitwise left shift // 'rev' by 1 rev <<= 1; // if current bit is '1' if ((int)(n & 1) == 1) rev ^= 1; // bitwise right shift //'n' by 1 n >>= 1; } // required number return rev; } public static ArrayList<String> getSequence(String str) { // If 1 // string is empty if (str.length() == 0) { // Return an empty arraylist ArrayList<String> empty = new ArrayList<>(); empty.add(""); return empty; } // Take first character of str char ch = str.charAt(0); // Take sub-string starting from the // second character String subStr = str.substring(1); // Recursive call for all the sub-sequences // starting from the second character ArrayList<String> subSequences = getSequence(subStr); // Add first character from str in the beginning // of every character from the sub-sequences // and then store it into the resultant arraylist ArrayList<String> res = new ArrayList<>(); for (String val : subSequences) { res.add(val); res.add(ch + val); } return res; } static int fact(int n) { int fact=1; while(n>=1) { fact=fact*n; n--; } return fact; } static long __gcd(long a, long b) { if (a == 0 || b == 0) return 0; if (a == b) return a; if (a > b) return __gcd(a-b, b); return __gcd(a, b-a); } static boolean coprime(long a, long b) { if ( __gcd(a, b) == 1) return true; else return false; } static int xor(int n,int a,int b) { if(n>0) { xor(n-1,b,a^b); return a^b; } else { return a^b; } } static ArrayList<ArrayList<Integer>> printSubArrays(int[] arr, int start, int end,ArrayList<ArrayList<Integer>> x) { if (end == arr.length) { return x; } else if (start > end) { printSubArrays(arr, 0, end + 1,x); } else { ArrayList<Integer> x1=new ArrayList<Integer>(); for (int i = start; i < end; i++) { x1.add(arr[i]); } x1.add(arr[end]); x.add(x1); printSubArrays(arr, start + 1, end,x); } return x; } public static ArrayList<ArrayList<Integer>> printSubsequences(int[] arr, int index, ArrayList<Integer> path) { // Print the subsequence when reach // the leaf of recursion tree ArrayList<ArrayList<Integer>> x=new ArrayList<ArrayList<Integer>>(); if (index == arr.length) { // Condition to avoid printing // empty subsequence if (path.size() > 0) x.add(path); return x; } else { // Subsequence without including // the element at current index printSubsequences(arr, index + 1, path); path.add(arr[index]); x.add(path); // Subsequence including the element // at current index printSubsequences(arr, index + 1, path); x.add(path); // Backtrack to remove the recently // inserted element path.remove(path.size() - 1); x.add(path); } return x; } static int f(int h,int n) { return 3*h*h+h-2*n; } public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int t=sc.nextInt(); while(t-->0) { String s=sc.next(); int n=s.length(); ArrayList<Integer> x=new ArrayList<Integer>(); x.add(0); for(int i=0;i<n;i++) { if(s.charAt(i)=='R') { x.add(i+1); } } x.add(n+1); long ans=0; for(int i=0;i<x.size()-1;i++) { ans=Math.max(ans,x.get(i+1)-x.get(i)); } out.println(Math.min(ans, n+1)); } out.close(); } }
java
1313
A
A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules: every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes); each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk; all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?InputThe first line contains an integer tt (1≤t≤5001≤t≤500) — the number of test cases to solve.Each of the remaining tt lines contains integers aa, bb and cc (0≤a,b,c≤100≤a,b,c≤10) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.OutputFor each test case print a single integer — the maximum number of visitors Denis can feed.ExampleInputCopy71 2 10 0 09 1 72 2 32 3 23 2 24 4 4OutputCopy3045557NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors.
[ "brute force", "greedy", "implementation" ]
import java.util.*; import java.io.*; public class Practice { static boolean multipleTC = true; final static int mod = 1000000007; final static int mod2 = 998244353; final double E = 2.7182818284590452354; final double PI = 3.14159265358979323846; int MAX = 10000005; void pre() throws Exception { } // All the best void solve(int TC) throws Exception { int a = ni(), b = ni(), c = ni(); int aa[] = new int[] { a, b, c }; sort(aa); c = aa[0]; b = aa[1]; a = aa[2]; int count = 0; int arr[] = { 1, 2, 4, 3, 5, 6, 7 }; for (int mask : arr) { if ((mask & 1) != 0 && a == 0) { continue; } if ((mask & 2) != 0 && b == 0) { continue; } if ((mask & 4) != 0 && c == 0) { continue; } count++; if ((mask & 1) != 0) { a--; } if ((mask & 2) != 0) { b--; } if ((mask & 4) != 0) { c--; } } pn(count); } int[] readArr(int n) throws Exception { int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = ni(); } return arr; } void sort(int arr[], int left, int right) { ArrayList<Integer> list = new ArrayList<>(); for (int i = left; i <= right; i++) list.add(arr[i]); Collections.sort(list); for (int i = left; i <= right; i++) arr[i] = list.get(i - left); } void sort(int arr[]) { ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < arr.length; i++) list.add(arr[i]); Collections.sort(list); for (int i = 0; i < arr.length; i++) arr[i] = list.get(i); } public long max(long... arr) { long max = arr[0]; for (long itr : arr) max = Math.max(max, itr); return max; } public int max(int... arr) { int max = arr[0]; for (int itr : arr) max = Math.max(max, itr); return max; } public long min(long... arr) { long min = arr[0]; for (long itr : arr) min = Math.min(min, itr); return min; } public int min(int... arr) { int min = arr[0]; for (int itr : arr) min = Math.min(min, itr); return min; } public long sum(long... arr) { long sum = 0; for (long itr : arr) sum += itr; return sum; } public long sum(int... arr) { long sum = 0; for (int itr : arr) sum += itr; return sum; } String bin(long n) { return Long.toBinaryString(n); } String bin(int n) { return Integer.toBinaryString(n); } static int bitCount(int x) { return x == 0 ? 0 : (1 + bitCount(x & (x - 1))); } static void dbg(Object... o) { System.err.println(Arrays.deepToString(o)); } int bit(long n) { return (n == 0) ? 0 : (1 + bit(n & (n - 1))); } int abs(int a) { return (a < 0) ? -a : a; } long abs(long a) { return (a < 0) ? -a : a; } void p(Object o) { out.print(o); } void pn(Object o) { out.println(o); } void pni(Object o) { out.println(o); out.flush(); } String n() throws Exception { return in.next(); } String nln() throws Exception { return in.nextLine(); } int ni() throws Exception { return Integer.parseInt(in.next()); } long nl() throws Exception { return Long.parseLong(in.next()); } double nd() throws Exception { return Double.parseDouble(in.next()); } public static void main(String[] args) throws Exception { new Practice().run(); } FastReader in; PrintWriter out; void run() throws Exception { in = new FastReader(); out = new PrintWriter(System.out); int T = (multipleTC) ? ni() : 1; pre(); for (int t = 1; t <= T; t++) solve(t); out.flush(); out.close(); } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception { br = new BufferedReader(new FileReader(s)); } String next() throws Exception { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new Exception(e.toString()); } } return st.nextToken(); } String nextLine() throws Exception { String str = ""; try { str = br.readLine(); } catch (IOException e) { throw new Exception(e.toString()); } return str; } } }
java
1324
A
A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2×12×1 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00: You place one figure 2×12×1 (choose some ii from 11 to nn and replace aiai with ai+2ai+2); then, while all aiai are greater than zero, replace each aiai with ai−1ai−1. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤1001≤n≤100) — the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.ExampleInputCopy4 3 1 1 3 4 1 1 2 1 2 11 11 1 100 OutputCopyYES NO YES YES NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process.
[ "implementation", "number theory" ]
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(System.out); Scanner sc=new Scanner(System.in); // String testcases[]=br.readLine().split(" "); // int t=Integer.parseInt(testcases[0]); int t=sc.nextInt(); for(int i=0;i<t;i++) { int n=sc.nextInt(); int a[]=new int[n]; int max=0; for(int j=0;j<n;j++) { a[j]=sc.nextInt(); if(a[j]>=max) max=a[j]; } int f=0; for(int j=0;j<n;j++) { if((max-a[j])%2!=0) f=1; } System.out.println(f==0?"YES":"NO"); } } // static int __gcd(int a, int b) // { // // Everything divides 0 // if (a == 0 || b == 0) // return 0; // // base case // if (a == b) // return a; // // a is greater // if (a > b) // return __gcd(a-b, b); // return __gcd(a, b-a); // } // static boolean coprime(int a, int b) { // if(a==1||b==1) // return true; // if ( __gcd(a, b) == 1) // return true; // else // return false; // } // private static boolean checkSquare(long n) // { // if (Math.ceil((double)Math.sqrt(n)) == // Math.floor((double)Math.sqrt(n))) // return true; // else // return false; // } // private static long floorSqrt(long x) // { // if (x == 0 || x == 1) // return x; // long start = 1, end = x / 2, ans = 0; // while (start <= end) { // long mid = (start + end) / 2; // if (mid * mid == x) // return (int)mid; // if (mid * mid < x) { // start = mid + 1; // ans = mid; // } // else // end = mid - 1; // } // return (long)ans; // } }
java
1293
B
B. JOE is on TV!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 - Standby for ActionOur dear Cafe's owner; JOE Miller, will soon take part in a new game TV-show "1 vs. nn"!The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The show ends when only JOE remains (we assume that JOE never answers a question wrong!).For each question JOE answers, if there are ss (s>0s>0) opponents remaining and tt (0≤t≤s0≤t≤s) of them make a mistake on it, JOE receives tsts dollars, and consequently there will be s−ts−t opponents left for the next question.JOE wonders what is the maximum possible reward he can receive in the best possible scenario. Yet he has little time before show starts, so can you help him answering it instead?InputThe first and single line contains a single integer nn (1≤n≤1051≤n≤105), denoting the number of JOE's opponents in the show.OutputPrint a number denoting the maximum prize (in dollars) JOE could have.Your answer will be considered correct if it's absolute or relative error won't exceed 10−410−4. In other words, if your answer is aa and the jury answer is bb, then it must hold that |a−b|max(1,b)≤10−4|a−b|max(1,b)≤10−4.ExamplesInputCopy1 OutputCopy1.000000000000 InputCopy2 OutputCopy1.500000000000 NoteIn the second example; the best scenario would be: one contestant fails at the first question; the other fails at the next one. The total reward will be 12+11=1.512+11=1.5 dollars.
[ "combinatorics", "greedy", "math" ]
import java.io.*; import java.util.*; public class JoeOnTV { public static void main(String[] args) throws IOException { FS msc = new FS(); // ADD FILEINPUT TO INFPUT FILE (OR NOTHING FOR MSC) int s = msc.nextInt(); double answer = 0.0; for(int i = 1; i < s + 1; i++){ answer += 1.0/(double)i; } System.out.println(answer); } static class FS { BufferedReader br; StringTokenizer st = new StringTokenizer(""); FS() { br = new BufferedReader(new InputStreamReader(System.in)); } FS(String file) throws IOException { br = new BufferedReader(new FileReader(file)); } String next() { // SEPERATES BY SPACES while (!st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } }
java
1320
C
C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1≤n,m,p≤2⋅1051≤n,m,p≤2⋅105) — the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1≤ai≤1061≤ai≤106, 1≤cai≤1091≤cai≤109) — the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1≤bj≤1061≤bj≤106, 1≤cbj≤1091≤cbj≤109) — the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1≤xk,yk≤1061≤xk,yk≤106, 1≤zk≤1031≤zk≤103) — defense, attack and the number of coins of the monster kk.OutputPrint a single integer — the maximum profit of the grind.ExampleInputCopy2 3 3 2 3 4 7 2 4 3 2 5 11 1 2 4 2 1 6 3 4 6 OutputCopy1
[ "brute force", "data structures", "sortings" ]
import java.io.*; import java.util.*; public class battle_azathoth { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(in.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int p = Integer.parseInt(st.nextToken()); int[] ys = new int[(int)(1e6)+5]; Arrays.fill(ys, Integer.MIN_VALUE); int max = 0; for(int i = 0; i<n; i++) { st = new StringTokenizer(in.readLine()); int pos = Integer.parseInt(st.nextToken()); ys[pos] = Math.max(ys[pos], -Integer.parseInt(st.nextToken())); max = Math.max(max, pos); } segtree tree = new segtree(ys, 0, ys.length-1); int[][] xs = new int[m][2]; for(int i = 0; i<m; i++){ st = new StringTokenizer(in.readLine()); xs[i] = new int[]{Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken())}; } Arrays.sort(xs, (int[] a, int[] b) -> a[0] - b[0]); int[][] coords = new int[p][3]; for(int i = 0; i<p; i++){ st = new StringTokenizer(in.readLine()); coords[i][1] = Integer.parseInt(st.nextToken()); coords[i][0] = Integer.parseInt(st.nextToken()); coords[i][2] = Integer.parseInt(st.nextToken()); } Arrays.sort(coords, (int[] a, int[] b) -> a[0] - b[0]); int idx = 0; int ret = Integer.MIN_VALUE; for(int i = 0; i<m; i++){ while(idx < p && coords[idx][0] < xs[i][0]){ if(max > coords[idx][1]){ tree.update(coords[idx][1]+1, ys.length-1, coords[idx][2]); } idx++; } ret = Math.max(ret, tree.get(0, ys.length-1) - xs[i][1]); } System.out.println(ret); } static class segtree { public int none = Integer.MIN_VALUE; public int updnone = 0; public int gL; public int gR; public int mid; public segtree left; public segtree right; public int val; public int lazy = updnone; segtree(int[] nums, int l, int r) { gL = l; gR = r; mid = (l + r) / 2; if (l == r) { val = nums[l]; return; } left = new segtree(nums, l, mid); right = new segtree(nums, mid + 1, r); val = comb(left.val, right.val); } public int get(int l, int r) { if (l > gR || r < gL) { return none; } push(); if (gL == l && gR == r) { return val; } return comb( left.get(l, Math.min(r, mid)), right.get(Math.max(l, mid + 1), r) ); } public int update(int l, int r, int v) { push(); if (l > gR || r < gL) { return val; } if (gL == l && gR == r) { compose(this, v); push(); } else { val = comb( left.update(l, Math.min(r, mid), v), right.update(Math.max(l, mid + 1), r, v) ); } return val; } public int comb(int a, int b) { return Math.max(a, b); } public void push() { if (gL != gR) { compose(left, lazy); compose(right, lazy); } val += lazy; lazy = updnone; } public void compose(segtree t, long v) { t.lazy += v; } public String toString() { return gL + " " + gR + " " + val + " " + lazy; } } }
java
1285
D
D. Dr. Evil Underscorestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; as a friendship gift, Bakry gave Badawy nn integers a1,a2,…,ana1,a2,…,an and challenged him to choose an integer XX such that the value max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X) is minimum possible, where ⊕⊕ denotes the bitwise XOR operation.As always, Badawy is too lazy, so you decided to help him and find the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).InputThe first line contains integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤230−10≤ai≤230−1).OutputPrint one integer — the minimum possible value of max1≤i≤n(ai⊕X)max1≤i≤n(ai⊕X).ExamplesInputCopy3 1 2 3 OutputCopy2 InputCopy2 1 5 OutputCopy4 NoteIn the first sample; we can choose X=3X=3.In the second sample, we can choose X=5X=5.
[ "bitmasks", "brute force", "dfs and similar", "divide and conquer", "dp", "greedy", "strings", "trees" ]
// practice with kaiboy import java.io.*; import java.util.*; public class CF1285D extends PrintWriter { CF1285D() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1285D o = new CF1285D(); o.main(); o.flush(); } int[] aa; int solve(int l, int r, int h) { if (l == r || h == -1) return 0; int m = l; while (m < r && (aa[m] & 1 << h) == 0) m++; if (m == l || m == r) return solve(l, r, h - 1); return Math.min(solve(l, m, h - 1), solve(m, r, h - 1)) | 1 << h; } void main() { int n = sc.nextInt(); aa = new int[n]; for (int i = 0; i < n; i++) aa[i] = sc.nextInt(); aa = Arrays.stream(aa).boxed().sorted().mapToInt($->$).toArray(); println(solve(0, n, 29)); } }
java
13
B
B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold: Two segments have common endpoint (lets call these segments first and second); while the third segment connects two points on the different segments. The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees. The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4). InputThe first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.ExamplesInputCopy34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputCopyYESNOYES
[ "geometry", "implementation" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; public class AnotA { long x1,x2; long y1,y2; AnotA(String s){ StringTokenizer st = new StringTokenizer(s); this.x1 =Integer.parseInt(st.nextToken()); this.y1 =Integer.parseInt(st.nextToken()); this.x2 =Integer.parseInt(st.nextToken()); this.y2 =Integer.parseInt(st.nextToken()); } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); for(int i=0; i<n; i++) { AnotA a = new AnotA(br.readLine()); AnotA b = new AnotA(br.readLine()); AnotA c = new AnotA(br.readLine()); System.out.println(checkConstraints(a,b,c)||checkConstraints(b,c,a)||checkConstraints(c,a,b)?"YES":"NO"); } } private static boolean checkIntersection(long x, long y, AnotA a) { //check if the point is lying outside the segment if(x<Math.min(a.x1, a.x2)||x>Math.max(a.x1, a.x2)||y<Math.min(a.y1, a.y2)||y>Math.max(a.y1, a.y2)) return false; //check ratio between parts int xpart = (int) Math.abs(a.x1-a.x2); int ypart = (int) Math.abs(a.y1-a.y2); int xmin = (int) Math.min(Math.abs(a.x1-x), Math.abs(a.x2-x)); int ymin = (int) Math.min(Math.abs(a.y1-y), Math.abs(a.y2-y)); return xpart<=5*xmin&&ypart<=5*ymin&& (long) (x-a.x2)*(a.y1-a.y2)==(long)(y-a.y2)*(a.x1-a.x2); } public static boolean checkConstraints(AnotA a, AnotA b, AnotA c) { if(a.x1==b.x1&&a.y1==b.y1) { return getAngle(a.x2,a.y2,b.x2,b.y2,a.x1,a.y1)&&( checkIntersection(c.x1, c.y1,a)&&checkIntersection(c.x2, c.y2,b)|| checkIntersection(c.x2, c.y2,a)&&checkIntersection(c.x1, c.y1,b)); } if(a.x2==b.x1&&a.y2==b.y1) { return getAngle(a.x1, a.y1, b.x2, b.y2, a.x2, a.y2)&&( checkIntersection(c.x1, c.y1,a)&&checkIntersection(c.x2, c.y2,b)|| checkIntersection(c.x2, c.y2,a)&&checkIntersection(c.x1, c.y1,b)); } if(a.x1==b.x2&&a.y1==b.y2) { return getAngle(a.x2, a.y2, b.x1, b.y1, a.x1, a.y1)&&( checkIntersection(c.x1, c.y1,a)&&checkIntersection(c.x2, c.y2,b)|| checkIntersection(c.x2, c.y2,a)&&checkIntersection(c.x1, c.y1,b)); } if(a.x2==b.x2&&a.y2==b.y2) { return getAngle(a.x1, a.y1, b.x1, b.y1, a.x2, a.y2)&&( checkIntersection(c.x1, c.y1,a)&&checkIntersection(c.x2, c.y2,b)|| checkIntersection(c.x2, c.y2,a)&&checkIntersection(c.x1, c.y1,b)); } return false; } public static boolean getAngle(long x1, long y1, long x2, long y2, long x3, long y3) { boolean collinear =areCollinear( x1, y1, x2, y2, x3, y3); //check angle <= 90 long a13 = (long) (x1-x3) * (x1-x3) + (long) (y1-y3) *(y1-y3); long a23 = (long) (x2-x3) * (x2-x3) + (long) (y2-y3) *(y2-y3); long a12 = (long) (x1-x2) * (x1-x2) + (long) (y1-y2) *(y1-y2); return !collinear&&a13+a23>=a12; } private static boolean areCollinear(long x1, long y1, long x2, long y2, long x3, long y3) { long area = (long) (x1-x3)*(y2-y3) - (long) (x2-x3)*(y1-y3); return area==0?true:false; } public static long dotProduct(long x1, long y1, long x2, long y2) { return x1*x2+y1*y2; } }
java
1296
E1
E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2001≤n≤200) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9 abacbecfd OutputCopyYES 001010101 InputCopy8 aaabbcbb OutputCopyYES 01011011 InputCopy7 abcdedc OutputCopyNO InputCopy5 abcde OutputCopyYES 00000
[ "constructive algorithms", "dp", "graphs", "greedy", "sortings" ]
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); E1StringColoringEasyVersion solver = new E1StringColoringEasyVersion(); solver.solve(1, in, out); out.close(); } static class E1StringColoringEasyVersion { static int n; static char[] arr; static int[] ans; public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.nextInt(); arr = in.next().toCharArray(); ans = new int[n]; Arrays.fill(ans, -1); if (pos(n - 1)) { out.println("YES"); for (int i = 0; i < n; i++) out.print(ans[i]); } else { out.println("NO"); } } static boolean pos(int ind) { if (ind == -1) return true; if (ans[ind] == -1) { int last = -1; for (int i = 0; i < ind; i++) { if (ans[i] == -1) continue; if (arr[i] > arr[ind] && last == -1) last = ans[i]; else if (arr[i] > arr[ind]) { if (ans[i] != last) return false; } } if (last == -1) { ans[ind] = 0; for (int i = 0; i < ind; i++) { if (arr[i] > arr[ind]) ans[i] = 1; } } else { ans[ind] = 1 - last; for (int i = 0; i < ind; i++) { if (arr[i] > arr[ind]) ans[i] = last; } } return pos(ind - 1); } else { int c = 1 - ans[ind]; for (int i = 0; i < ind; i++) { if (ans[i] == -1) continue; if (arr[i] > arr[ind] && ans[i] != c) return false; } for (int i = 0; i < ind; i++) { if (arr[i] > arr[ind]) ans[i] = c; } return pos(ind - 1); } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void print(int i) { writer.print(i); } } static class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
java
1307
B
B. Cow and Friendtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play! More specifically; he wants to get from (0,0)(0,0) to (x,0)(x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance between the endpoints of a hop is one of its nn favorite numbers: a1,a2,…,ana1,a2,…,an. What is the minimum number of hops Rabbit needs to get from (0,0)(0,0) to (x,0)(x,0)? Rabbit may land on points with non-integer coordinates. It can be proved that Rabbit can always reach his destination.Recall that the Euclidean distance between points (xi,yi)(xi,yi) and (xj,yj)(xj,yj) is (xi−xj)2+(yi−yj)2−−−−−−−−−−−−−−−−−−√(xi−xj)2+(yi−yj)2.For example, if Rabbit has favorite numbers 11 and 33 he could hop from (0,0)(0,0) to (4,0)(4,0) in two hops as shown below. Note that there also exists other valid ways to hop to (4,0)(4,0) in 22 hops (e.g. (0,0)(0,0) →→ (2,−5–√)(2,−5) →→ (4,0)(4,0)). Here is a graphic for the first example. Both hops have distance 33, one of Rabbit's favorite numbers. In other words, each time Rabbit chooses some number aiai and hops with distance equal to aiai in any direction he wants. The same number can be used multiple times.InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. Next 2t2t lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and xx (1≤n≤1051≤n≤105, 1≤x≤1091≤x≤109)  — the number of favorite numbers and the distance Rabbit wants to travel, respectively.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — Rabbit's favorite numbers. It is guaranteed that the favorite numbers are distinct.It is guaranteed that the sum of nn over all the test cases will not exceed 105105.OutputFor each test case, print a single integer — the minimum number of hops needed.ExampleInputCopy42 41 33 123 4 51 552 1015 4OutputCopy2 3 1 2 NoteThe first test case of the sample is shown in the picture above. Rabbit can hop to (2,5–√)(2,5), then to (4,0)(4,0) for a total of two hops. Each hop has a distance of 33, which is one of his favorite numbers.In the second test case of the sample, one way for Rabbit to hop 33 times is: (0,0)(0,0) →→ (4,0)(4,0) →→ (8,0)(8,0) →→ (12,0)(12,0).In the third test case of the sample, Rabbit can hop from (0,0)(0,0) to (5,0)(5,0).In the fourth test case of the sample, Rabbit can hop: (0,0)(0,0) →→ (5,102–√)(5,102) →→ (10,0)(10,0).
[ "geometry", "greedy", "math" ]
import java.util.*; import java.io.*; public class Solution { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); StringTokenizer st; while (t-- > 0) { // int n = Integer.parseInt(br.readLine()); st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int x = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); int arr[] = new int[n]; HashMap<Integer, Integer> map = new HashMap<>(); int max = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { int e = Integer.parseInt(st.nextToken()); arr[i] = e; max = Math.max(max, e); map.put(e, -1); } map.put(0,-1); int res = 0; if(max >= x) res = map.containsKey(x)?1:2; else { int div = x / max; if(div != 1) { div = (div>1)?div-1:div; x-=(div*max); res+=div; } if(map.containsKey(x)) res++; else res+=2; } output.write(res + "\n"); // char arr[] = br.readLine().toCharArray(); // output.write(); // int n = Integer.parseInt(st.nextToken()); // HashMap<Character, Integer> map = new HashMap<Character, Integer>(); // if // output.write("YES\n"); // else // output.write("NO\n"); // long a = Long.parseLong(st.nextToken()); // long b = Long.parseLong(st.nextToken()); // if(flag == 1) // output.write("NO\n"); // else // output.write("YES\n" + x + " " + y + " " + z + "\n"); // output.write(n+ "\n"); } output.flush(); } }
java
1316
C
C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109),  — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109)  — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2)  — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2 1 1 2 2 1 OutputCopy1 InputCopy2 2 999999937 2 1 3 1 OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime.
[ "constructive algorithms", "math", "ternary search" ]
// Problem: C. Primitive Primes // Contest: Codeforces - CodeCraft-20 (Div. 2) // URL: https://codeforces.com/problemset/problem/1316/C // Memory Limit: 256 MB // Time Limit: 1500 ms // // Powered by CP Editor (https://cpeditor.org) import java.io.*; import java.math.MathContext; import java.math.RoundingMode; import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.util.Collections; import java.io.InputStreamReader; import static java.lang.Math.*; import static java.lang.System.*; public class Main { public static void main(String[] args) throws IOException { // try { // Scanner in = new Scanner(System.in) ; FastScanner in = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt() ; int m = in.nextInt() ; int p = in.nextInt() ; int a[] = in.readArray(n) ; int b[] = in.readArray(m) ; int n1=0 , n2=0 ; for(int i=0 ; i<n ; i++){ if(a[i]%p != 0){ n1 = i ; break ; } } for(int i=0 ; i<m ; i++){ if(b[i]%p != 0){ n2 = i ; break ; } } System.out.println(n1+n2) ; out.flush(); out.close(); // } catch (Exception e) { // return; // } } // solution END // template start : static long gcd(long a, long b) {return (b == 0) ? a : gcd(b, a % b);} static int gcd(int a, int b) {return (b == 0) ? a : gcd(b, a % b);} static void sort(int ar[]) { int n = ar.length; ArrayList<Integer> a = new ArrayList<>(); for (int i = 0; i < n; i++) a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++)ar[i] = a.get(i); } static void sort1(long ar[]) { int n = ar.length; ArrayList<Long> a = new ArrayList<>(); for (int i = 0; i < n; i++)a.add(ar[i]); Collections.sort(a); for (int i = 0; i < n; i++)ar[i] = a.get(i); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) {e.printStackTrace();} return st.nextToken(); } int nextInt() { return Integer.parseInt(next());} int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() {return Long.parseLong(next());} } } // template end
java
1312
D
D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4 OutputCopy6 InputCopy3 5 OutputCopy10 InputCopy42 1337 OutputCopy806066790 InputCopy100000 200000 OutputCopy707899035 NoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3].
[ "combinatorics", "math" ]
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); DCountTheArrays solver = new DCountTheArrays(); solver.solve(1, in, out); out.close(); } static class DCountTheArrays { int n; int m; int mod = 998244353; int N = (int) (2e5 + 5); public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.nextInt(); m = in.nextInt(); long[][] fif = enumFAndIf(N); long res = 0; long base = (n - 2) * c(m, n - 1, fif) % mod; for (int i = 2; i <= n - 1; i++) { res = (res + base * (c(n - 3, i - 2, fif))) % mod; } out.println(res); } long[][] enumFAndIf(int n) { long[] f = new long[n + 1]; long[] invf = new long[n + 1]; f[0] = 1; for (int i = 1; i <= n; i++) { f[i] = f[i - 1] * i % mod; } invf[n] = invl(f[n], mod); for (int i = n - 1; i >= 0; i--) { invf[i] = invf[i + 1] * (i + 1) % mod; } return new long[][]{f, invf}; } long invl(long a, long mod) { long b = mod; long p = 1, q = 0; while (b > 0) { long c = a / b; long d; d = a; a = b; b = d % b; d = p; p = q; q = d - c * q; } return p < 0 ? p + mod : p; } long c(int a, int b, long[][] fif) { if (b < 0 || b > a) { return 0; } return fif[0][a] * fif[1][b] % mod * fif[1][a - b] % mod; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(long i) { writer.println(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; 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 boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
java
1286
A
A. Garlandtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVadim loves decorating the Christmas tree; so he got a beautiful garland as a present. It consists of nn light bulbs in a single row. Each bulb has a number from 11 to nn (in arbitrary order), such that all the numbers are distinct. While Vadim was solving problems, his home Carp removed some light bulbs from the garland. Now Vadim wants to put them back on.Vadim wants to put all bulb back on the garland. Vadim defines complexity of a garland to be the number of pairs of adjacent bulbs with numbers with different parity (remainder of the division by 22). For example, the complexity of 1 4 2 3 5 is 22 and the complexity of 1 3 5 7 6 4 2 is 11.No one likes complexity, so Vadim wants to minimize the number of such pairs. Find the way to put all bulbs back on the garland, such that the complexity is as small as possible.InputThe first line contains a single integer nn (1≤n≤1001≤n≤100) — the number of light bulbs on the garland.The second line contains nn integers p1, p2, …, pnp1, p2, …, pn (0≤pi≤n0≤pi≤n) — the number on the ii-th bulb, or 00 if it was removed.OutputOutput a single number — the minimum complexity of the garland.ExamplesInputCopy5 0 5 0 2 3 OutputCopy2 InputCopy7 1 0 0 5 0 0 2 OutputCopy1 NoteIn the first example; one should place light bulbs as 1 5 4 2 3. In that case; the complexity would be equal to 2; because only (5,4)(5,4) and (2,3)(2,3) are the pairs of adjacent bulbs that have different parity.In the second case, one of the correct answers is 1 7 3 5 6 4 2.
[ "dp", "greedy", "sortings" ]
import java.util.*; public class _1286A_garland { static int solve(int[] nums) { int n = nums.length; Set<Integer> existing = new HashSet<>(); int ans = 0; existing.add(nums[0]); for (int i = 1; i < n; i++) { existing.add(nums[i]); if (nums[i - 1] != 0 && nums[i] != 0 && nums[i] % 2 != nums[i - 1] % 2) { ans++; } } // System.out.println("init ans: " + String.valueOf(ans)); int[] counts = new int[2]; for (int i = 1; i <= n; i++) { if (!existing.contains(i)) { counts[i % 2]++; } } // System.out.println(Arrays.toString(counts)); // type, count, odd/even List<int[]> spans = new ArrayList<>(); int pre = 0; for (int i = 0; i < n; ) { while (i < n && nums[i] != 0) { i++; pre = i; } while (i < n && nums[i] == 0) { i++; } if (pre == 0) { // left side: type = 1 spans.add(new int[]{1, i, i == n ? 0 : nums[i] % 2}); } else if (i == n) { // right side type = 1 if (i > pre) { spans.add(new int[]{1, i - pre, nums[pre - 1] % 2}); } } else if (nums[pre - 1] % 2 != nums[i] % 2) { // different type = 2 spans.add(new int[]{2, i - pre, 0}); } else { // same type = 0 spans.add(new int[]{0, i - pre, nums[pre - 1] % 2}); } } Collections.sort(spans, (int[] a, int[] b) -> { if (a[0] == b[0]) { return a[1] - b[1]; } return a[0] - b[0]; }); for (int i = 0; i < spans.size(); i++) { int[] span = spans.get(i); if (span[1] == 0) continue; int type = span[0]; if (span[1] > counts[span[2]] && type == 0) { // find type 1 first for (int j = i+1; j < spans.size(); j++) { if (spans.get(j)[0] == 1 && spans.get(j)[2] == span[2] && spans.get(j)[1] <= counts[span[2]]) { counts[span[2]] -= spans.get(j)[1]; spans.get(j)[1] = 0; } } } int toFill = Math.min(span[1], counts[span[2]]); span[1] -= toFill; counts[span[2]] -= toFill; if (span[1] > 0) { counts[(span[2] + 1) % 2] -= span[1]; if (type == 0) { ans += 2; } if (type == 1) { ans++; } } if (type == 2) { ans++; } } return ans; } public static void main(String[] args) { // int res = _1286A_garland.solve(new int[]{0, 5, 0, 2, 3}); // System.out.println(res); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] nums = new int[n]; for (int i = 0; i < n; i++) { nums[i] = sc.nextInt(); } if (n == 1) { System.out.println(0); } else { int res = _1286A_garland.solve(nums); System.out.println(res); } } }
java
1325
B
B. CopyCopyCopyCopyCopytime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEhab has an array aa of length nn. He has just enough free time to make a new array consisting of nn copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence?A sequence aa is a subsequence of an array bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements. The longest increasing subsequence of an array is the longest subsequence such that its elements are ordered in strictly increasing order.InputThe first line contains an integer tt — the number of test cases you need to solve. The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1051≤n≤105) — the number of elements in the array aa.The second line contains nn space-separated integers a1a1, a2a2, ……, anan (1≤ai≤1091≤ai≤109) — the elements of the array aa.The sum of nn across the test cases doesn't exceed 105105.OutputFor each testcase, output the length of the longest increasing subsequence of aa if you concatenate it to itself nn times.ExampleInputCopy2 3 3 2 1 6 3 1 4 1 5 9 OutputCopy3 5 NoteIn the first sample; the new array is [3,2,1,3,2,1,3,2,1][3,2,1,3,2,1,3,2,1]. The longest increasing subsequence is marked in bold.In the second sample, the longest increasing subsequence will be [1,3,4,5,9][1,3,4,5,9].
[ "greedy", "implementation" ]
import java.util.Scanner; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-- >= 1){ int n = sc.nextInt(); long a[] = new long[n]; Set<Long> distinctElements = new HashSet<>(); for(int i = 0; i < n; i++){ a[i] = sc.nextInt(); distinctElements.add(a[i]); } System.out.println(distinctElements.size()); } } }
java