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
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" ]
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.InputMismatchException; import java.util.Iterator; import java.util.Set; public class Main { private static final String NO = "No"; private static final String YES = "Yes"; InputStream is; PrintWriter out; String INPUT = ""; private static final long MOD = 998244353; static int MAXN = 10; void solve() { int T = 1;//ni(); for (int i = 0; i < T; i++) solve(i); } void solve(int nth) { int n = ni(); int m = ni(); Set<String> all = new HashSet<String>(); String s[] = new String[n]; for (int i = 0; i < n; i++) { s[i] = ns(); all.add(s[i]); } long ans = 0; for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) { char a[] = new char[m]; for (int k = 0; k < m; k++) if (s[i].charAt(k) == s[j].charAt(k)) a[k] = s[i].charAt(k); else a[k] = (char) ('S' + 'E' + 'T' - s[i].charAt(k) - s[j].charAt(k)); if (all.contains(new String(a))) ans++; } out.println(ans/3); } // a^b long power(long a, long b) { long x = 1, y = a; while (b > 0) { if (b % 2 != 0) { x = (x * y) % MOD; } y = (y * y) % MOD; b /= 2; } return x % MOD; } private long gcd(long a, long b) { while (a != 0) { long tmp = b % a; b = a; a = tmp; } return b; } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new Main().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private char[] nc(int n) { char[] ret = new char[n]; for (int i = 0; i < n; i++) ret[i] = nc(); return ret; } 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) { if (!(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 Integer[] na2(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int[][] na(int n, int m) { int[][] a = new int[n][]; for (int i = 0; i < n; i++) a[i] = na(m); 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[] nl2(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nl(); return a; } private long[] nl(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); return a; } private long[][] nl(int n, int m) { long[][] a = new long[n][]; for (int i = 0; i < n; i++) a[i] = nl(m); return a; } 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 IterablePermutation implements Iterable<int[]>, Iterator<int[]> { int[] a; boolean first = true; public IterablePermutation(int n) { assert n >= 1; a = new int[n]; for (int i = 0; i < n; i++) a[i] = i; } public IterablePermutation(int... a) { this.a = Arrays.copyOf(a, a.length); } @Override public boolean hasNext() { if (first) return true; int n = a.length; int i; for (i = n - 2; i >= 0 && a[i] >= a[i + 1]; i--) ; return i != -1; } @Override public int[] next() { if (first) { first = false; return a; } int n = a.length; int i; for (i = n - 2; i >= 0 && a[i] >= a[i + 1]; i--) ; assert i != -1; int j; for (j = i + 1; j < n && a[i] < a[j]; j++) ; int d = a[i]; a[i] = a[j - 1]; a[j - 1] = d; for (int p = i + 1, q = n - 1; p < q; p++, q--) { d = a[p]; a[p] = a[q]; a[q] = d; } return a; } @Override public Iterator<int[]> iterator() { return this; } } private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); } }
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" ]
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(); int a[] = sc.readIntArray(n); HashMap<Long, List<int[]>> map = new HashMap<>(); for (int i = 0; i < n; i++) { long sum = 0; for (int j = i; j < n; j++) { sum += (long) a[j]; map.putIfAbsent(sum, new ArrayList<>()); map.get(sum).add(new int[] { i + 1, j + 1 }); } } List<int[]> ans = new ArrayList<>(); for (long key : map.keySet()) { List<int[]> al = new ArrayList<>(); for (int i = map.get(key).size() - 1; i >= 0; i--) { if (al.isEmpty() || al.get(al.size() - 1)[0] > map.get(key).get(i)[1]) { al.add(map.get(key).get(i)); } } if (al.size() > ans.size()) { ans = al; } } System.out.println(ans.size()); for (int x[] : ans) System.out.println(x[0] + " " + x[1]); } 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
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" ]
import java.io.*; import java.lang.*; import java.util.*; public class Main { public static int mod = (int) 1e9 + 7; // **** -----> Disjoint Set Union(DSU) Start ********** public static int findPar(int node, int[] parent) { if (parent[node] == node) return node; return parent[node] = findPar(parent[node], parent); } public static boolean union(int u, int v, int[] rank, int[] parent) { u = findPar(u, parent); v = findPar(v, parent); if(u == v) return false; if (rank[u] < rank[v]) parent[u] = v; else if (rank[u] > rank[v]) parent[v] = u; else { parent[u] = v; rank[v]++; } return true; } // **** DSU Ends *********** //Pair with int int public static class Pair{ public int a; public int b; Pair(int a , int b){ this.a = a; this.b = b; } @Override public String toString(){ return a + " -> " + b; } } public static String toBinary(int decimal) {StringBuilder sb = new StringBuilder();while (decimal > 0) {sb.append(decimal % 2);decimal = decimal / 2;}return sb.reverse().toString();} public static boolean isPalindrome(String s) {int i = 0, j = s.length() - 1;while (i < j) {if (s.charAt(i) != s.charAt(j))return false;i++;j--;}return true;} public static boolean isPalindrome(int[] arr) {int i = 0, j = arr.length - 1;while (i < j) {if (arr[i] != arr[j])return false;}return true;} public static int pow(int x, int y) {int res = 1;x = x % mod;if (x == 0)return 0;while (y > 0) {if ((y & 1) != 0)res = (res * x) % mod;y = y >> 1;x = (x * x) % mod;}return res;} public static int gcd(int a, int b) {if (b == 0)return a;return gcd(b, a % b);} public static long gcd(long a, long b) {if (b == 0)return a;return gcd(b, a % b);} public static void sort(long[] a) {Random rnd = new Random();for (int i = 0; i < a.length; i++) {int pos = i + rnd.nextInt(a.length - i);long temp = a[i];a[i] = a[pos];a[pos] = temp;}Arrays.sort(a);} public static void reverse(int a[]) {int i, k, t, n = a.length;for (i = 0; i < n / 2; i++) {t = a[i];a[i] = a[n - i - 1];a[n - i - 1] = t;}} public static void sort(int[] a) {Random rnd = new Random();for (int i = 0; i < a.length; i++) {int pos = i + rnd.nextInt(a.length - i);int temp = a[i];a[i] = a[pos];a[pos] = temp;}Arrays.sort(a);} public static void revSort(int[] a) {Random rnd = new Random();for (int i = 0; i < a.length; i++) {int pos = i + rnd.nextInt(a.length - i);int temp = a[i];a[i] = a[pos];a[pos] = temp;}Arrays.sort(a);reverse(a);} public static long LCM(long a, long b) {if (a > b) {long t = a;a = b;b = t;}a /= gcd(a, b);return (a * b);} public static int findMax(int[] a, int left, int right) {int res = left;int max = a[left];for (int i = left + 1; i <= right; i++) {if (a[i] > max) {max = a[i];res = i;}}return res;} public static long findClosest(long arr[], long target) {int n = arr.length;if (target <= arr[0])return arr[0];if (target >= arr[n - 1])return arr[n - 1];int i = 0, j = n, mid = 0;while (i < j) {mid = (i + j) / 2;if (arr[mid] == target)return arr[mid];if (target < arr[mid]) {if (mid > 0 && target > arr[mid - 1])return getClosest(arr[mid - 1], arr[mid], target);j = mid;} else {if (mid < n - 1 && target < arr[mid + 1])return getClosest(arr[mid], arr[mid + 1], target);i = mid + 1;}}return arr[mid];} public static long getClosest(long val1, long val2, long target) {if (target - val1 >= val2 - target)return val2;else return val1;} public static int findClosest(int arr[], int target) { int n = arr.length; if (target <= arr[0]) return arr[0]; if (target >= arr[n - 1]) return arr[n - 1]; int i = 0, j = n, mid = 0; while (i < j) { mid = (i + j) / 2; if (arr[mid] == target) return arr[mid];if (target < arr[mid]) {if (mid > 0 && target > arr[mid - 1])return getClosest(arr[mid - 1], arr[mid], target);j = mid;} else {if (mid < n - 1 && target < arr[mid + 1])return getClosest(arr[mid], arr[mid + 1], target);i = mid + 1;}}return arr[mid];} public static int getClosest(int val1, int val2, int target) {if (target - val1 >= val2 - target)return val2;else return val1;} public static String reverse(String str) {String nstr = "";char ch;for (int i = 0; i < str.length(); i++) {ch = str.charAt(i);nstr = ch + nstr;}return nstr;} public static boolean isPrime(int n){if (n <= 1)return false;if (n <= 3)return true;if (n % 2 == 0 || n % 3 == 0)return false;for (int i = 5; i * i <= n; i = i + 6)if (n % i == 0 || n % (i + 2) == 0)return false;return true;} public static int xorSum(int arr[], int n){int bits = 0;for (int i = 0; i < n; ++i)bits |= arr[i];int ans = bits * (int)Math.pow(2, n-1);return ans;} public static ArrayList<Integer> primeFactors(int n) { ArrayList<Integer> res = new ArrayList<>();while (n%2 == 0) { res.add(2); n = n/2; } for (int i = 3; i <= Math.sqrt(n); i = i+2) { while (n%i == 0) { res.add(i); n = n/i; } } if (n > 2) res.add(n);return res;} public static ArrayList<Long> primeFactors(long n) { ArrayList<Long> res = new ArrayList<>();while (n%2 == 0) { res.add(2L); n = n/2; } for (long i = 3; i <= Math.sqrt(n); i = i+2) { while (n%i == 0) { res.add(i); n = n/i; } } if (n > 2) res.add(n);return res;} static int lower_bound(int array[], int low, int high, int key){ int mid; while (low < high) { mid = low + (high - low) / 2; if (key <= array[mid]) high = mid; else low = mid + 1; } if (low < array.length && array[low] < key) low++; return low; } /********************************* Start Here ***********************************/ // int mod = 1000000007; static HashSet<Integer> set; public static void main(String[] args) throws java.lang.Exception { if (System.getProperty("ONLINE_JUDGE") == null) { PrintStream ps = new PrintStream(new File("output.txt")); System.setOut(ps); } FastScanner sc = new FastScanner("input.txt"); StringBuilder result = new StringBuilder(); set = new HashSet<>(); // sieveOfEratosthenes(1000000); int T = sc.nextInt(); // int T = 1; while (T-- > 0) { int n=sc.nextInt(); long pre=sc.nextLong(); long min= Integer.MAX_VALUE/2; long max=Integer.MIN_VALUE/2; long knownGap=0; for(int i=1;i<n;i++){ long cur=sc.nextLong(); if(cur==-1&&pre!=-1){ min=Math.min(min,pre); max=Math.max(max,pre); pre=cur; } else if(cur==-1&&pre==-1){ continue; } else if(cur!=-1&&pre==-1){ min=Math.min(min,cur); max=Math.max(max,cur); pre=cur; } knownGap=Math.max(knownGap,Math.abs(cur-pre)); pre=cur; } long num=(max-min)/2+min; long res=Math.max(knownGap,Math.max(num-min,max-num)); result.append(res+" "+num+"\n"); } System.out.println(result); System.out.close(); } public static boolean solve(int a[],int ans,int index){ int sum = 0; int l = 0; int r = 0; while(l<=r){ if(sum==ans&&r-l>=2)return true; if(sum>ans){ sum-=a[l++]; }else{ if(r==a.length)break; sum+=a[r++]; } } return false; } static void sieveOfEratosthenes(int n){ boolean prime[] = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++){ if (prime[p] == true){ for (int i = p * p; i <= n; i += p) prime[i] = false; } } for (int i = 2; i <= n; i++){ if (prime[i] == true) set.add(i); } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { br = new BufferedReader(new InputStreamReader(System.in)); } } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } public String nextLine() { if (st == null || !st.hasMoreTokens()) { try { return br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken("\n"); } public String[] readStringArray(int n) { String[] a = new String[n]; for (int i = 0; i < n; i++) { a[i] = next(); } return a; } int nextInt() { return Integer.parseInt(nextToken()); } String next() { return nextToken(); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] read2dArray(int n, int m) { int[][] a = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = nextInt(); } } return a; } long[][] read2dlongArray(int n, int m) { long[][] a = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = nextLong(); } } return a; } } }
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" ]
/* Author : Akshat Jindal from NIT Jalandhar , Punjab , India JAI MATA DI */ import java.util.*; import javax.swing.text.Segment; import java.io.*; import java.math.*; import java.sql.Array; public class Main { static class FR{ BufferedReader br; StringTokenizer st; public FR() { 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 a , long b ,long mod) { return ((a%mod)*(b%mod))%mod; } 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 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{ long[] fac; long[] inf; public Combinations(long N , long mod) { fac = new long[(int)N+1]; inf = new long[(int)N+1]; fac[0] = 1; for(int i =1 ; i<=N ; i++) fac[i] = (fac[i-1]*i)%mod; long[] naturalNumInverse = new long[(int)N+1]; naturalNumInverse[0] = naturalNumInverse[1] = 1; for (int i = 2; i <= N; i++) naturalNumInverse[i] = naturalNumInverse[(int)(mod % i)] * (mod - mod / i) % mod; inf[0] = inf[1] = 1; for (int i = 2; i <= N; i++) inf[i] = (naturalNumInverse[i] * inf[i - 1]) % mod; } long ncr(long N, long R, long mod) { if(R<0 || R>N ) return 0; long ans = ((fac[(int)N] * inf[(int)R]) % mod * inf[(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[] 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.min(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.min(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 FR sc = new FR(); static StringBuilder sb = new StringBuilder(); public static void main(String args[]) throws IOException { int tc = 1; // tc = sc.nextInt(); while(tc-->0) { TEST_CASE(); } System.out.println(sb); } static void TEST_CASE() { int n = sc.nextInt() , m = sc.nextInt(); long p = sc.nextLong(); long[] a = new long[n] , b = new long[m]; for(int i =0 ; i<n ; i++) a[i] = sc.nextLong(); for(int i =0 ; i<m; i++) b[i] = sc.nextLong(); int a1 = -1 , a2 = -1; for(int i = 0 ; i<n ; i++) { if(a[i]%p != 0) a1 = i; } for(int i =0 ; i<m ; i++) { if(b[i]%p != 0) a2 = i; } sb.append(a1+a2+"\n"); } } /*******************************************************************************************************************************************************/ /*** 3 4 a0 a1 a2 b0 b1 b2 b3 c0 = (a0*b0) | c1 = (a0*b1 + a1*b0) | c2 = (a0*b2 + a1*b1 + a2*b0) | c3 = (a0*b3 + a1*b2 + a2*b1 ) | c4 = (a1*b3 + a2*b2) | c5 = (a2*b3) */
java
1141
E
E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6 -100 -200 -300 125 77 -4 OutputCopy9 InputCopy1000000000000 5 -1 0 0 0 0 OutputCopy4999999999996 InputCopy10 4 -3 -6 5 4 OutputCopy-1
[ "math" ]
import java.util.*; public class Solution { public static void main(String[] args){ Scanner sc=new Scanner(System.in); long h=sc.nextLong(); int n=sc.nextInt(); long[] ar=new long[n]; long base=h; int an=0, pr=0; boolean ok=false; for(int i=0;i<n;i++){ ar[i]=sc.nextLong(); base+=ar[i]; an++; if(base<=0 && ok==false){ok=true;pr=an;} } if(base>=h){ if(ok)System.out.println(pr); else System.out.println("-1"); } else{ long b=h, max=0, ans=0, min=0; ok=true; long overall=0; for(int i=0;i<n;i++){ ans++; b+=ar[i]; min+=ar[i]; overall+=ar[i]; if(Math.abs(min)>max && min<0){ max=Math.abs(min); } if(b<=0 && ok){ok=false;break;} } if(!ok)System.out.println(ans); else{ long rem=b-max; overall=Math.abs(overall); if(rem<=0){ for(int i=0;i<n;i++){ if(b<=0)break; b+=ar[i]; ans++;} } else{ long div=rem/overall; rem-=div*overall; div=div*(long)n; ans+=div; rem+=max; while(rem>0){ for(int i=0;i<n;i++){ if(rem<=0)break; rem+=ar[i]; ans++; } } } System.out.println(ans); } } } }
java
1313
C1
C1. Skyscrapers (easy version)time limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is an easier version of the problem. In this version n≤1000n≤1000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤10001≤n≤1000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.
[ "brute force", "data structures", "dp", "greedy" ]
import java.io.*; import java.text.DecimalFormat; import java.util.*; public class Main { static class Pair { int l; long w; public Pair(int l,long w) { this.l=l; this.w=w; } public String toString() { return l +" "+w; } } static final int INF = 1<<30; static final long INFL = 1L<<60; static final long NINF =INFL*-1; static final long mod = (long) 1e9 + 7; static final long mod2=998244353; static DecimalFormat df = new DecimalFormat("0.00000000000000"); public static final double PI = 3.141592653589793d ,eps = 1e-9; public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { public static void solve(int testNumber, InputReader in, OutputWriter out) { int t=1; while(t-->0) { int n=in.readInt(); long[] arr=new long[n]; long mx=0,same=1; for(int i=0;i<n;i++) { arr[i]=in.nextLong(); mx=Math.max(mx,arr[i]); } long sum=0; long[] fin=arr; for(int i=0;i<n;++i) { long prev=Long.MAX_VALUE; int ind=i; long tp=0; long b[]=new long[n]; for(int j=ind;j>=0;--j) { if(arr[j]>prev) { tp+=prev; b[j]=prev; } else { tp+=arr[j]; b[j]=arr[j]; prev=arr[j]; } } prev=Long.MAX_VALUE; for(int j=ind+1;j<n;++j) { if(arr[j]>prev) { tp+=prev; b[j]=prev; } else { tp+=arr[j]; b[j]=arr[j]; prev=arr[j]; } } if(tp>sum) { sum=tp; fin=b; } } for(int i=0;i<n;i++) { out.print(fin[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 int[] nextIntArray(int arraySize) { int[] array = new int[arraySize]; for (int i = 0; i < arraySize; i++) { array[i] = readInt(); } return array; } private int skip() { int b; while((b = read()) != -1 && isSpaceChar(b)); return b; } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = read(); } 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 = read(); } return n == p ? buf : Arrays.copyOf(buf, p); } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isNewLine(int c) { return c == '\n'; } public String nextLine() { int c = read(); StringBuilder result = new StringBuilder(); do { result.appendCodePoint(c); c = read(); } while (!isNewLine(c)); return result.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sign = 1; if (c == '-') { sign = -1; c = read(); } long result = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } result *= 10; result += c & 15; c = read(); } while (!isSpaceChar(c)); return result * sign; } public long[] nextLongArray(int arraySize) { long array[] = new long[arraySize]; for (int i = 0; i < arraySize; i++) { array[i] = nextLong(); } return array; } public double nextDouble() { double ret = 0, div = 1; byte c = (byte) read(); while (c <= ' ') { c = (byte) read(); } boolean neg = (c == '-'); if (neg) { c = (byte) read(); } do { ret = ret * 10 + c - '0'; } while ((c = (byte) read()) >= '0' && c <= '9'); if (c == '.') { while ((c = (byte) read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) { return -ret; } return ret; } public 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 CP { static boolean isPrime(long 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; (long) i * i <= n; i += 6) { if (n % i == 0 || n % (i + 2) == 0) return false; } return true; } public static int log2(int N) { int result = (int) (Math.log(N) / Math.log(2)); return result; } public static long pow(long a, long n, long mod) { // a %= mod; long ret = 1; int x = 63 - Long.numberOfLeadingZeros(n); for (; x >= 0; x--) { ret = ret * ret % mod; if (n << 63 - x < 0) ret = ret * a % mod; } return ret; } public static boolean isComposite(long n) { if (n < 2) return true; if (n == 2 || n == 3) return false; if (n % 2 == 0 || n % 3 == 0) return true; for (long i = 6L; i * i <= n; i += 6) if (n % (i - 1) == 0 || n % (i + 1) == 0) return true; return false; } static int ifnotPrime(int[] prime, int x) { return (prime[x / 64] & (1 << ((x >> 1) & 31))); } static int log2(long n) { return (int) (Math.log10(n) / Math.log10(2)); } static void makeComposite(int[] prime, int x) { prime[x / 64] |= (1 << ((x >> 1) & 31)); } public static int[] sieveEratosthenes(int n) { if (n <= 32) { int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31}; for (int i = 0; i < primes.length; i++) { if (n < primes[i]) { return Arrays.copyOf(primes, i); } } return primes; } int u = n + 32; double lu = Math.log(u); int[] ret = new int[(int) (u / lu + u / lu / lu * 1.5)]; ret[0] = 2; int pos = 1; int[] isnp = new int[(n + 1) / 32 / 2 + 1]; int sup = (n + 1) / 32 / 2 + 1; int[] tprimes = {3, 5, 7, 11, 13, 17, 19, 23, 29, 31}; for (int tp : tprimes) { ret[pos++] = tp; int[] ptn = new int[tp]; for (int i = (tp - 3) / 2; i < tp << 5; i += tp) ptn[i >> 5] |= 1 << (i & 31); for (int j = 0; j < sup; j += tp) { for (int i = 0; i < tp && i + j < sup; i++) { isnp[j + i] |= ptn[i]; } } } // 3,5,7 // 2x+3=n int[] magic = {0, 1, 23, 2, 29, 24, 19, 3, 30, 27, 25, 11, 20, 8, 4, 13, 31, 22, 28, 18, 26, 10, 7, 12, 21, 17, 9, 6, 16, 5, 15, 14}; int h = n / 2; for (int i = 0; i < sup; i++) { for (int j = ~isnp[i]; j != 0; j &= j - 1) { int pp = i << 5 | magic[(j & -j) * 0x076be629 >>> 27]; int p = 2 * pp + 3; if (p > n) break; ret[pos++] = p; if ((long) p * p > n) continue; for (int q = (p * p - 3) / 2; q <= h; q += p) isnp[q >> 5] |= 1 << q; } } return Arrays.copyOf(ret, pos); } static int digit(long s){int brute = 0;while(s>0){s/=10;brute++;}return brute;} public static int[] primefacs(int n, int[] primes) { int[] ret = new int[15]; int rp = 0; for (int p : primes) { if (p * p > n) break; int i; for (i = 0; n % p == 0; n /= p, i++) ; if (i > 0) ret[rp++] = p; } if (n != 1) ret[rp++] = n; return Arrays.copyOf(ret, rp); } static ArrayList<Integer> bitWiseSieve(int n) { ArrayList<Integer> al = new ArrayList<>(); int prime[] = new int[n / 64 + 1]; for (int i = 3; i * i <= n; i += 2) { if (ifnotPrime(prime, i) == 0) for (int j = i * i, k = i << 1; j < n; j += k) makeComposite(prime, j); } al.add(2); for (int i = 3; i <= n; i += 2) if (ifnotPrime(prime, i) == 0) al.add(i); return al; } public static long[] sort(long arr[]) { List<Long> list = new ArrayList<>(); for (long n : arr) { list.add(n); } Collections.sort(list); for (int i = 0; i < arr.length; i++) { arr[i] = list.get(i); } return arr; } public static long[] revsort(long[] arr) { List<Long> list = new ArrayList<>(); for (long n : arr) { list.add(n); } Collections.sort(list, Collections.reverseOrder()); for (int i = 0; i < arr.length; i++) { arr[i] = list.get(i); } return arr; } public static int[] revsort(int[] arr) { List<Integer> list = new ArrayList<>(); for (int n : arr) { list.add(n); } Collections.sort(list, Collections.reverseOrder()); for (int i = 0; i < arr.length; i++) { arr[i] = list.get(i); } return arr; } static ArrayList<Integer> sieve(long size) { ArrayList<Integer> pr = new ArrayList<Integer>(); boolean prime[] = new boolean[(int) size]; for (int i = 2; i < prime.length; i++) prime[i] = true; for (int i = 2; i * i < prime.length; i++) { if (prime[i]) { for (int j = i * i; j < prime.length; j += i) { prime[j] = false; } } } for (int i = 2; i < prime.length; i++) if (prime[i]) pr.add(i); return pr; } static ArrayList<Integer> segmented_sieve(int l, int r, ArrayList<Integer> primes) { ArrayList<Integer> al = new ArrayList<>(); if (l == 1) ++l; int max = r - l + 1; int arr[] = new int[max]; for (int p : primes) { if (p * p <= r) { int i = (l / p) * p; if (i < l) i += p; for (; i <= r; i += p) { if (i != p) { arr[i - l] = 1; } } } } for (int i = 0; i < max; ++i) { if (arr[i] == 0) { al.add(l + i); } } return al; } static boolean isfPrime(long n, int iteration) { if (n == 0 || n == 1) return false; if (n == 2) return true; if (n % 2 == 0) return false; Random rand = new Random(); for (int i = 0; i < iteration; i++) { long r = Math.abs(rand.nextLong()); long a = r % (n - 1) + 1; if (modPow(a, n - 1, n) != 1) return false; } return true; } static long modPow(long a, long b, long c) { long res = 1; for (int i = 0; i < b; i++) { res *= a; res %= c; } return res % c; } static public int lengthOfLIS(int arr[]) { ArrayList<Integer> dp = new ArrayList<Integer>(); int n = arr.length; dp.add(arr[0]); int idx = 0; for (int i = 1; i < n; i++) { if (arr[i] >= dp.get(dp.size() - 1)) { dp.add(arr[i]); } else { idx = ub(dp, arr[i]); dp.set(idx, arr[i]); } } return dp.size(); } private static long binPower(long a, long l, long mod) { long res = 0; while (l > 0) { if ((l & 1) == 1) { res = mulmod(res, a, mod); l >>= 1; } a = mulmod(a, a, mod); } return res; } private static long mulmod(long a, long b, long c) { long x = 0, y = a % c; while (b > 0) { if (b % 2 == 1) { x = (x + y) % c; } y = (y * 2L) % c; b /= 2; } return x % c; } static long binary_Expo(long a, long b) { long res = 1; while (b != 0) { if ((b & 1) == 1) { res *= a; --b; } a *= a; b /= 2; } return res; } static void swap(int a, int b) { int tp = b; b = a; a = tp; } static long Modular_Expo(long a, long b,long mod) { long res = 1; while (b != 0) { if ((b & 1) == 1) { res = (res * a) % mod; --b; } a = (a * a) % mod; b /= 2; } return res % mod; } static int i_gcd(int a, int b) { while (true) { if (b == 0) return a; int c = a; a = b; b = c % b; } } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long ceil_div(long a, long b) { return (a + b - 1) / b; } static int getIthBitFromInt(int bits, int i) { return (bits >> (i - 1)) & 1; } private static TreeMap<Long, Long> primeFactorize(long n) { TreeMap<Long, Long> pf = new TreeMap<>(Collections.reverseOrder()); long cnt = 0; long total = 1; for (long i = 2; (long) i * i <= n; ++i) { if (n % i == 0) { cnt = 0; while (n % i == 0) { ++cnt; n /= i; } pf.put(cnt, i); //total*=(cnt+1); } } if (n > 1) { pf.put(1L, n); //total*=2; } return pf; } static int upper_Bound(int a[], long x) { long l = 0, h = a.length-1, mid = 0, ans = -1; while (l <= h) { mid = (l + h) /2; if (a[(int) mid] > x) { ans = mid; h = mid - 1; } else { l = mid + 1; } } return (int)ans; } static long upper_Bound(long a[], long x) { long l = 0, h = 0, mid = 0, ans = -1; while (l <= h) { mid = (l + h) >> 1; if (a[(int) mid] > x) { ans = mid; h = mid - 1; } else { l = mid + 1; } } return ans; } static int lower_Bound(ArrayList<Long> a, long x) { int l = 0, r = a.size() - 1, ans = -1, mid = 0; while (l <= r) { mid = (l + r) >> 1; if (a.get(mid) <= x) { ans = mid; l = mid + 1; } else { r = mid - 1; } } return ans; } static long lower_Bound(int a[], long x) { long l = 0, h = a.length-1, mid = 0, ans = -1; while (l <= h) { mid = (l + h)/2; if (a[(int) mid]<=x) { ans = mid; l=mid+1; } else { h=mid-1; } } return ans; } static long lower_Bound(long a[], long x) { long l = 0, h = 0, mid = 0, ans = -1; while (l <= h) { mid = (l + h) >> 1; if (a[(int) mid]<=x) { ans = mid; l=mid+1; } else { h=mid-1; } } return ans; } static int upperBound(int a[], int x) {// x is the key or target value long l = 0, h = 0, mid = 0, ans = -1; while (l <= h) { mid = (l + h) >> 1; if (a[(int) mid] > x) { ans = mid; h = mid - 1; } else { l = mid + 1; } } return (int) ans; } static int bs(long a[], long t) { int ans = -1; int i = 0, j = a.length - 1; while (i <= j) { int mid = i + (j - i) / 2; if (a[mid] >=t) { ans = mid; j = mid - 1; } else { i = mid + 1; } } return ans; } static public int ub(ArrayList<Integer> dp, long num) { int l = 0, r = dp.size() - 1, ans = -1, mid = 0; while (l <= r) { mid = l + ((r - l) >> 1); if (dp.get(mid) >= num) { ans = mid; r = mid - 1; } else { l = mid + 1; } } return ans; } static boolean isSquarefactor(int x, int factor, int target) { int s = (int) Math.round(Math.sqrt(x)); return factor * s * s == target; } static boolean isSquare(int x) { int s = (int) Math.round(Math.sqrt(x)); return x * x == s; } static int bs(ArrayList<Integer> al, int val) { int l = 0, h = al.size() - 1, mid = 0, ans = -1; while (l <= h) { mid = (l + h) >> 1; if (al.get(mid) == val) { return mid; } else if (al.get(mid) > val) { h = mid - 1; } else { l = mid + 1; } } return ans; } static void sort(int a[]) // heap sort { PriorityQueue<Integer> q = new PriorityQueue<>(); for (int i = 0; i < a.length; i++) q.add(a[i]); for (int i = 0; i < a.length; i++) a[i] = q.poll(); } static void shuffle(int[] in) { for (int i = 0; i < in.length; i++) { int idx = (int) (Math.random() * in.length); fast_swap(in, idx, i); } } static boolean isPalindrome(String s) { StringBuilder sb = new StringBuilder(s); sb.reverse(); if (s.equals(sb.toString())) { return true; } return false; } public static int[] radixSort2(int[] a) { int n = a.length; int[] c0 = new int[0x101]; int[] c1 = new int[0x101]; int[] c2 = new int[0x101]; int[] c3 = new int[0x101]; for (int v : a) { c0[(v & 0xff) + 1]++; c1[(v >>> 8 & 0xff) + 1]++; c2[(v >>> 16 & 0xff) + 1]++; c3[(v >>> 24 ^ 0x80) + 1]++; } for (int i = 0; i < 0xff; i++) { c0[i + 1] += c0[i]; c1[i + 1] += c1[i]; c2[i + 1] += c2[i]; c3[i + 1] += c3[i]; } int[] t = new int[n]; for (int v : a) t[c0[v & 0xff]++] = v; for (int v : t) a[c1[v >>> 8 & 0xff]++] = v; for (int v : a) t[c2[v >>> 16 & 0xff]++] = v; for (int v : t) a[c3[v >>> 24 ^ 0x80]++] = v; return a; } static int[] computeLps(String pat) { int len = 0, i = 1, m = pat.length(); int lps[] = new int[m]; lps[0] = 0; while (i < m) { if (pat.charAt(i) == pat.charAt(len)) { ++len; lps[i] = len; ++i; } else { if (len != 0) { len = lps[len - 1]; } else { lps[i] = len; ++i; } } } return lps; } static ArrayList<Integer> kmp(String s, String pat) { ArrayList<Integer> al = new ArrayList<>(); int n = s.length(), m = pat.length(); int lps[] = computeLps(pat); int i = 0, j = 0; while (i < n) { if (s.charAt(i) == pat.charAt(j)) { i++; j++; if (j == m) { al.add(i - j); j = lps[j - 1]; } } else { if (j != 0) { j = lps[j - 1]; } else { i++; } } } return al; } static void reverse_ruffle_sort(int a[]) { shuffle(a); Arrays.sort(a); for (int l = 0, r = a.length - 1; l < r; ++l, --r) fast_swap(a, l, r); } static void ruffle_sort(int a[]) { shuffle(a); Arrays.sort(a); } static int getMax(int arr[], int n) { int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx; } static ArrayList<Long> primeFactors(long n) { ArrayList<Long> al = new ArrayList<>(); al.add(1L); while (n % 2 == 0) { if (!al.contains(2L)) { al.add(2L); } n /= 2L; } for (long i = 3; (long) i * i <= n; i += 2) { while ((n % i == 0)) { if (!al.contains((long) i)) { al.add((long) i); } n /= i; } } if (n > 2) { if (!al.contains(n)) { al.add(n); } } return al; } public static long totFactors(int n) { long cnt = 0, tot = 1; while (n % 2 == 0) { n /= 2; ++cnt; } tot *= (cnt + 1); for (int i = 3; i <= Math.sqrt(n); i += 2) { cnt = 0; while (n % i == 0) { n /= i; ++cnt; } tot *= (cnt + 1); } if (n > 2) { tot *= 2; } return tot; } static int[] z_function(String s) { int n = s.length(), z[] = new int[n]; for (int i = 1, l = 0, r = 0; i < n; ++i) { if (i <= r) z[i] = Math.min(z[i - l], r - i + 1); while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) ++z[i]; if (i + z[i] - 1 > r) { l = i; r = i + z[i] - 1; } } return z; } static void fast_swap(int[] a, int idx1, int idx2) { if (a[idx1] == a[idx2]) return; a[idx1] ^= a[idx2]; a[idx2] ^= a[idx1]; a[idx1] ^= a[idx2]; } static void fast_swap(long[] a, int idx1, int idx2) { if (a[idx1] == a[idx2]) return; a[idx1] ^= a[idx2]; a[idx2] ^= a[idx1]; a[idx1] ^= a[idx2]; } public static void fast_sort(long[] array) { ArrayList<Long> copy = new ArrayList<>(); for (long i : array) copy.add(i); Collections.sort(copy); for (int i = 0; i < array.length; i++) array[i] = copy.get(i); } static int factorsCount(int n) { boolean hash[] = new boolean[n + 1]; Arrays.fill(hash, true); for (int p = 2; p * p < n; p++) if (hash[p] == true) for (int i = p * 2; i < n; i += p) hash[i] = false; int total = 1; for (int p = 2; p <= n; p++) { if (hash[p]) { int count = 0; if (n % p == 0) { while (n % p == 0) { n = n / p; count++; } total = total * (count + 1); } } } return total; } static long binomialCoeff(long n, long k) { long res = 1; if (k > n - k) k = n - k; for (int i = 0; i < k; ++i) { res = (res * (n - i)); res /= (i + 1); } return res; } static long nck(long fact[], long inv[], long n, long k) { if (k > n) return 0; long res = fact[(int) n]; res = (int) ((res * inv[(int) k])); res = (int) ((res * inv[(int) (n - k)])); return res % mod; } public static ArrayList<Long> getFact(long x) { ArrayList<Long> facts = new ArrayList<>(); for (long i = 2; i * i <= x; ++i) { if (x % i == 0) { facts.add(i); if (i != x / i) { facts.add(x / i); } } } return facts; } static void matrix_ex(long n, long[][] A, long[][] I) { while (n > 0) { if (n % 2 == 0) { Multiply(A, A); n /= 2; } else { Multiply(I, A); n--; } } } static void Multiply(long[][] A, long[][] B) { int n = A.length, m = A[0].length, p = B[0].length; long[][] C = new long[n][p]; for (int i = 0; i < n; i++) { for (int j = 0; j < p; j++) { for (int k = 0; k < m; k++) { C[i][j] += ((A[i][k] % mod) * (B[k][j] % mod)) % mod; C[i][j] = C[i][j] % mod; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < p; j++) { A[i][j] = C[i][j]; } } } public static HashMap<Character, Integer> sortMapDesc(HashMap<Character, Integer> map) { List<Map.Entry<Character, Integer>> list = new LinkedList<>(map.entrySet()); Collections.sort(list, (o1, o2) -> o2.getValue() - o1.getValue()); HashMap<Character, Integer> temp = new LinkedHashMap<>(); for (Map.Entry<Character, Integer> i : list) { temp.put(i.getKey(), i.getValue()); } return temp; } public static HashMap<Integer, Integer> sortMapAsc(HashMap<Integer, Integer> map) { List<Map.Entry<Integer, Integer>> list = new LinkedList<>(map.entrySet()); Collections.sort(list, (o1, o2) -> o1.getValue() - o2.getValue()); HashMap<Integer, Integer> temp = new LinkedHashMap<>(); for (Map.Entry<Integer, Integer> i : list) { temp.put(i.getKey(), i.getValue()); } return temp; } public static long lcm(long l, long l2) { long val = gcd(l, l2); return (l * l2) / val; } public static int isSubsequence(String s, String t) { int n = s.length(); int m = t.length(); if (m > n) { return Integer.MAX_VALUE; } int i = 0, j = 0, skip = 0; while (i < n && j < m) { if (s.charAt(i) == t.charAt(j)) { --skip; ++j; } ++skip; ++i; } while (i < n) { ++i; ++skip; } if (j != m) { skip = Integer.MAX_VALUE; } return skip; } public static final class MultiSet<T> extends java.util.TreeMap<T, Long> { private static final long serialVersionUID = 1L; public MultiSet() { super(); } public MultiSet(final java.util.List<T> list) { super(); for (final T e : list) this.addOne(e); } public long count(final Object elm) { return getOrDefault(elm, 0L); } public void add(final T elm, final long amount) { if (!containsKey(elm)) put(elm, amount); else replace(elm, get(elm) + amount); if (this.count(elm) == 0) this.remove(elm); } public void addOne(final T elm) { this.add(elm, 1); } public void removeOne(final T elm) { this.add(elm, -1); } public void removeAll(final T elm) { this.add(elm, -this.count(elm)); } public static <T> MultiSet<T> merge(final MultiSet<T> a, final MultiSet<T> b) { final MultiSet<T> c = new MultiSet<>(); for (final T x : a.keySet()) c.add(x, a.count(x)); for (final T y : b.keySet()) c.add(y, b.count(y)); return c; } } public static long[][] combination(int l, int r) { long[][] pascal = new long[l + 1][r + 1]; pascal[0][0] = 1; for (int i = 1; i <= l; ++i) { pascal[i][0] = 1; for (int j = 1; j <= r; ++j) { pascal[i][j] = pascal[i - 1][j - 1] + pascal[i - 1][j]; } } return pascal; } public static long gcd(long... array) { long ret = array[0]; for (int i = 1; i < array.length; ++i) ret =gcd(ret, array[i]); return ret; } public static long lcm(int... array) { long ret = array[0]; for (int i = 1; i < array.length; ++i) ret = lcm(ret, array[i]); return ret; } public static int min(int a, int b) { return a < b ? a : b; } public static int min(int... array) { int ret = array[0]; for (int i = 1; i < array.length; ++i) ret = min(ret, array[i]); return ret; } public static long min(long a, long b) { return a < b ? a : b; } public static long min(long... array) { long ret = array[0]; for (int i = 1; i < array.length; ++i) ret = min(ret, array[i]); return ret; } public static int max(int a, int b) { return a > b ? a : b; } public static int max(int... array) { int ret = array[0]; for (int i = 1; i < array.length; ++i) ret = max(ret, array[i]); return ret; } public static long max(long a, long b) { return a > b ? a : b; } public static long max(long... array) { long ret = array[0]; for (int i = 1; i < array.length; ++i) ret = max(ret, array[i]); return ret; } public static long sum(int... array) { long ret = 0; for (int i : array) ret += i; return ret; } public static long sum(long... array) { long ret = 0; for (long i : array) ret += i; return ret; } public static int modinv(long x,long mod) { return (int) (CP.Modular_Expo(x, mod - 2,mod) % mod); } public static int lcs(String s, String t) { int n = s.length(), m = t.length(); int dp[][] = new int[n + 1][m + 1]; for (int i = 0; i <= n; ++i) { for (int j = 0; j <= m; ++j) { if (i == 0 || j == 0) { dp[i][j] = 0; } else if (s.charAt(i - 1) == t.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1] + 1; } else { dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); } } } return dp[n][m]; } } 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(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void printLine(int[] array) { print(array); writer.println(); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } public void printLine(int i) { writer.println(i); } public void printLine(char c) { writer.println(c); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } void flush() { writer.flush(); } } }
java
1307
E
E. Cow and Treatstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a successful year of milk production; Farmer John is rewarding his cows with their favorite treat: tasty grass!On the field, there is a row of nn units of grass, each with a sweetness sisi. Farmer John has mm cows, each with a favorite sweetness fifi and a hunger value hihi. He would like to pick two disjoint subsets of cows to line up on the left and right side of the grass row. There is no restriction on how many cows must be on either side. The cows will be treated in the following manner: The cows from the left and right side will take turns feeding in an order decided by Farmer John. When a cow feeds, it walks towards the other end without changing direction and eats grass of its favorite sweetness until it eats hihi units. The moment a cow eats hihi units, it will fall asleep there, preventing further cows from passing it from both directions. If it encounters another sleeping cow or reaches the end of the grass row, it will get upset. Farmer John absolutely does not want any cows to get upset. Note that grass does not grow back. Also, to prevent cows from getting upset, not every cow has to feed since FJ can choose a subset of them. Surprisingly, FJ has determined that sleeping cows are the most satisfied. If FJ orders optimally, what is the maximum number of sleeping cows that can result, and how many ways can FJ choose the subset of cows on the left and right side to achieve that maximum number of sleeping cows (modulo 109+7109+7)? The order in which FJ sends the cows does not matter as long as no cows get upset. InputThe first line contains two integers nn and mm (1≤n≤50001≤n≤5000, 1≤m≤50001≤m≤5000)  — the number of units of grass and the number of cows. The second line contains nn integers s1,s2,…,sns1,s2,…,sn (1≤si≤n1≤si≤n)  — the sweetness values of the grass.The ii-th of the following mm lines contains two integers fifi and hihi (1≤fi,hi≤n1≤fi,hi≤n)  — the favorite sweetness and hunger value of the ii-th cow. No two cows have the same hunger and favorite sweetness simultaneously.OutputOutput two integers  — the maximum number of sleeping cows that can result and the number of ways modulo 109+7109+7. ExamplesInputCopy5 2 1 1 1 1 1 1 2 1 3 OutputCopy2 2 InputCopy5 2 1 1 1 1 1 1 2 1 4 OutputCopy1 4 InputCopy3 2 2 3 2 3 1 2 1 OutputCopy2 4 InputCopy5 1 1 1 1 1 1 2 5 OutputCopy0 1 NoteIn the first example; FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 22 is lined up on the left side and cow 11 is lined up on the right side. In the second example, FJ can line up the cows as follows to achieve 11 sleeping cow: Cow 11 is lined up on the left side. Cow 22 is lined up on the left side. Cow 11 is lined up on the right side. Cow 22 is lined up on the right side. In the third example, FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 and 22 are lined up on the left side. Cow 11 and 22 are lined up on the right side. Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 11 is lined up on the right side and cow 22 is lined up on the left side. In the fourth example, FJ cannot end up with any sleeping cows, so there will be no cows lined up on either side.
[ "binary search", "combinatorics", "dp", "greedy", "implementation", "math" ]
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author lucasr */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; MyScanner in = new MyScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); ECowAndTreats solver = new ECowAndTreats(); solver.solve(1, in, out); out.close(); } static class ECowAndTreats { static long MOD = 1000000007; public static MyScanner sc; public static PrintWriter out; public void solve(int testNumber, MyScanner sc, PrintWriter out) { ECowAndTreats.sc = sc; ECowAndTreats.out = out; int n = sc.nextInt(); int m = sc.nextInt(); int[] elems = sc.nextIntArray(n); int[] sweetCount = new int[n + 1]; boolean[][] present = new boolean[n + 1][n + 1]; for (int i = 0; i < n; i++) { sweetCount[elems[i]]++; } IntArray[] cant = new IntArray[n + 1]; for (int i = 1; i <= n; i++) { cant[i] = new IntArray(); } for (int i = 0; i < m; i++) { int a = sc.nextInt(); int cc = sc.nextInt(); present[a][cc] = true; cant[a].add(cc); } for (int i = 1; i <= n; i++) { cant[i].sort(); } int ans = 0; long tot = 1; int[] acumLeft = new int[n + 1]; for (int i = 1; i <= n; i++) { int got = 0; for (int ii = 0; ii < cant[i].size(); ii++) { if (cant[i].get(ii) <= sweetCount[i]) got++; else break; } if (got > 0) { ans++; tot = (tot * got) % MOD; } } for (int pos = 0; pos < n; pos++) { int sw = elems[pos]; acumLeft[sw]++; if (present[sw][acumLeft[sw]]) { int curAns = 1; long curTot = 1; for (int i = 1; i <= n; i++) if (cant[i].size() > 0) { if (i == sw) { int got = 0; for (int ii = 0; ii < cant[i].size(); ii++) { int val = cant[i].get(ii); if (val <= sweetCount[i] - acumLeft[i] && val != acumLeft[i]) got++; } if (got > 0) { curAns++; curTot = (curTot * got) % MOD; } } else { int min = Math.min(sweetCount[i] - acumLeft[i], acumLeft[i]); int max = Math.max(sweetCount[i] - acumLeft[i], acumLeft[i]); int totMin = 0, totMax = 0; for (int ii = 0; ii < cant[i].size(); ii++) { int val = cant[i].get(ii); if (val <= min) totMin++; else if (val <= max) totMax++; else break; } totMax += totMin; long tot2 = totMin * (long) (totMax - 1); if (tot2 > 0) { curAns += 2; curTot = (curTot * tot2) % MOD; } else if (totMax > 0) { curAns++; curTot = (curTot * (totMin + totMax)) % MOD; } } } if (curAns >= ans) { if (curAns > ans) { ans = curAns; tot = curTot; } else { tot = (tot + curTot) % MOD; } } } } out.println(ans + " " + tot); } } static class IntArray { int[] arr; int size; public IntArray() { arr = new int[4]; } public void add(int val) { if (size == arr.length) { arr = Arrays.copyOf(arr, 2 * arr.length); } arr[size++] = val; } public int get(int pos) { return arr[pos]; } public int size() { return size; } public void sort() { Arrays.sort(arr, 0, size); } } static class MyScanner { private BufferedReader br; private StringTokenizer tokenizer; public MyScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public int[] nextIntArray(int n) { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = nextInt(); } return ret; } } }
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.util.*; import java.math.*; public class Main{ public static void main(String[]args)throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int T=Integer.parseInt(br.readLine()); while(T>0){ StringTokenizer st=new StringTokenizer(br.readLine()); int n=Integer.parseInt(st.nextToken()); int x=Integer.parseInt(st.nextToken()); String s=br.readLine(); int b[]=new int[n]; int zero=0,one=0; for(int i=0;i<n;i++){ if(s.charAt(i)=='1'){ one++; } else{ zero++; } b[i]=zero-one; } if(b[n-1]==0){ boolean ok=false; for(int i=0;i<n;i++){ if(b[i]==x){ ok=true; break; } } if(ok){ System.out.println(-1); } else{ System.out.println(0); } } else if(b[n-1]>0){ int cnt=0; if(x==0){ cnt=1; } for(int i=0;i<n;i++){ if(b[i]<=x && (x-b[i])%(b[n-1])==0){ cnt++; } } System.out.println(cnt); } else{ int cnt=0; if(x==0){ cnt=1; } for(int i=0;i<n;i++){ if(b[i]>=x && (b[i]-x)%(Math.abs(b[n-1]))==0){ cnt++; } } System.out.println(cnt); } T--; } } }
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" ]
import java.util.*; import java.lang.*; import java.io.*; public class Main { static final PrintWriter out =new PrintWriter(System.out); static final FastReader sc = new FastReader(); /* _oo0oo_ o8888888o 88" . "88 (| -_- |) 0\ = /0 ___/`---'\___ .' \\| |// '. / \\||| : |||// \ / _||||| -:- |||||- \ | | \\\ - /// | | | \_| ''\---/'' |_/ | \ .-\__ '-' ___/-. / ___'. .' /--.--\ `. .'___ ."" '< `.___\_<|>_/___.' >' "". | | : `- \`.;`\ _ /`;.`/ - ` : | | \ \ `_. \_ __\ /__ _/ .-` / / =====`-.____`.___ \_____/___.-`___.-'===== `=---=' */ public static boolean sorted(int a[]) { int n=a.length,i; int b[]=new int[n]; for(i=0;i<n;i++) b[i]=a[i]; Arrays.sort(b); for(i=0;i<n;i++) { if(a[i]!=b[i]) return false; } return true; } public static void main (String[] args) throws java.lang.Exception { int tes=sc.nextInt(); lable:while(tes-->0) { int n=sc.nextInt(); long a[]=new long[n]; int i; boolean flag=false; for(i=0;i<n;i++) a[i]=sc.nextLong(); long max=0,min=Integer.MAX_VALUE; if(a[0]==-1 && a[1]!=-1) { max=Math.max(a[1],max); min=Math.min(min,a[1]); flag=true; } if(a[n-1]==-1 && a[n-2]!=-1) { max=Math.max(a[n-2],max); min=Math.min(min,a[n-2]); flag=true; } for(i=1;i<n-1;i++) { if(a[i]==-1 && a[i+1]!=-1) { max=Math.max(a[i+1],max); min=Math.min(min,a[i+1]); flag=true; } if(a[i]==-1 && a[i-1]!=-1) { max=Math.max(a[i-1],max); min=Math.min(min,a[i-1]); flag=true; } } if(!flag) { System.out.println("0 69"); continue; } long big=0; long temp=(long)Math.ceil((double)(max+min)/2); for(i=0;i<n;i++) { if(a[i]==-1) a[i]=temp; } for(i=0;i<n-1;i++) big=Math.max(big,Math.abs(a[i]-a[i+1])); System.out.println(big+" "+temp); } } public static int first(ArrayList<Integer> arr, int low, int high, int x, int n) { if (high >= low) { int mid = low + (high - low) / 2; if ((mid == 0 || x > arr.get(mid-1)) && arr.get(mid) == x) return mid; else if (x > arr.get(mid)) return first(arr, (mid + 1), high, x, n); else return first(arr, low, (mid - 1), x, n); } return -1; } public static int last(ArrayList<Integer> arr, int low, int high, int x, int n) { if (high >= low) { int mid = low + (high - low) / 2; if ((mid == n - 1 || x < arr.get(mid+1)) && arr.get(mid) == x) return mid; else if (x < arr.get(mid)) return last(arr, low, (mid - 1), x, n); else return last(arr, (mid + 1), high, x, n); } return -1; } public static int lis(int[] arr) { int n = arr.length; ArrayList<Integer> al = new ArrayList<Integer>(); al.add(arr[0]); for(int i = 1 ; i<n;i++) { int x = al.get(al.size()-1); if(arr[i]>=x) { al.add(arr[i]); }else { int v = upper_bound(al, 0, al.size(), arr[i]); al.set(v, arr[i]); } } return al.size(); } public static int lower_bound(ArrayList<Long> ar,int lo , int hi , long k) { Collections.sort(ar); int s=lo; int e=hi; while (s !=e) { int mid = s+e>>1; if (ar.get((int)mid) <k) { s=mid+1; } else { e=mid; } } if(s==ar.size()) { return -1; } return s; } public static int upper_bound(ArrayList<Integer> ar,int lo , int hi, int k) { Collections.sort(ar); int s=lo; int e=hi; while (s !=e) { int mid = s+e>>1; if (ar.get(mid) <=k) { s=mid+1; } else { e=mid; } } if(s==ar.size()) { return -1; } return s; } static boolean isPrime(long N) { if (N<=1) return false; if (N<=3) return true; if (N%2 == 0 || N%3 == 0) return false; for (int i=5; i*i<=N; i=i+6) if (N%i == 0 || N%(i+2) == 0) return false; return true; } static int countBits(long a) { return (int)(Math.log(a)/Math.log(2)+1); } static long fact(long N) { long mod=1000000007; long n=2; if(N<=1)return 1; else { for(int i=3; i<=N; i++)n=(n*i)%mod; } return n; } private static boolean isInteger(String s) { try { Integer.parseInt(s); } catch (NumberFormatException e) { return false; } catch (NullPointerException e) { return false; } return true; } private static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } private static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } private static boolean isPalindrome(String str) { int i = 0, j = str.length() - 1; while (i < j) if (str.charAt(i++) != str.charAt(j--)) return false; return true; } private static String reverseString(String str) { StringBuilder sb = new StringBuilder(str); return sb.reverse().toString(); } 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
1284
B
B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5 1 1 1 1 1 2 1 4 1 3 OutputCopy9 InputCopy3 4 2 0 2 0 6 9 9 8 8 7 7 1 6 OutputCopy7 InputCopy10 3 62 24 39 1 17 1 99 1 60 1 64 1 30 2 79 29 2 20 73 2 85 37 1 100 OutputCopy72 NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences.
[ "binary search", "combinatorics", "data structures", "dp", "implementation", "sortings" ]
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.*; import java.io.*; public class Main { // Graph // prefix sums //inputs public static void main(String args[])throws Exception{ Input sc=new Input(); precalculates p=new precalculates(); StringBuilder sb=new StringBuilder(); long n=sc.readInt(); ArrayList<Integer> lst1=new ArrayList<>(); ArrayList<Integer> lst2=new ArrayList<>(); for(int i=0;i<n;i++){ int a[]=sc.readArray(); boolean b=false; int min=Integer.MAX_VALUE; int max=Integer.MIN_VALUE; for(int j=1;j<a[0];j++){ min=Math.min(a[j],min); max=Math.max(a[j],max); if(a[j]<a[j+1]){ b=true; break; } } if(!b){ lst1.add(Math.min(min,a[a[0]])); lst2.add(Math.max(max,a[a[0]])); } } long ans=n*(long)n; long c=0; Collections.sort(lst2); //System.out.println(lst1); //System.out.println(lst2); HashMap<Integer,Integer> map=new HashMap<>(); for(int i=0;i<lst2.size();i++){ map.put(lst2.get(i),i); } for(int i=0;i<lst1.size();i++){ int k=Collections.binarySearch(lst2, lst1.get(i)); if(k<0){ k=Math.abs(k); // if(k==1) // k=0; // k++; k--; if(k>lst1.size()) k--; // System.out.println(k+" "+ lst1.get(i)); }else{ k=map.get(lst1.get(i))+1; } c+=k; } ans=ans-c; sb.append(ans+"\n"); System.out.print(sb); } } class Input{ BufferedReader br; StringTokenizer st; Input(){ br=new BufferedReader(new InputStreamReader(System.in)); st=new StringTokenizer(""); } public int[] readArray() throws Exception{ st=new StringTokenizer(br.readLine()); int a[]=new int[st.countTokens()]; for(int i=0;i<a.length;i++){ a[i]=Integer.parseInt(st.nextToken()); } return a; } public long[] readArrayLong() throws Exception{ st=new StringTokenizer(br.readLine()); long a[]=new long[st.countTokens()]; for(int i=0;i<a.length;i++){ a[i]=Long.parseLong(st.nextToken()); } return a; } public int readInt() throws Exception{ st=new StringTokenizer(br.readLine()); return Integer.parseInt(st.nextToken()); } public long readLong() throws Exception{ st=new StringTokenizer(br.readLine()); return Long.parseLong(st.nextToken()); } public String readString() throws Exception{ return br.readLine(); } public int[][] read2dArray(int n,int m)throws Exception{ int a[][]=new int[n][m]; for(int i=0;i<n;i++){ st=new StringTokenizer(br.readLine()); for(int j=0;j<m;j++){ a[i][j]=Integer.parseInt(st.nextToken()); } } return a; } } class precalculates{ public int[] prefixSumOneDimentional(int a[]){ int n=a.length; int dp[]=new int[n]; for(int i=0;i<n;i++){ if(i==0) dp[i]=a[i]; else dp[i]=dp[i-1]+a[i]; } return dp; } public int[] postSumOneDimentional(int a[]) { int n = a.length; int dp[] = new int[n]; for (int i = n - 1; i >= 0; i--) { if (i == n - 1) dp[i] = a[i]; else dp[i] = dp[i + 1] + a[i]; } return dp; } public int[][] prefixSum2d(int a[][]){ int n=a.length;int m=a[0].length; int dp[][]=new int[n+1][m+1]; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ dp[i][j]=a[i-1][j-1]+dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1]; } } return dp; } public long pow(long a,long b){ long mod=1000000007; long ans=0; if(b<=0) return 1; if(b%2==0){ ans=pow(a,b/2)%mod; return ((ans%mod)*(ans%mod))%mod; }else{ return ((a%mod)*(ans%mod))%mod; } } } class GraphInteger{ HashMap<Integer,vertex> vtces; class vertex{ HashMap<Integer,Integer> children; public vertex(){ children=new HashMap<>(); } } public GraphInteger(){ vtces=new HashMap<>(); } public void addVertex(int a){ vtces.put(a,new vertex()); } public void addEdge(int a,int b,int cost){ if(!vtces.containsKey(a)){ vtces.put(a,new vertex()); } if(!vtces.containsKey(b)){ vtces.put(b,new vertex()); } vtces.get(a).children.put(b,cost); // vtces.get(b).children.put(a,cost); } public boolean isCyclicDirected(){ boolean isdone[]=new boolean[vtces.size()+1]; boolean check[]=new boolean[vtces.size()+1]; for(int i=1;i<=vtces.size();i++) { if (!isdone[i] && isCyclicDirected(i,isdone, check)) { return true; } } return false; } private boolean isCyclicDirected(int i,boolean isdone[],boolean check[]){ if(check[i]) return true; if(isdone[i]) return false; check[i]=true; isdone[i]=true; Set<Integer> set=vtces.get(i).children.keySet(); for(Integer ii:set){ if(isCyclicDirected(ii,isdone,check)) return true; } check[i]=false; return false; } }
java
1323
A
A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3 3 1 4 3 1 15 2 3 5 OutputCopy1 2 -1 2 1 2 NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum.
[ "brute force", "dp", "greedy", "implementation" ]
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); for(int p=0;p<t;p++) { int n=sc.nextInt(); int z=0; int[] arr=new int[n]; int even_1=-1,odd_1=-1,odd_2=-1; for(int i=0;i<n;i++) { arr[i]=sc.nextInt(); if(arr[i]%2==0) { even_1=i; } else{ if(odd_1==-1) { odd_1=i; } else{ odd_2=i; } } } if(odd_2==-1&&even_1==-1) { System.out.println("-1"); continue; } else if(even_1!=-1) { System.out.println("1"); System.out.println(even_1+1); } else { System.out.println("2"); System.out.print(odd_1+1+" "); System.out.print(odd_2+1); System.out.println(" "); } } } }
java
1312
E
E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such pair). Replace them by one element with value ai+1ai+1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array aa you can get?InputThe first line contains the single integer nn (1≤n≤5001≤n≤500) — the initial length of the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the initial array aa.OutputPrint the only integer — the minimum possible length you can get after performing the operation described above any number of times.ExamplesInputCopy5 4 3 2 2 3 OutputCopy2 InputCopy7 3 3 4 4 4 3 3 OutputCopy2 InputCopy3 1 3 5 OutputCopy3 InputCopy1 1000 OutputCopy1 NoteIn the first test; this is one of the optimal sequences of operations: 44 33 22 22 33 →→ 44 33 33 33 →→ 44 44 33 →→ 55 33.In the second test, this is one of the optimal sequences of operations: 33 33 44 44 44 33 33 →→ 44 44 44 44 33 33 →→ 44 44 44 44 44 →→ 55 44 44 44 →→ 55 55 44 →→ 66 44.In the third and fourth tests, you can't perform the operation at all.
[ "dp", "greedy" ]
import java.io.*; import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; public class e { public static void print(String str,long val){ System.out.println(str+" "+val); } public long gcd(long a, long b) { if (b==0L) return a; return gcd(b,a%b); } 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(Object[] 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'); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String path) throws FileNotFoundException { br = new BufferedReader(new FileReader(path)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader s=new FastReader(); int n = s.nextInt(); int[] arr = new int[n]; int MAX_VALUE = (int)(1e5); for(int i=0;i<n;i++){ arr[i] = s.nextInt(); } int[][] dp = new int[n][n]; for(int i=0;i<n;i++){ Arrays.fill(dp[i],MAX_VALUE); dp[i][i] = arr[i]; } for(int size = 2;size<=n;size++){ for(int i=0;i+size-1<n;i++){ for(int j=i;j<(i+size-1);j++){ if(dp[i][j]==dp[j+1][i+size-1]){ if(dp[i][j]<MAX_VALUE){ dp[i][i+size-1] = dp[i][j]+1; } } } if(dp[i][i+size-2]==dp[i+size-1][i+size-1]){ if(dp[i][i+size-2]<MAX_VALUE){ dp[i][i+size-1] = dp[i][i+size-2]+1; } } } } // debug(dp); int[] dp2 = new int[n]; dp2[0] = 1; for(int i=1;i<n;i++){ dp2[i] = (i+1); for(int j=0;j<=i;j++){ if(dp[j][i]<MAX_VALUE){ if(j>=1){ dp2[i] = Math.min(dp2[i],dp2[j-1]+1); } else { dp2[i] = Math.min(dp2[i],1); } } } } // print(dp2); System.out.println(dp2[n-1]); } // OutputStream out = new BufferedOutputStream( System.out ); // for(int i=1;i<n;i++){ // out.write((arr[i]+" ").getBytes()); // } // out.flush(); // long start_time = System.currentTimeMillis(); // long end_time = System.currentTimeMillis(); // System.out.println((end_time - start_time) + "ms"); }
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.util.*; import java.io.*; import java.math.*; import java.lang.*; public class StringModification { // static int mod = 998244353; static int mod = 1000000007; private static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) throws Exception { FastReader scn = new FastReader(); PrintWriter pw = new PrintWriter(System.out); int t = scn.nextInt(); outer : while(t-->0){ int n = scn.nextInt(); String s = scn.nextLine(); String[] arr = new String[n+1]; StringBuilder zero = new StringBuilder(); for(int i=0; i<=n; i++){ zero.append("z"); } arr[0] = zero.toString(); arr[1] = s; arr[n] = reverseStr(s); for(int k=2; k<n; k++){ StringBuilder sb = new StringBuilder(); sb.append(s.substring(k-1)); int len = sb.length(); String ss = s.substring(0, k-1); if(len % 2 == 1){ sb.append(reverseStr(ss)); }else{ sb.append(ss); } arr[k] = sb.toString(); } HashMap<String, Integer> hm = new HashMap<>(); for(int i=n; i>=1; i--){ hm.put(arr[i], i); } Arrays.sort(arr); pw.println(arr[0]); pw.println(hm.get(arr[0])); } pw.close(); } public static class Pair{ int x; int y; Pair(int x, int y){ this.x = x; this.y = y; } } private static void sort(int[] arr) { List<Integer> list = new ArrayList<>(); for (int i=0; i<arr.length; i++){ list.add(arr[i]); } Collections.sort(list); // collections.sort uses nlogn in backend for (int i = 0; i < arr.length; i++){ arr[i] = list.get(i); } } private static void sort(long[] arr) { List<Long> list = new ArrayList<>(); for(int i=0; i<arr.length; i++){ list.add(arr[i]); } Collections.sort(list); // collections.sort uses nlogn in backend for (int i = 0; i < arr.length; i++){ arr[i] = list.get(i); } } // private static void sort(Pair[] arr) { // List<Pair> list = new ArrayList<>(); // for(int i=0; i<arr.length; i++){ // list.add(arr[i]); // } // Collections.sort(list); // collections.sort uses nlogn in backend // for (int i = 0; i < arr.length; i++){ // arr[i] = list.get(i); // } // } private static void reverseSort(int[] arr){ List<Integer> list = new ArrayList<>(); for (int i=0; i<arr.length; i++){ list.add(arr[i]); } Collections.sort(list, Collections.reverseOrder()); // collections.sort uses nlogn in backend for (int i = 0; i < arr.length; i++){ arr[i] = list.get(i); } } private static void reverseSort(long[] arr){ List<Long> list = new ArrayList<>(); for (int i=0; i<arr.length; i++){ list.add(arr[i]); } Collections.sort(list, Collections.reverseOrder()); // collections.sort uses nlogn in backend for (int i = 0; i < arr.length; i++){ arr[i] = list.get(i); } } private static void reverseSort(ArrayList<Integer> list){ Collections.sort(list, Collections.reverseOrder()); } private static int lowerBound(int[] arr, int x){ int n = arr.length, si = 0, ei = n - 1; while(si <= ei){ int mid = si + (ei - si)/2; if(arr[mid] == x){ if(mid-1 >= 0 && arr[mid-1] == arr[mid]){ ei = mid-1; }else{ return mid; } }else if(arr[mid] > x){ ei = mid - 1; }else{ si = mid+1; } } return si; } private static int upperBound(int[] arr, int x){ int n = arr.length, si = 0, ei = n - 1; while(si <= ei){ int mid = si + (ei - si)/2; if(arr[mid] == x){ if(mid+1 < n && arr[mid+1] == arr[mid]){ si = mid+1; }else{ return mid + 1; } }else if(arr[mid] > x){ ei = mid - 1; }else{ si = mid+1; } } return si; } private static int upperBound(ArrayList<Integer> list, int x){ int n = list.size(), si = 0, ei = n - 1; while(si <= ei){ int mid = si + (ei - si)/2; if(list.get(mid) == x){ if(mid+1 < n && list.get(mid+1) == list.get(mid)){ si = mid+1; }else{ return mid + 1; } }else if(list.get(mid) > x){ ei = mid - 1; }else{ si = mid+1; } } return si; } // (x^y)%p in O(logy) private static long power(long x, long y){ long res = 1; x = x % mod; while(y > 0){ if ((y & 1) == 1){ res = (res * x) % mod; } y = y >> 1; x = (x * x) % mod; } return res; } public static boolean nextPermutation(int[] arr) { if(arr == null || arr.length <= 1){ return false; } int last = arr.length-2; while(last >= 0){ if(arr[last] < arr[last+1]){ break; } last--; } if (last < 0){ return false; } if(last >= 0){ int nextGreater = arr.length-1; for(int i=arr.length-1; i>last; i--){ if(arr[i] > arr[last]){ nextGreater = i; break; } } swap(arr, last, nextGreater); } reverse(arr, last+1, arr.length-1); return true; } private static void swap(int[] arr, int i, int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } private static void reverse(int[] arr, int i, int j){ while(i < j){ swap(arr, i++, j--); } } private static String reverseStr(String s){ StringBuilder sb = new StringBuilder(s); return sb.reverse().toString(); } // TC- O(logmax(a,b)) private static int gcd(int a, int b) { if(a == 0){ return b; } return gcd(b%a, a); } private static long gcd(long a, long b) { if(a == 0L){ return b; } return gcd(b%a, a); } private static long lcm(long a, long b) { return a / gcd(a, b) * b; } // TC- O(logmax(a,b)) private static int lcm(int a, int b) { return a / gcd(a, b) * b; } private static long inv(long x){ return power(x, mod - 2); } private static long summation(long n){ return (n * (n + 1L)) >> 1; } }
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.math.BigInteger; import java.util.*; /** * * @author eslam */ public class IceCave { 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 + ".in")); } // 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()); } } // 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 int mod = (int) (Math.pow(10, 9) + 7); static int dp[][]; // static int n, d, m; public static void main(String[] args) throws IOException { int t = 1;// input.nextInt(); loop: while (t-- > 0) { int n = input.nextInt(); int m = input.nextInt(); long a[] = new long[n]; TreeSet<Long> s = new TreeSet<>(); boolean ca = false; for (int i = 0; i < n; i++) { a[i] = input.nextInt(); long r = a[i] % m; if (s.contains(r)) { ca = true; } else { s.add(r); } } if (ca) { log.write("0\n"); } else { long ans = 1; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { ans = mod(mod(ans, m) * mod(Math.abs(a[i] - a[j]), m), m); } } log.write(ans + "\n"); } } log.flush(); } public static int countPrimeInRange(int n) { int cnt = 0; boolean isPrime[] = new boolean[n + 1]; 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 int logK(long v, long k) { int ans = 0; while (v > 1) { ans++; v /= k; } return ans; } public static long power(long a, long n) { if (n == 1) { return a; } long pow = power(a, n / 2); pow *= pow; if (n % 2 != 0) { pow *= a; } return pow; } 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 int get(int n) { int sum = 0; while (n > 0) { sum += n % 10; n /= 10; } return sum; } public static ArrayList<Integer> primeFactors(int n) { ArrayList<Integer> a = new ArrayList<>(); while (n % 2 == 0) { a.add(2); n /= 2; } for (int i = 3; i <= Math.sqrt(n); i += 2) { while (n % i == 0) { a.add(i); n /= i; } if (n < i) { break; } } if (n > 2) { a.add(n); } return a; } public static ArrayList<Integer> printPrimeFactoriztion(int n) { ArrayList<Integer> a = new ArrayList<>(); for (int i = 1; i < Math.sqrt(n) + 1; i++) { if (n % i == 0) { if (isPrime(i)) { a.add(i); n /= i; i = 0; } else if (isPrime(n / i)) { a.add(n / i); n = i; i = 0; } } } return a; } // end of solution public static BigInteger f(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 class tri { int x, y, z; public tri(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } } 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 (int i = 3; i <= Math.sqrt(num) + 1; 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 decimalToBinary(long n) { String w = ""; while (n > 0) { w = n % 2 + w; n /= 2; } return w; } public static boolean isSorted(int[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] >= a[i + 1]) { return false; } } return true; } 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 pair { int x; int y; public pair(int 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(long a, long b) { long GCD = GCD(a, b); System.out.println(a / GCD + " " + b / GCD); } /** */ // class RedBlackNode 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
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" ]
import java.util.*; import java.io.*; import java.math.*; public class Main { static class Publication{ int num; long t; public Publication(int num, long t){ this.num = num; this.t = t; } } public static void process(int test_number)throws IOException { int n = ni(); Publication arr[] = new Publication[n]; for(int i = 0; i < n; i++){ int num = ni(); arr[i] = new Publication(num, 0l); } for(int i = 0; i < n; i++){ arr[i].t = nl(); } Arrays.sort(arr, (A, B)-> (A.num != B.num) ? (Integer.compare(A.num, B.num)) : (Long.compare(A.t, B.t))); PriorityQueue<Publication> pq = new PriorityQueue<>((A, B)->( (-Long.compare(A.t, B.t)) )); long res = 0l, cummulativeSum = 0l; int idx = 0, newPublicationNum = arr[0].num; while(idx < n){ if(pq.isEmpty()) newPublicationNum = arr[idx].num; while(idx < n && arr[idx].num == newPublicationNum){ pq.add(arr[idx]); cummulativeSum += arr[idx].t; ++idx; } while(!pq.isEmpty()){ if(idx < n && arr[idx].num == newPublicationNum) break; Publication ob = pq.poll(); cummulativeSum -= ob.t; res += cummulativeSum; ++newPublicationNum; } } pn(res); } static final long mod = (long)1e9+7l; static boolean DEBUG = true; static FastReader sc; static PrintWriter out; public static void main(String[]args)throws IOException { out = new PrintWriter(System.out); sc = new FastReader(); long s = System.currentTimeMillis(); int t = 1; // t = ni(); for(int i = 1; i <= t; i++) process(i); out.flush(); System.err.println(System.currentTimeMillis()-s+"ms"); } static void trace(Object... o){ if(!DEBUG) return; System.err.println(Arrays.deepToString(o)); }; static void pn(Object o){ out.println(o); } static void p(Object o){ out.print(o); } static int ni()throws IOException{ return Integer.parseInt(sc.next()); } static long nl()throws IOException{ return Long.parseLong(sc.next()); } static double nd()throws IOException{ return Double.parseDouble(sc.next()); } static String nln()throws IOException{ return sc.nextLine(); } 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 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(); } String nextLine(){ String str = ""; try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
java
1288
C
C. Two Arraystime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm. Calculate the number of pairs of arrays (a,b)(a,b) such that: the length of both arrays is equal to mm; each element of each array is an integer between 11 and nn (inclusive); ai≤biai≤bi for any index ii from 11 to mm; array aa is sorted in non-descending order; array bb is sorted in non-ascending order. As the result can be very large, you should print it modulo 109+7109+7.InputThe only line contains two integers nn and mm (1≤n≤10001≤n≤1000, 1≤m≤101≤m≤10).OutputPrint one integer – the number of arrays aa and bb satisfying the conditions described above modulo 109+7109+7.ExamplesInputCopy2 2 OutputCopy5 InputCopy10 1 OutputCopy55 InputCopy723 9 OutputCopy157557417 NoteIn the first test there are 55 suitable arrays: a=[1,1],b=[2,2]a=[1,1],b=[2,2]; a=[1,2],b=[2,2]a=[1,2],b=[2,2]; a=[2,2],b=[2,2]a=[2,2],b=[2,2]; a=[1,1],b=[2,1]a=[1,1],b=[2,1]; a=[1,1],b=[1,1]a=[1,1],b=[1,1].
[ "combinatorics", "dp" ]
import java.io.*; import java.util.*; public class CF1562C extends PrintWriter { CF1562C() { super(System.out); } public static Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1562C o = new CF1562C(); o.main(); o.flush(); } static int power(int x, int y, int p) { // Initialize result int res = 1; // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } // Returns n^(-1) mod p static int modInverse(int n, int p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. static int nCrMod(int n, int r, int p) { if (n<r) return 0; // Base case if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r int[] fac = new int[n + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } static long calculate(long p, long q) { long mod = 1000000007, expo; expo = mod - 2; // Loop to find the value // until the expo is not zero while (expo != 0) { // Multiply p with q // if expo is odd if ((expo & 1) == 1) { p = (p * q) % mod; } q = (q * q) % mod; // Reduce the value of // expo by 2 expo >>= 1; } return p; } static String longestPalSubstr(String str) { // The result (length of LPS) int maxLength = 1; int start = 0; int len = str.length(); int low, high; // One by one consider every // character as center // point of even and length // palindromes for (int i = 1; i < len; ++i) { // Find the longest even // length palindrome with // center points as i-1 and i. low = i - 1; high = i; while (low >= 0 && high < len && str.charAt(low) == str.charAt(high)) { --low; ++high; } // Move back to the last possible valid palindrom substring // as that will anyway be the longest from above loop ++low; --high; if (str.charAt(low) == str.charAt(high) && high - low + 1 > maxLength) { start = low; maxLength = high - low + 1; } // Find the longest odd length // palindrome with center point as i low = i - 1; high = i + 1; while (low >= 0 && high < len && str.charAt(low) == str.charAt(high)) { --low; ++high; } // Move back to the last possible valid palindrom substring // as that will anyway be the longest from above loop ++low; --high; if (str.charAt(low) == str.charAt(high) && high - low + 1 > maxLength) { start = low; maxLength = high - low + 1; } } return str.substring(start, start + maxLength - 1); } long check(long a){ long ret=0; for(long k=2;(k*k*k)<=a;k++){ ret=ret+(a/(k*k*k)); } return ret; } /*public static int getFirstSetBitPos(int n) { return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1; } public static int bfsq(int n, int m, HashMap<Integer,ArrayList<Integer>>h,boolean v ){ v[n]=true; if(n==m) return 1; else { int a=h.get(n).get(0); int b=h.get(n).get(1); if(b>m) return(m-n); else { int a1=bfsq(a,m,h,v); int b1=bfsq(b,m,h,v); return 1+Math.min(a1,b1); } } }*/ static long nCr(int n, int r) { return fact(n) / (fact(r) * fact(n - r)); } // Returns factorial of n static long fact(long n) { long res = 1; for (long i = 2; i <= n; i++) res = res * i; return res; } /*void bfs(int src, HashMap<Integer,ArrayList<Integer,Integer>>h,int deg, boolean v[] ){ a[src]=deg; Queue<Integer>= new LinkedList<Integer>(); q.add(src); while(!q.isEmpty()){ (int a:h.get(src)){ if() } } }*/ /* void dfs(int root, int par, HashMap<Integer,ArrayList<Integer>>h,int dp[], int child[]) { dp[root]=0; child[root]=1; for(int x: h.get(root)){ if(x == par) continue; dfs(x,root,h,in,dp); child[root]+=child[x]; } ArrayList<Integer> mine= new ArrayList<Integer>(); for(int x: h.get(root)) { if(x == par) continue; mine.add(x); } if(mine.size() >=2){ int y= Math.max(child[mine.get(0)] - 1 + dp[mine.get(1)] , child[mine.get(1)] -1 + dp[mine.get(0)]); dp[root]=y;} else if(mine.size() == 1) dp[root]=child[mine.get(0)] - 1; } */ class Pair implements Comparable<Pair>{ int i; int j; Pair (int a, int b){ i = a; j = b; } public int compareTo(Pair A){ return (int)(this.i-A.i); }} /*static class Pair { int i; int j; Pair() { } Pair(int i, int j) { this.i = i; this.j = j; } }*/ /*ArrayList<Integer> check(int a[], int b){ int n=a.length; long ans=0;int k=0; ArrayList<Integer>ab= new ArrayList<Integer>(); for(int i=0;i<n;i++){ if(a[i]%m==0) {k=a[i]; while(a[i]%m==0){ a[i]=a[i]/m; } for(int z=0;z<k/a[i];z++){ ab.add(a[i]); } } else{ ab.add(a[i]); } } return ab; } */ /*int check[]; int tree[]; static void build( int []arr) { // insert leaf nodes in tree for (int i = 0; i < n; i++) tree[n + i] = arr[i]; // build the tree by calculating // parents for (int i = n - 1; i > 0; --i){ int ans= Math.min(tree[i << 1], tree[i << 1 | 1]); int ans1=Math.max((tree[i << 1], tree[i << 1 | 1])); if(ans==0) } }*/ /*static void ab(long n) { // Note that this loop runs till square root for (long i=1; i<=Math.sqrt(n); i++) { if(i==1) { p.add(n/i); continue; } if (n%i==0) { // If divisors are equal, print only one if (n/i == i) p.add(i); else // Otherwise print both { p.add(i); p.add(n/i); } } } }*/ //Base Case public static long solve(int A, int B, int C) { //Base Case if (B == 0) return 1; //Precomputing the factorial values long[] fac = new long[A + 1]; fac[0] = 1; for (int i = 1; i <= A; i++) fac[i] = fac[i - 1] * i % C; long ncr = ((fac[A] * modInverse(fac[B], C) % C * modInverse(fac[A - B], C) % C)% C); return ncr; } static long modInverse(long n, long p) { return power(n, p - 2, p); } static long power(long x, long y, long p) { // Initialize result long res = 1; // Update x if it is more than or // equal to p x = x % p; while (y > 0) { // If y is odd, multiply x // with result if (y % 2 == 1) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } void main() { // int g=sc.nextInt(); // int mod=1000000007; // for(int w=0;w<g;w++){ int n=sc.nextInt(); int m=sc.nextInt(); int mod=1000000007; int w=Math.min(n,2*m); long ans=0; for(int i=1;i<=w;i++){ ans+=solve(n,i,mod)*solve(2*m-1,i-1,mod); ans%=mod; } println(ans); } } // (*nCrModPFermat(2*m-1,i-1,mod);
java
1290
A
A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains three space-separated integers nn, mm and kk (1≤m≤n≤35001≤m≤n≤3500, 0≤k≤n−10≤k≤n−1)  — the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4 6 4 2 2 9 2 3 8 5 4 4 1 2 13 60 4 4 1 3 1 2 2 1 2 2 0 1 2 OutputCopy8 4 1 1 NoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element. the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8]; the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8]; if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element); if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44.
[ "brute force", "data structures", "implementation" ]
import java.util.*; import java.io.*; public class Main { static StringBuilder sb; static dsu dsu; static long fact[]; static int mod = (int) (1e9 + 7); static void solve() { int n=i(); int m=i(); int k=i(); int[]arr=new int[n]; k=Math.min(k,m-1); for(int i=0;i<n;i++)arr[i]=i(); m--; m-=k; m=Math.max(m,0); int ans=Integer.MIN_VALUE; for(int l=0;l<=k;l++){ int r=k-l; int si=l; int ei=n-1-r; int temp=Integer.MAX_VALUE; for(int l1=0;l1<=m;l1++){ int r1=m-l1; int f1=arr[si+l1]; int f2=arr[ei-r1]; f2=Math.max(f2,f1); temp=Math.min(temp,f2); } ans=Math.max(ans,temp); } sb.append(ans+"\n"); } public static void main(String[] args) { sb = new StringBuilder(); int test =i(); fact=new long[(int)1e6+10]; fact[0]=fact[1]=1; for(int i=2;i<fact.length;i++) { fact[i]=((long)(i%mod)*(long)(fact[i-1]%mod))%mod; } while (test-- > 0) { solve(); } System.out.println(sb); } //**************NCR%P****************** static long ncr(int n, int r) { if (r > n) return (long) 1; long res = fact[n] % mod; // System.out.println(res); res = ((long) (res % mod) * (long) (p(fact[r], mod - 2) % mod)) % mod; res = ((long) (res % mod) * (long) (p(fact[n - r], mod - 2) % mod)) % mod; // System.out.println(res); return res; } static long p(long x, long y)// POWER FXN // { if (y == 0) return 1; long res = 1; while (y > 0) { if (y % 2 == 1) { res = (res * x) %mod; y--; } x = (x * x) %mod; y = y / 2; } return res; } //**************END****************** // *************Disjoint set // union*********// static class dsu { int parent[]; dsu(int n) { parent = new int[n]; for (int i = 0; i < n; i++) parent[i] = -1; } int find(int a) { if (parent[a] < 0) return a; else { int x = find(parent[a]); parent[a] = x; return x; } } void merge(int a, int b) { a = find(a); b = find(b); if (a == b) return; parent[b] = a; } } //**************PRIME FACTORIZE **********************************// static TreeMap<Integer, Integer> prime(long n) { TreeMap<Integer, Integer> h = new TreeMap<>(); long num = n; for (int i = 2; i <= Math.sqrt(num); i++) { if (n % i == 0) { int nt = 0; while (n % i == 0) { n = n / i; nt++; } h.put(i, nt); } } if (n != 1) h.put((int) n, 1); return h; } //****CLASS PAIR ************************************************ static class Pair implements Comparable<Pair> { int dx; int dy; Pair() { } public int compareTo(Pair o) { if(this.dx!=o.dx) return (int) (this.dx - o.dx); else return (int) (this.dy - o.dy); } } static class Pair1 implements Comparable<Pair1> { int idx; long w; Pair1(int idx, long w) { this.idx = idx; this.w = w; } public int compareTo(Pair1 o) { return (int) (this.w - o.w); } } static class PairF implements Comparable<PairF> { int i; long x; PairF( int i,long x) { this.x = x; this.i=i; } public int compareTo(PairF o) { return (int) (this.x - o.x); } } //****CLASS PAIR ************************************************** static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int Int() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String String() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return String(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } } static InputReader in = new InputReader(System.in); static OutputWriter out = new OutputWriter(System.out); public static long[] sort(long[] a2) { int n = a2.length; ArrayList<Long> l = new ArrayList<>(); for (long i : a2) l.add(i); Collections.sort(l); for (int i = 0; i < l.size(); i++) a2[i] = l.get(i); return a2; } public static char[] sort(char[] a2) { int n = a2.length; ArrayList<Character> l = new ArrayList<>(); for (char i : a2) l.add(i); Collections.sort(l); for (int i = 0; i < l.size(); i++) a2[i] = l.get(i); return a2; } public static long pow(long x, long y) { long res = 1; while (y > 0) { if (y % 2 != 0) { res = (res * x);// % modulus; y--; } x = (x * x);// % modulus; y = y / 2; } return res; } //GCD___+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ public static long gcd(long x, long y) { if (x == 0) return y; else return gcd(y % x, x); } // ******LOWEST COMMON MULTIPLE // ********************************************* public static long lcm(long x, long y) { return (x * (y / gcd(x, y))); } //INPUT PATTERN******************************************************** public static int i() { return in.Int(); } public static long l() { String s = in.String(); return Long.parseLong(s); } public static String s() { return in.String(); } public static int[] readArrayi(int n) { int A[] = new int[n]; for (int i = 0; i < n; i++) { A[i] = i(); } return A; } public static long[] readArray(long n) { long A[] = new long[(int) n]; for (int i = 0; i < n; i++) { A[i] = l(); } return A; } }
java
1324
B
B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a subsequence of the array aa if bb can be obtained by removing some (possibly, zero) elements from aa (not necessarily consecutive) without changing the order of remaining elements. For example, [2][2], [1,2,1,3][1,2,1,3] and [2,3][2,3] are subsequences of [1,2,1,3][1,2,1,3], but [1,1,2][1,1,2] and [4][4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array aa of length nn is the palindrome if ai=an−i−1ai=an−i−1 for all ii from 11 to nn. For example, arrays [1234][1234], [1,2,1][1,2,1], [1,3,2,2,3,1][1,3,2,2,3,1] and [10,100,10][10,100,10] are palindromes, but arrays [1,2][1,2] and [1,2,3,1][1,2,3,1] are not.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.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 50005000 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5 3 1 2 1 5 1 2 2 3 2 3 1 1 2 4 1 2 2 1 10 1 1 2 2 3 3 4 4 5 5 OutputCopyYES YES NO YES NO NoteIn the first test case of the example; the array aa has a subsequence [1,2,1][1,2,1] which is a palindrome.In the second test case of the example, the array aa has two subsequences of length 33 which are palindromes: [2,3,2][2,3,2] and [2,2,2][2,2,2].In the third test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.In the fourth test case of the example, the array aa has one subsequence of length 44 which is a palindrome: [1,2,2,1][1,2,2,1] (and has two subsequences of length 33 which are palindromes: both are [1,2,1][1,2,1]).In the fifth test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.
[ "brute force", "strings" ]
import java.io.*; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.*; public class ProblemA { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int test = Integer.parseInt(br.readLine()); while(test-->0){ int n = Integer.parseInt(br.readLine()); String line[] = br.readLine().split(" "); boolean ok = false; for(int i = 0;i<n;i++){ int a = Integer.parseInt(line[i]); int count = 0; for(int j = i+1;j<n;j++){ if(Integer.parseInt(line[j]) == a){ count++; if(j - i>1){ ok = true; break; } } } if(count>=3 || ok){ ok = true; break; } } if(ok)sb.append("YES"); else sb.append("NO"); sb.append("\n"); } System.out.println(sb); } public static int search(int target,int arr[]){ int l = 0; int r = arr.length-1; int index = -1; while(l<=r){ int mid = (l+r)/2; if(arr[mid]<=target){ index = mid; 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); for(int i = 0;i<list.size();i++)arr[i] = list.get(i); } } class Pair{ int x,y; public Pair(int x,int y){ this.x = x; this.y = y; } }
java
1286
C1
C1. Madhouse (Easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is different with hard 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 (n+1)2(n+1)2.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 (n+1)2(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", "interactive", "math" ]
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.BufferedOutputStream; import java.io.UncheckedIOException; import java.nio.charset.Charset; 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 * * @author mikit */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; LightScanner in = new LightScanner(inputStream); LightWriter out = new LightWriter(outputStream); C1MadhouseEasyVersion solver = new C1MadhouseEasyVersion(); solver.solve(1, in, out); out.close(); } static class C1MadhouseEasyVersion { public void solve(int testNumber, LightScanner in, LightWriter out) { // out.setBoolLabel(LightWriter.BoolLabel.YES_NO_FIRST_UP); out.enableAutoFlush(); int n = in.ints(); char[] p1 = guess(in, out, 1, n); if (n == 1) { out.ans('!').ans(String.valueOf(p1)).ln(); return; } char[] p2 = guess(in, out, 1, n - 1); int[] cnt = new int[26]; for (int i = 0; i < n; i++) cnt[p1[i] - 'a']++; for (int i = 0; i < n - 1; i++) cnt[p2[i] - 'a']--; char[] ans = new char[n]; for (int i = 0; i < 26; i++) if (cnt[i] > 0) ans[n - 1] = (char) (i + 'a'); for (int i = 0; i < n / 2; i++) { if (ans[n - i - 1] != p1[n - i - 1]) ArrayUtil.swap(p1, i, n - i - 1); ans[i] = p1[i]; if (ans[i] != p2[i]) ArrayUtil.swap(p2, i, n - i - 2); ans[n - i - 2] = p2[n - i - 2]; } out.ans('!').ans(String.valueOf(ans)).ln(); } private static char[] guess(LightScanner in, LightWriter out, int from, int to) { int n = to - from + 1; if (n == 0) return new char[0]; out.ans('?').ans(from).ans(to).ln(); int n2 = (n + 1) / 2; int[][] cnt = new int[26][n + 1]; for (int i = 0; i < n * (n + 1) / 2; i++) { char[] s = in.string().toCharArray(); if (s.length < n2) continue; for (char c : s) cnt[c - 'a'][s.length]++; } for (int i = n2; i < n; i++) { for (int j = 0; j < 26; j++) { cnt[j][i] -= cnt[j][i + 1]; } } for (int i = n; i >= n2 + 1; i--) { for (int j = 0; j < 26; j++) { cnt[j][i] -= cnt[j][i - 1]; } } char[] ans = new char[n]; for (int i = 0; i < n; i++) { int ref = Math.max(n - i, i + 1); for (int j = 0; j < 26; j++) { if (cnt[j][ref] > 0) { cnt[j][ref]--; ans[i] = (char) ('a' + j); break; } } } return ans; } } static class LightScanner { private BufferedReader reader = null; private StringTokenizer tokenizer = null; public LightScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public String string() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new UncheckedIOException(e); } } return tokenizer.nextToken(); } public int ints() { return Integer.parseInt(string()); } } static class LightWriter implements AutoCloseable { private final Writer out; private boolean autoflush = false; private boolean breaked = true; public LightWriter(Writer out) { this.out = out; } public LightWriter(OutputStream out) { this(new OutputStreamWriter(new BufferedOutputStream(out), Charset.defaultCharset())); } public void enableAutoFlush() { autoflush = true; } public LightWriter print(char c) { try { out.write(c); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter print(String s) { try { out.write(s, 0, s.length()); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter ans(char c) { if (!breaked) { print(' '); } return print(c); } public LightWriter ans(String s) { if (!breaked) { print(' '); } return print(s); } public LightWriter ans(int i) { return ans(Integer.toString(i)); } public LightWriter ln() { print(System.lineSeparator()); breaked = true; if (autoflush) { try { out.flush(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } return this; } public void close() { try { out.close(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } } static final class ArrayUtil { private ArrayUtil() { } public static void swap(char[] a, int x, int y) { char t = a[x]; a[x] = a[y]; a[y] = t; } } }
java
1288
E
E. Messenger Simulatortime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is a frequent user of the very popular messenger. He's chatting with his friends all the time. He has nn friends, numbered from 11 to nn.Recall that a permutation of size nn is an array of size nn such that each integer from 11 to nn occurs exactly once in this array.So his recent chat list can be represented with a permutation pp of size nn. p1p1 is the most recent friend Polycarp talked to, p2p2 is the second most recent and so on.Initially, Polycarp's recent chat list pp looks like 1,2,…,n1,2,…,n (in other words, it is an identity permutation).After that he receives mm messages, the jj-th message comes from the friend ajaj. And that causes friend ajaj to move to the first position in a permutation, shifting everyone between the first position and the current position of ajaj by 11. Note that if the friend ajaj is in the first position already then nothing happens.For example, let the recent chat list be p=[4,1,5,3,2]p=[4,1,5,3,2]: if he gets messaged by friend 33, then pp becomes [3,4,1,5,2][3,4,1,5,2]; if he gets messaged by friend 44, then pp doesn't change [4,1,5,3,2][4,1,5,3,2]; if he gets messaged by friend 22, then pp becomes [2,4,1,5,3][2,4,1,5,3]. For each friend consider all position he has been at in the beginning and after receiving each message. Polycarp wants to know what were the minimum and the maximum positions.InputThe first line contains two integers nn and mm (1≤n,m≤3⋅1051≤n,m≤3⋅105) — the number of Polycarp's friends and the number of received messages, respectively.The second line contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤n1≤ai≤n) — the descriptions of the received messages.OutputPrint nn pairs of integers. For each friend output the minimum and the maximum positions he has been in the beginning and after receiving each message.ExamplesInputCopy5 4 3 5 1 4 OutputCopy1 3 2 5 1 4 1 5 1 5 InputCopy4 3 1 2 4 OutputCopy1 3 1 2 3 4 1 4 NoteIn the first example; Polycarp's recent chat list looks like this: [1,2,3,4,5][1,2,3,4,5] [3,1,2,4,5][3,1,2,4,5] [5,3,1,2,4][5,3,1,2,4] [1,5,3,2,4][1,5,3,2,4] [4,1,5,3,2][4,1,5,3,2] So, for example, the positions of the friend 22 are 2,3,4,4,52,3,4,4,5, respectively. Out of these 22 is the minimum one and 55 is the maximum one. Thus, the answer for the friend 22 is a pair (2,5)(2,5).In the second example, Polycarp's recent chat list looks like this: [1,2,3,4][1,2,3,4] [1,2,3,4][1,2,3,4] [2,1,3,4][2,1,3,4] [4,2,1,3][4,2,1,3]
[ "data structures" ]
import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Scanner; public class CP{ public static void main(String[] args)throws IOException { FastReader in=new FastReader(System.in); StringBuilder sb=new StringBuilder(); int i,j; int n=in.nextInt(); int m=in.nextInt(); int itp[]=new int[n+1]; int arr[]=new int[m]; int ans[]=new int[n+1]; int maxp[]=new int[n+1]; boolean exist[]=new boolean[n+1]; AVLTreeNew tree=new AVLTreeNew(); int p=m+1; for(i=1;i<=n;i++){ itp[i]=p; tree.insert(p); p++; } for(i=0;i<m;i++) { arr[i] = in.nextInt(); exist[arr[i]]=true; } for(i=1;i<=n;i++){ if(exist[i]) ans[i]=1; else ans[i]=i; maxp[i]=i; } int x; p=m; for(i=0;i<m;i++){ x=itp[arr[i]]; maxp[arr[i]]=Math.max(maxp[arr[i]],tree.getPosition(x)); tree.delete(x); tree.insert(p); itp[arr[i]]=p; p--; } for(i=1;i<=n;i++){ x=itp[i]; maxp[i]=Math.max(maxp[i],tree.getPosition(x)); } for(i=1;i<=n;i++){ sb.append(ans[i]+" "+maxp[i]).append("\n"); } System.out.println(sb); } } class AVLTreeNew { Node root; public AVLTreeNew() { root = null; } int height(Node N) { if (N == null) return 0; return N.height; } int max(int a, int b) { return (a > b) ? a : b; } int getBalance(Node N) { if (N == null) return 0; return height(N.left) - height(N.right); } long getSize(Node N) { if (N == null) return 0; return N.size; } int size() { return (int) getSize(root); } public void recurse(Node n) { if (n == null) return; System.out.println(n.key + " " + n.size); if (n.left != null) { System.out.println("GO to left"); recurse(n.left); } if (n.right != null) { System.out.println("GO to right"); recurse(n.right); } } Node rightRotate(Node y) { Node x = y.left; Node T2 = x.right; x.right = y; y.left = T2; y.height = max(height(y.left), height(y.right)) + 1; x.height = max(height(x.left), height(x.right)) + 1; y.size = 1 + getSize(y.left) + getSize(y.right); x.size = 1 + getSize(x.left) + getSize(x.right); return x; } Node leftRotate(Node x) { Node y = x.right; Node T2 = y.left; y.left = x; x.right = T2; x.height = max(height(x.left), height(x.right)) + 1; y.height = max(height(y.left), height(y.right)) + 1; x.size = 1 + getSize(x.left) + getSize(x.right); y.size = 1 + getSize(y.left) + getSize(y.right); return y; } Node minValueNode(Node node) { Node current = node; while (current.left != null) current = current.left; return current; } void insert(int key) { root = insert(root, key); } void delete(int key) { root = deleteNode(root, key); } void display() { recurse(root); } Node insert(Node node, int key) { if (node == null) return new Node(key); if (key < node.key) { node.left = insert(node.left, key); } else if (key > node.key) { node.right = insert(node.right, key); } else { System.out.println(1 / 0); node.size += 1; } node.height = 1 + max(height(node.left), height(node.right)); node.size = 1 + getSize(node.left) + getSize(node.right); int balance = getBalance(node); if (balance > 1 && key < node.left.key) return rightRotate(node); if (balance < -1 && key > node.right.key) return leftRotate(node); if (balance > 1 && key > node.left.key) { node.left = leftRotate(node.left); return rightRotate(node); } if (balance < -1 && key < node.right.key) { node.right = rightRotate(node.right); return leftRotate(node); } return node; } int getValue(long n) { return query(root, n); } int getPosition(long key){return (int)position(root,key);} long position(Node node,long key){ if(key<node.key) return position(node.left,key); else if(key>node.key) return getSize(node.left)+1+position(node.right,key); else return getSize(node.left)+1; } int query(Node node, long n) { if (n <= getSize(node.left)) { return query(node.left, n); } if (n == getSize(node.left) + 1) { return node.key; } else { return query(node.right, n - getSize(node.left) - 1); } } Node deleteNode(Node root, int key) { if (root == null) return root; if (key < root.key) root.left = deleteNode(root.left, key); else if (key > root.key) root.right = deleteNode(root.right, key); else { if ((root.left == null) || (root.right == null)) { Node temp = null; if (temp == root.left) temp = root.right; else temp = root.left; if (temp == null) { temp = root; root = null; } else root = temp; } else { Node temp = minValueNode(root.right); root.key = temp.key; root.right = deleteNode(root.right, temp.key); } } if (root == null) return root; root.height = max(height(root.left), height(root.right)) + 1; root.size = getSize(root.left) + getSize(root.right) + 1; int balance = getBalance(root); if (balance > 1 && getBalance(root.left) >= 0) return rightRotate(root); if (balance > 1 && getBalance(root.left) < 0) { root.left = leftRotate(root.left); return rightRotate(root); } if (balance < -1 && getBalance(root.right) <= 0) return leftRotate(root); if (balance < -1 && getBalance(root.right) > 0) { root.right = rightRotate(root.right); return leftRotate(root); } return root; } void preOrder(Node node) { if (node != null) { System.out.print(node.key + " "); preOrder(node.left); preOrder(node.right); } } } class Node { int key, height; long size; Node left, right; public Node(int v) { key = v; size = 1; height = 1; left = right = null; } } 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(); } String nextLine() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c != 10 && c != 13; c = scan()) { sb.append((char) c); } return sb.toString(); } char nextChar() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; return (char) c; } 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; } }
java
1295
A
A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2 3 4 OutputCopy7 11
[ "greedy" ]
import java.util.Scanner; public class Displaythenumber { public static void main(String[] args) { Scanner s=new Scanner(System.in); int t=s.nextInt(); for(int j=0;j<t;j++) { int n=s.nextInt(); if(n%2==0) { n/=2; for(int i=0;i<n;i++){ System.out.print("1"); } System.out.println(); } else if(n%2!=0) { n=n-3; n/=2; System.out.print("7"); for(int i=0;i<n;i++){ System.out.print("1"); } System.out.println(); } } } }
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" ]
import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.util.InputMismatchException; import java.util.PriorityQueue; import java.util.TreeSet; public class d { static class Solver { int N; Lecture lecA[], lecB[]; TreeSet<Lecture> byStart, byEnd; void solve(FastScanner s, PrintWriter out) { N = s.nextInt(); lecA = new Lecture[N]; lecB = new Lecture[N]; for(int i = 0; i < N; i++) { int sa = s.nextInt(), ea = s.nextInt(), sb = s.nextInt(), eb = s.nextInt(); lecA[i] = new Lecture(sa, ea, i); lecB[i] = new Lecture(sb, eb, i); } // event queue [time, index, 1 if remove else -1] PriorityQueue<int[]> q = new PriorityQueue<>((a, b) -> { if (a[0] == b[0]) { if(a[2] == b[2]) return a[1] - b[1]; // by ID return a[2] - b[2]; // remove first smh } return a[0] - b[0]; // by time }); // sweep A, check B byStart = new TreeSet<>((a, b) -> { if(a.start == b.start) return a.id - b.id; return a.start - b.start; }); byEnd = new TreeSet<>((a, b) -> { if(a.end == b.end) return a.id - b.id; return a.end - b.end; }); for(int i = 0; i < N; i++) { q.add(new int[] { lecA[i].start, i, 1 }); q.add(new int[] { lecA[i].end + 1, i, -1 }); } int cur[]; Lecture blec, qq; while(!q.isEmpty()) { cur = q.poll(); blec = lecB[cur[1]]; if(cur[2] == -1) { byStart.remove(blec); byEnd.remove(blec); continue; } else { // any overlapping? if(byStart.size() > 0) { qq = byStart.last(); if(qq != null && qq.start > blec.end) { out.println("NO"); return; } qq = byEnd.first(); if(qq != null && blec.start > qq.end) { out.println("NO"); return; } } byStart.add(blec); byEnd.add(blec); } } // reset (should be moot) byStart.clear(); byEnd.clear(); q.clear(); for(int i = 0; i < N; i++) { q.add(new int[] { lecB[i].start, i, 1 }); q.add(new int[] { lecB[i].end + 1, i, -1 }); } Lecture alec; while(!q.isEmpty()) { cur = q.poll(); alec = lecA[cur[1]]; if(cur[2] == -1) { byStart.remove(alec); byEnd.remove(alec); continue; } else { // any overlapping? if(byStart.size() > 0) { qq = byStart.last(); if(qq != null && qq.start > alec.end) { out.println("NO"); return; } qq = byEnd.first(); if(qq != null && alec.start > qq.end) { out.println("NO"); return; } } byStart.add(alec); byEnd.add(alec); } } out.println("YES"); } static class Lecture { int start, end, id; Lecture(int ss, int ee, int ii) { start = ss; end = ee; id = ii; } } } public static void main(String[] args) { FastScanner s = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); new Solver().solve(s, out); out.close(); s.close(); } static class FastScanner { private InputStream stream; private byte[] buf = new byte[1 << 22]; private int curChar; private int numChars; public FastScanner(InputStream stream) { this.stream = stream; } public FastScanner(File f) throws FileNotFoundException { this(new FileInputStream(f)); } public FastScanner(String s) { this.stream = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)); } void close() { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } 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++]; } boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } boolean isEndline(int c) { return c == '\n' || c == '\r' || c == -1; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isEndline(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndline(c)); return res.toString(); } public int[] nextIntArray(int N) { int[] ret = new int[N]; for (int i = 0; i < N; i++) ret[i] = this.nextInt(); return ret; } public int[][] next2DIntArray(int N, int M) { int[][] ret = new int[N][]; for (int i = 0; i < N; i++) ret[i] = this.nextIntArray(M); return ret; } public long[] nextLongArray(int N) { long[] ret = new long[N]; for (int i = 0; i < N; i++) ret[i] = this.nextLong(); return ret; } public long[][] next2DLongArray(int N, int M) { long[][] ret = new long[N][]; for (int i = 0; i < N; i++) ret[i] = nextLongArray(M); return ret; } public double[] nextDoubleArray(int N) { double[] ret = new double[N]; for (int i = 0; i < N; i++) ret[i] = this.nextDouble(); return ret; } public double[][] next2DDoubleArray(int N, int M) { double[][] ret = new double[N][]; for (int i = 0; i < N; i++) ret[i] = this.nextDoubleArray(M); return ret; } } }
java
1324
F
F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9 0 1 1 1 0 0 0 0 1 1 2 1 3 3 4 3 5 2 6 4 7 6 8 5 9 OutputCopy2 2 2 2 2 1 1 0 2 InputCopy4 0 0 1 0 1 2 1 3 1 4 OutputCopy0 -1 1 -1 NoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33.
[ "dfs and similar", "dp", "graphs", "trees" ]
import java.io.*; import java.lang.reflect.Array; 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.*; import java.io.*; import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.util.Collections; import java.io.InputStreamReader; public class Main { static int dp1[] ; static int dp2[] ; static void solver(int curr, int parent, ArrayList<ArrayList<Integer>> list,int a[]){ int temp= 0 ; for(int i : list.get(curr)){ if (i == parent)continue; solver(i, curr, list, a) ; int tt = dp1[i]; if (tt > 0)temp += tt ; } dp1[curr] = a[curr] + temp ; } static void solver2(int curr , int parent , ArrayList<ArrayList<Integer>> list , int a[]){ if (parent != -1) { int val = dp1[parent] + dp2[parent]; if (dp1[curr] >= 0) val -= dp1[curr]; dp2[curr] = max(0, val); } for(int i : list.get(curr)){ if (i == parent)continue; solver2(i,curr,list,a); } } 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); StringBuilder sb = new StringBuilder() ; int n = in.nextInt() ; int a[] = new int[n] ; for (int i = 0; i <n ; i++) { a[i] = in.nextInt() ; if (a[i] == 0)a[i] = -1 ; } dp1 = new int[n] ; dp2 = new int[n] ; ArrayList<ArrayList<Integer>> list = new ArrayList<>() ; for(int i=0 ; i<n ; i++)list.add(new ArrayList<>()) ; for (int i = 0; i <n-1 ; i++) { int src = in.nextInt()-1 ; int dest = in.nextInt()-1 ; list.get(src).add(dest); list.get(dest).add(src); } solver(0, -1, list, a); solver2(0, -1, list, a); for (int i = 0; i <n ; i++) { sb.append((dp1[i]+dp2[i]) + " ") ; } System.out.print(sb); out.flush(); out.close(); // } catch (Exception e) { // System.out.println(e); // return; // } } 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 long ncr(long n, long r, long mod) { if (r == 0) return 1; long val = ncr(n - 1, r - 1, mod); val = (n * val) % mod; val = (val * modInverse(r, mod)) % mod; return val; } static long fast_pow(long base, long n, long M) { if (n == 0) return 1; if (n == 1) return base % M; long halfn = fast_pow(base, n / 2, M); if (n % 2 == 0) return (halfn * halfn) % M; else return (((halfn * halfn) % M) * base) % M; } static long modInverse(long n, long M) { return fast_pow(n, M - 2, M); } 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()); } } static PrintWriter out = new PrintWriter(System.out); }
java
1323
B
B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e. aiai multiplied by bjbj). It's easy to see that cc consists of only zeroes and ones too.How many subrectangles of size (area) kk consisting only of ones are there in cc?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x1,x2,y1,y2x1,x2,y1,y2 (1≤x1≤x2≤n1≤x1≤x2≤n, 1≤y1≤y2≤m1≤y1≤y2≤m) a subrectangle c[x1…x2][y1…y2]c[x1…x2][y1…y2] is an intersection of the rows x1,x1+1,x1+2,…,x2x1,x1+1,x1+2,…,x2 and the columns y1,y1+1,y1+2,…,y2y1,y1+1,y1+2,…,y2.The size (area) of a subrectangle is the total number of cells in it.InputThe first line contains three integers nn, mm and kk (1≤n,m≤40000,1≤k≤n⋅m1≤n,m≤40000,1≤k≤n⋅m), length of array aa, length of array bb and required size of subrectangles.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), elements of aa.The third line contains mm integers b1,b2,…,bmb1,b2,…,bm (0≤bi≤10≤bi≤1), elements of bb.OutputOutput single integer — the number of subrectangles of cc with size (area) kk consisting only of ones.ExamplesInputCopy3 3 2 1 0 1 1 1 1 OutputCopy4 InputCopy3 5 4 1 1 1 1 1 1 1 1 OutputCopy14 NoteIn first example matrix cc is: There are 44 subrectangles of size 22 consisting of only ones in it: In second example matrix cc is:
[ "binary search", "greedy", "implementation" ]
import java.util.*; import javax.swing.text.Segment; import java.io.*; import java.math.*; import java.sql.Array; public class Main { static class Scanner{ BufferedReader br; StringTokenizer st; public Scanner() { 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 a , long b ,long mod) { return ((a%mod)*(b%mod))%mod; } 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 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[] 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.min(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.min(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 Scanner sc = new Scanner(); 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 void TEST_CASE() { int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int[] row = new int[n]; int[] col = new int[m]; for(int i =0 ; i<n ; i++) row[i] = sc.nextInt(); for(int i =0 ; i<m ; i++) col[i] = sc.nextInt(); ArrayList<Integer> ver = new ArrayList<>(); ArrayList<Integer> hor = new ArrayList<>(); int i = 0; while(i<n) { while(i<n && row[i] == 0) i++; int c = 0; while(i<n && row[i] == 1) { c++; i++; } if(c !=0) hor.add(c); } i =0 ; while(i<m) { while(i<m && col[i] == 0) i++; int c = 0; while(i<m && col[i] == 1) { c++; i++; } if(c!= 0) ver.add(c); } ArrayList<Long> factors = new ArrayList<>(); for(long j = 1 ; j*j <= k ;j++) { if(k%j == 0) { long a = j; long b = k/j; if(a == b) { factors.add(a); }else { factors.add(a); factors.add(b); } } } long ans = 0; // System.out.println(hor); // System.out.println(ver); // System.out.println(factors); Collections.sort(factors); Map<Long, Long> map = new HashMap<>(); for(long h:ver) { if(map.containsKey(h)) { ans += map.get(h); continue; } long val = 0; for(long v:hor) { long num = fnc(h, v, k, factors); val += num; ans += num ; // System.out.println(h+" , "+v +" - "+fnc(h, v, k, factors)); } map.put(h, val); } System.out.println(ans); } static long fnc(long n , long m, long k , ArrayList<Long> factors ) { long ans = 0; for(long r:factors) { long c= k/r; if(r > n) break; long b = n-r+1; long d= m - c + 1; if(b*d>0) ans += b*d; // System.out.println(c+" "+r+" "+b*d); } // System.out.println(n+" "+m+" "+ans); return ans; } } /*******************************************************************************************************************************************************/ /** */
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 java.util.*; import java.lang.Math.*; public class MyClass { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); int count = 0; long[] answer = new long[t]; while(t-- > 0) { long n = sc.nextLong(); long g = sc.nextLong(); long b = sc.nextLong(); long ans = (n+1)/2; long total = ans/g * (g+b); if(ans % g == 0){ total -= b; }else{ total += ans %g; } answer[count++] = Math.max(n, total); } for(long b : answer){ System.out.println(b); } } } class Point implements Comparable<Point>{ public int x; public int y; public Point(int x, int y){ this.x = x; this.y = y; } public int compareTo(Point o){ int real_value = Math.abs(o.x); int real_this_val = Math.abs(this.x); if(real_value > real_this_val){ return -1; }else if(real_value == real_this_val){ return 0; } return 1; } }
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.Arrays; import java.util.HashSet; import java.util.Objects; import java.util.StringTokenizer; public class Problem1304B { static Scanner scanner = new Scanner(System.in); public static void main(String[] args) throws IOException { int n = scanner.nextInt(); int length = scanner.nextInt(); HashSet<String > set = new HashSet<>(); char [] ans = new char[n*length]; Arrays.fill(ans,'0' ); int l = 0; int r = ans.length-1; int finalLength = 0; for (int i =0;i<n;i++){ String str = scanner.next(); String sbr = new StringBuilder(str).reverse().toString(); if (set.contains(sbr)){ set.remove(sbr); for (int j =0;j<length;j++){ ans[l++] = str.charAt(j); ans[r--] = sbr.charAt(length-j-1); } finalLength+=2*length; }else { set.add(str); } } for(String s : set) { String t = new StringBuilder(s).reverse().toString(); if(s.equals(t)) { finalLength += length; for(int j = 0; j < length; j++) { ans[l++] = s.charAt(j); } break; } } System.out.println(finalLength); for (int i =0;i<length*n;i++){ if (ans[i]!='0') System.out.print(ans[i]); } System.out.println(); } 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
1313
C2
C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.
[ "data structures", "dp", "greedy" ]
import java.util.*; import java.util.concurrent.CompletableFuture; import javax.swing.event.TreeExpansionEvent; import javax.swing.text.Segment; import java.io.*; import java.math.*; import java.sql.Array; public class Main { 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 long[] rvrs(long[] arr) { int i =0 , j = arr.length-1; int n = arr.length; long[] ans = new long[n]; for( i =0 ; i<n ; i++) ans[i] = arr[j--]; return ans; } static long mod_mul(long a , long b ,long mod) { return ((a%mod)*(b%mod))%mod; } 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 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; long MOD; public Combinations(long N , long mod) { MOD = 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) { 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[] 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.min(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.min(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 Reader sc = new Reader(); static StringBuilder sb = new StringBuilder(); public static void main(String args[]) { 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 void TEST_CASE() { int n = sc.nextInt(); long[] arr = new long[n]; for(int i =0 ; i <n ; i++) { arr[i] = sc.nextLong(); } if( n <=2) { for(long e:arr) sb.append(e+" "); return; } long[] left = arr(arr); arr = rvrs(arr); long[] right = arr(arr); right = rvrs(right); arr = rvrs(arr); long min = Long.MAX_VALUE; int ind = -1; for(int i =0 ; i<n ; i++) { long v = left[i] + right[i]; if(v<min) { min = v; ind = i; } } for(int i = ind-1 ; i>=0 ; i--) { arr[i] =Math.min(arr[i], arr[i+1]); } for(int i = ind+1 ; i<n ; i++) { arr[i] = Math.min(arr[i], arr[i-1]); } for(long e:arr) sb.append(e+" "); } static long[] arr(long[] arr) { int n = arr.length; Stack<Integer> st = new Stack<>(); int[] tree = new int[n]; for(int i = 0 ; i<n ; i++) { while(!st.isEmpty() && arr[st.peek()]> arr[i]) { st.pop(); } if(st.isEmpty()) tree[i] = -1; else tree[i] = st.peek(); st.push(i); } long[] pre = new long[n]; pre[0] = arr[0]; for(int i = 1 ; i<n ; i++) pre[i] += arr[i] + pre[i-1]; long[] left = new long[n]; for(int i =0 ; i< n ; i++) { if(tree[i]!=-1) { int ind = tree[i]; left[i] += left[ind]; left[i] += pre[i-1] - pre[ind]; left[i] -= (i-1-ind)*arr[i]; }else { if(i!=0) { left[i] += pre[i-1] - (i)*arr[i]; } } } return left; } } /*******************************************************************************************************************************************************/ /** 7 5 3 4 9 8 2 4 7 9 8 7 6 5 4 2 1 */
java
1141
E
E. Superhero Battletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputA superhero fights with a monster. The battle consists of rounds; each of which lasts exactly nn minutes. After a round ends, the next round starts immediately. This is repeated over and over again.Each round has the same scenario. It is described by a sequence of nn numbers: d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106). The ii-th element means that monster's hp (hit points) changes by the value didi during the ii-th minute of each round. Formally, if before the ii-th minute of a round the monster's hp is hh, then after the ii-th minute it changes to h:=h+dih:=h+di.The monster's initial hp is HH. It means that before the battle the monster has HH hit points. Print the first minute after which the monster dies. The monster dies if its hp is less than or equal to 00. Print -1 if the battle continues infinitely.InputThe first line contains two integers HH and nn (1≤H≤10121≤H≤1012, 1≤n≤2⋅1051≤n≤2⋅105). The second line contains the sequence of integers d1,d2,…,dnd1,d2,…,dn (−106≤di≤106−106≤di≤106), where didi is the value to change monster's hp in the ii-th minute of a round.OutputPrint -1 if the superhero can't kill the monster and the battle will last infinitely. Otherwise, print the positive integer kk such that kk is the first minute after which the monster is dead.ExamplesInputCopy1000 6 -100 -200 -300 125 77 -4 OutputCopy9 InputCopy1000000000000 5 -1 0 0 0 0 OutputCopy4999999999996 InputCopy10 4 -3 -6 5 4 OutputCopy-1
[ "math" ]
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.math.BigInteger; import java.util.*; public class Solution { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static class Pair { int x; int y; int z; // Constructor public Pair(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } // @Override // public int hashCode() { // return this.x ^ this.y; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // Pair other = (Pair) obj; // if (x != other.x) // return false; // if (y != other.y) // return false; // return true; // } } static class Quad { String a; String b; String c; String d; // Constructor public Quad(String a, String b, String c, String d) { this.a = a; this.b = b; this.c = c; this.d = d; } } public static void swap(int i, int[] arr) { int temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; } static boolean isPrime(long n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (long i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static long gcd(long a, long b) { if (a == 0) return b; else if (b == 0) return a; if (a < b) return gcd(a, b % a); else return gcd(b, a % b); } static int factorial(int n) { // single line to find factorial return (n == 1 || n == 0) ? 1 : (n * factorial(n - 1))/1000000007; } // Function to convert decimal to fraction public static void SubString(String str, int n, HashSet<String> hs) { for (int i = 0; i < n; i++) for (int j = i+1; j <= n; j++) // Please refer below article for details // of substr in Java // https://www.geeksforgeeks.org/java-lang-string-substring-java/ hs.add(str.substring(i, j)); } static class TrieNode{ TrieNode children[]; boolean isEnd; TrieNode(){ this.children = new TrieNode[26]; this.isEnd = false; } } static void subStrings(String s,HashSet<String> hs) { // To store distinct output subStrings HashSet<String> us = new HashSet<String>(); // Traverse through the given String and // one by one generate subStrings beginning // from s[i]. for (int i = 0; i < s.length(); ++i) { // One by one generate subStrings ending // with s[j] String ss = ""; for (int j = i; j < s.length(); ++j) { ss = ss + s.charAt(j); us.add(ss); } } // Print all subStrings one by one for (String str : us) { hs.add(str); } } static boolean isSubSequence(String str1, String str2, int m, int n) { int j = 0; // Traverse str2 and str1, and compare // current character of str2 with first // unmatched char of str1, if matched // then move ahead in str1 for (int i = 0; i < n && j < m; i++) if (str1.charAt(j) == str2.charAt(i)) j++; // If all characters of str1 were found // in str2 return (j == m); } static int onesComplement(int n) { // Find number of bits in the // given integer int number_of_bits = (int)(Math.floor(Math.log(n) / Math.log(2))) + 1; // XOR the given integer with poe(2, // number_of_bits-1 and print the result return ((1 << number_of_bits) - 1) ^ n; } public static void main(String[] args) throws IOException{ BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); FastReader sc = new FastReader(); // int t = sc.nextInt(); // while(t-- > 0) { long H = sc.nextLong(); int n = sc.nextInt(); long[] arr = new long[n]; long diff=0; long min=Integer.MAX_VALUE; for(int i=0;i<n;i++) { arr[i]=sc.nextLong(); diff+=arr[i]; min=Math.min(min, diff); if(diff+H<=0) { System.out.println(i+1); return; } } if(diff>=0) { System.out.println(-1); return; } long HH=H; H=H+min; //System.out.println(min); //System.out.println(H); long ans=H/Math.abs(diff); //System.out.println(ans); H=H%Math.abs(diff); if(H!=0) { ans++;H=HH-(Math.abs(diff)*(ans));} else H=HH-(Math.abs(diff)*ans); //System.out.println(H); diff=0; for(int i=0;i<n;i++) { diff+=arr[i]; if(diff+H<=0) { System.out.println(i+1+(ans*n)); return; } } } // // } //output.flush(); }
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.*; public class Main{ static int solveLower(int i,int[]in,int left,int right) { int lo=0,hi=i-1; int ans=-1; while(lo<=hi) { int mid=(lo+hi)>>1; int sum=in[i]+in[mid]; if(sum>=left && sum<=right) { ans=mid; hi=mid-1; } else { if(sum<left) { lo=mid+1; } else { hi=mid-1; } } } return ans; } static int solveUpper(int i,int[]in,int left,int right) { int lo=0,hi=i-1; int ans=-1; while(lo<=hi) { int mid=(lo+hi)>>1; int sum=in[i]+in[mid]; if(sum>=left && sum<=right) { ans=mid; lo=mid+1; } else { if(sum<left) { lo=mid+1; } else { hi=mid-1; } } } return ans; } public static void main(String[] args) throws Exception{ MScanner sc=new MScanner(System.in); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt(); int[]in=sc.takearr(n); int ans=0; for(int b=0;b<27;b++) { int tmp[]=new int[n]; for(int i=0;i<n;i++) { tmp[i]=in[i]%(1<<(b+1)); } Arrays.sort(tmp); int left=1<<b,right=(1<<(b+1))-1; long cnt=0; for(int i=1;i<n;i++) { int lower=solveLower(i, tmp, left, right); if(lower==-1)continue; int upper=solveUpper(i, tmp, left, right); cnt+=upper-lower+1; } left=(1<<b)+(1<<(b+1));right=(1<<(b+2))-2; for(int i=1;i<n;i++) { int lower=solveLower(i, tmp, left, right); if(lower==-1)continue; int upper=solveUpper(i, tmp, left, right); cnt+=upper-lower+1; } if(cnt%2==1) { ans+=1<<b; } } 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
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" ]
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int m = scanner.nextInt(); int pMax = 0; for (int i = 2; i < n; i++) { pMax += i / 2; } if (pMax < m) { System.out.println(-1); return; } if (n == 1) { System.out.println(1); return; } if (n == 2) { System.out.println("1 2"); return; } int[] ans = new int[n]; ans[0] = 1; ans[1] = 2; int k = 2; while (m >= k / 2) { ans[k] = k + 1; m -= k / 2; k++; } if (k < n && m != 0) { ans[k] = 2 * k - 2 * m + 1; k++; } int diff = ans[k-1]+ans[k-2]+1; for (int i = n-1; i >= k; i--) { ans[i] = 1_000_000_000 - diff*(n-1-i); } StringBuilder sb = new StringBuilder(); sb.append("1 2"); for (int i = 2; i < n; i++) { sb.append(' ').append(ans[i]); } System.out.println(sb.toString()); } }
java
1304
D
D. Shortest and Longest LIStime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong recently learned how to find the longest increasing subsequence (LIS) in O(nlogn)O(nlog⁡n) time for a sequence of length nn. He wants to test himself if he can implement it correctly, but he couldn't find any online judges that would do it (even though there are actually many of them). So instead he's going to make a quiz for you about making permutations of nn distinct integers between 11 and nn, inclusive, to test his code with your output.The quiz is as follows.Gildong provides a string of length n−1n−1, consisting of characters '<' and '>' only. The ii-th (1-indexed) character is the comparison result between the ii-th element and the i+1i+1-st element of the sequence. If the ii-th character of the string is '<', then the ii-th element of the sequence is less than the i+1i+1-st element. If the ii-th character of the string is '>', then the ii-th element of the sequence is greater than the i+1i+1-st element.He wants you to find two possible sequences (not necessarily distinct) consisting of nn distinct integers between 11 and nn, inclusive, each satisfying the comparison results, where the length of the LIS of the first sequence is minimum possible, and the length of the LIS of the second sequence is maximum possible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).Each test case contains exactly one line, consisting of an integer and a string consisting of characters '<' and '>' only. The integer is nn (2≤n≤2⋅1052≤n≤2⋅105), the length of the permutation you need to find. The string is the comparison results explained in the description. The length of the string is n−1n−1.It is guaranteed that the sum of all nn in all test cases doesn't exceed 2⋅1052⋅105.OutputFor each test case, print two lines with nn integers each. The first line is the sequence with the minimum length of the LIS, and the second line is the sequence with the maximum length of the LIS. If there are multiple answers, print any one of them. Each sequence should contain all integers between 11 and nn, inclusive, and should satisfy the comparison results.It can be shown that at least one answer always exists.ExampleInputCopy3 3 << 7 >><>>< 5 >>>< OutputCopy1 2 3 1 2 3 5 4 3 7 2 1 6 4 3 1 7 5 2 6 4 3 2 1 5 5 4 2 1 3 NoteIn the first case; 11 22 33 is the only possible answer.In the second case, the shortest length of the LIS is 22, and the longest length of the LIS is 33. In the example of the maximum LIS sequence, 44 '33' 11 77 '55' 22 '66' can be one of the possible LIS.
[ "constructive algorithms", "graphs", "greedy", "two pointers" ]
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); DShortestAndLongestLIS solver = new DShortestAndLongestLIS(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) { solver.solve(i, in, out); } out.close(); } static class DShortestAndLongestLIS { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); String s = in.nextString(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = n - i; } for (int i = 0; i < n - 1; i++) { if (s.charAt(i) == '<') { int j = i; while (j + 1 < n - 1 && s.charAt(j + 1) == '<') { j++; } reverse(a, i, j); i = j; } } out.println(a); for (int i = 0; i < n; i++) { a[i] = i + 1; } for (int i = 0; i < n - 1; i++) { if (s.charAt(i) == '>') { int j = i; while (j + 1 < n - 1 && s.charAt(j + 1) == '>') { j++; } reverse(a, i, j); i = j; } } out.println(a); } private void reverse(int[] a, int i, int j) { int x = i; int y = j + 1; while (x < y) { int t = a[x]; a[x] = a[y]; a[y] = t; x++; y--; } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return nextString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void println(int[] array) { print(array); writer.println(); } public void close() { writer.close(); } } }
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.rajan.codeforces.level_1500; import java.io.*; import java.util.Arrays; public class FightWithMonsters { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out)); String[] temp = reader.readLine().split("\\s+"); int n = Integer.parseInt(temp[0]), a = Integer.parseInt(temp[1]), b = Integer.parseInt(temp[2]), k = Integer.parseInt(temp[3]); temp = reader.readLine().split("\\s+"); int[][] h = new int[n][2]; for (int i = 0; i < n; i++) { int pow = Integer.parseInt(temp[i]); long leftForA = pow % (a + 0L + b); if (leftForA == 0) leftForA = a + 0L + b; if (leftForA <= a) h[i] = new int[]{pow, 0}; else { int aTurnNeeded = (int) Math.ceil(leftForA / (a * 1.0)); h[i] = new int[]{pow, aTurnNeeded - 1}; } } Arrays.sort(h, (x, y) -> Integer.compare(x[1], y[1])); int ans = 0; for (int i = 0; i < n; i++) { if (h[i][1] == 0) { ans++; } else { if (h[i][1] <= k) { k -= h[i][1]; ans++; } } } writer.write(ans + "\n"); writer.flush(); } }
java
1294
E
E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3 3 2 1 1 2 3 4 5 6 OutputCopy6 InputCopy4 3 1 2 3 4 5 6 7 8 9 10 11 12 OutputCopy0 InputCopy3 4 1 6 3 4 5 10 7 8 9 2 11 12 OutputCopy2 NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22.
[ "greedy", "implementation", "math" ]
import java.util.*; public class Hello { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int R = sc.nextInt(); int C = sc.nextInt(); int matrix[][] = new int[R][C]; for (int row = 0; row < R; row++) { for (int col = 0; col < C; col++) { matrix[row][col] = sc.nextInt(); matrix[row][col]--; } } long result = 0; for (int col = 0; col < C; col++) { int count[] = new int[R]; for (int row = 0; row < R; row++) { if (matrix[row][col] % C == col) { int pos = matrix[row][col] / C; if (pos < R) { ++count[(row - pos + R) % R]; } } } int cur = R - count[0]; for (int row = 1; row < R; row++) { cur = Math.min(cur, R - count[row] + row); } result += cur; } System.out.println(result); } }
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.*; import java.nio.file.FileStore; import java.util.*; public class zia { static boolean prime[] = new boolean[25001]; static void ruffleSort(int[] a) { int n=a.length; Random random = new Random(); for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } public static int Lcm(int a,int b) { int max=Math.max(a,b); for(int i=1;;i++) { if((max*i)%a==0&&(max*i)%b==0) return (max*i); } } static void sieve(int n,boolean prime[]) { // boolean prime[] = new boolean[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { if (prime[p] == true) { for (int i = p * p; i <= n; i =i+ p) prime[i] = false; } } } // public static String run(int ar[],int n) // { // } public static long lcm(long a,long b) { long max=Math.max(a, b); long min=Math.min(a, b); for(int i=1;;i++) { if((max*i)%min==0) return max; } } public static long calculate(long a,long b,long x,long y,long n) { if(a-x>=n) { a-=n; } else { b=b-(n-(a-x)); a=x; if(b<y) b=y; } return a*b; } public static int upperbound(int s,int e, long ar[],long x) { int res=-1; while(s<=e) { int mid=((s-e)/2)+e; if(ar[mid]>x) {e=mid-1;res=mid;} else if(ar[mid]<x) {s=mid+1;} else {e=mid-1;res=mid; if(mid>0&&ar[mid]==ar[mid-1]) e=mid-1; else break; } } return res; } public static int lowerbound(int s,int e, long ar[],long x) { int res=-1; while(s<=e) { int mid=((s-e)/2)+e; if(ar[mid]>x) {e=mid-1;} else if(ar[mid]<x) {s=mid+1;res=mid;} else {res=mid; if(mid+1<ar.length&&ar[mid]==ar[mid+1]) s=mid+1; else break;} } return res; } static long modulo=1000000007; public static long power(long a, long b) { if(b==0) return 1; long temp=power(a,b/2)%modulo; if((b&1)==0) return (temp*temp)%modulo; else return (((temp*temp)%modulo)*a)%modulo; } public static long powerwithoutmod(long a, long b) { if(b==0) return 1; long temp=power(a,b/2); if((b&1)==0) return (temp*temp); else return ((temp*temp)*a); } public static double log2(long a) { double d=Math.log(a)/Math.log(2); return d; } public static int log10(long a) { double d=Math.log(a)/Math.log(10); return (int)d; } public static int find(int ar[],int x) { int count=0; for(int i=0;i<ar.length;i+=2) { if((ar[i]&1)!=x) count++; } return count; } public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } public static long frogK(int index,long height[],long output[],int k) { if(index==1) return 0; if(output[index]==0) { long MinEnergy=Long.MAX_VALUE; for(int j=1;j<=k&&index-j>=1;j++) MinEnergy=Math.min(MinEnergy,frogK(index-j, height, output, k)+Math.abs(height[index]-height[index-j])); output[index]=MinEnergy; } return output[index]; } public static void tree(int s,int e,int ar[],int c) { if(s<=e) { int max=s; for(int i=s;i<=e;i++) if(ar[i]>ar[max]) max=i; ar[max]=c++; tree(s,max-1,ar,c); tree(max+1,e,ar,c); } } public static void solve(int s,int m,ArrayList<Integer> digits) { for(int i=0;i<m;i++) { if(s>=9) { digits.add(9); s-=9; } else { if(s!=0) {digits.add(s);s=0;} else digits.add(0); } } } public static boolean isValid(int hour,int minute,int h,int m) { int ar[]={0,1,5,-1,-1,2,-1,-1,8,-1}; if(ar[minute%10]==-1||ar[minute/10]==-1 ||ar[hour%10]==-1||ar[hour/10]==-1) return false; int mirrorHour=ar[minute%10]*10+ar[minute/10]; int mirrorMinute=ar[hour%10]*10+ar[hour/10]; if(mirrorMinute>=m||mirrorHour>=h) return false; return true; } public static void main(String[] args) throws Exception { FastIO sc = new FastIO(); //sc.println(); //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx CODE xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx int test=sc.nextInt(); // // double c=Math.log(10); // boolean prime[]=new boolean[1000000001]; // sieve(1000000000, prime); while(test-->0) { char ar[]=sc.next().toCharArray(); int n=ar.length; int res=1,jump=1; for(int i=0;i<n;i++) { if(ar[i]=='L') { jump++; res=Math.max(res,jump); } else jump=1; } sc.println(res); } // xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx CODE xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx sc.close(); } } class pair implements Comparable<pair>{ long a; long b; pair(long a,long b) {this.a=a; this.b=b; } public int compareTo(pair p) {return (int)(-this.a+p.a);} } class triplet implements Comparable<triplet>{ int first,second,third; triplet(int first,int second,int third) {this.first=first; this.second=second; this.third=third; } public int compareTo(triplet p) {return this.third-p.third;} } // class triplet // { // int x1,x2,i; // triplet(int a,int b,int c) // {x1=a;x2=b;i=c;} // } class FastIO extends PrintWriter { private InputStream stream; private byte[] buf = new byte[1<<16]; private int curChar, numChars; // standard input public FastIO() { this(System.in,System.out); } public FastIO(InputStream i, OutputStream o) { super(o); stream = i; } // file input public FastIO(String i, String o) throws IOException { super(new FileWriter(o)); stream = new FileInputStream(i); } // throws InputMismatchException() if previously detected end of file private int nextByte() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars == -1) return -1; // end of file } return buf[curChar++]; } public String nextLine() { int c; do { c = nextByte(); } while (c <= '\n'); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = nextByte(); } while (c > '\n'); return res.toString(); } public String next() { int c; do { c = nextByte(); } while (c <= ' '); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = nextByte(); } while (c > ' '); return res.toString(); } public int nextInt() { int c; do { c = nextByte(); } while (c <= ' '); int sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = 10*res+c-'0'; c = nextByte(); } while (c > ' '); return res * sgn; } public long nextLong() { int c; do { c = nextByte(); } while (c <= ' '); long sgn = 1; if (c == '-') { sgn = -1; c = nextByte(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res = 10*res+c-'0'; c = nextByte(); } while (c > ' '); return res * sgn; } public double nextDouble() { return Double.parseDouble(next()); } }
java
1312
E
E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such pair). Replace them by one element with value ai+1ai+1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array aa you can get?InputThe first line contains the single integer nn (1≤n≤5001≤n≤500) — the initial length of the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the initial array aa.OutputPrint the only integer — the minimum possible length you can get after performing the operation described above any number of times.ExamplesInputCopy5 4 3 2 2 3 OutputCopy2 InputCopy7 3 3 4 4 4 3 3 OutputCopy2 InputCopy3 1 3 5 OutputCopy3 InputCopy1 1000 OutputCopy1 NoteIn the first test; this is one of the optimal sequences of operations: 44 33 22 22 33 →→ 44 33 33 33 →→ 44 44 33 →→ 55 33.In the second test, this is one of the optimal sequences of operations: 33 33 44 44 44 33 33 →→ 44 44 44 44 33 33 →→ 44 44 44 44 44 →→ 55 44 44 44 →→ 55 55 44 →→ 66 44.In the third and fourth tests, you can't perform the operation at all.
[ "dp", "greedy" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Solution { static Reader input = new Reader(); static int n; static int[] a; static int[][] segment; static Integer[][] memo; public static void main(String[] args) throws IOException { n = input.nextInt(); a = new int[n]; for(int i = 0; i < n; ++i) a[i] = input.nextInt(); segment = new int[n][n]; for(int i = 0; i < n; ++i) { segment[i][i] = a[i]; } int e; for(int s = 2; s <= n; ++s) { for(int i = 0; i <= n-s; ++i) { e = i+s-1; for(int j = i; j < e; ++j) { if(segment[i][j] == segment[j+1][e] && segment[i][j] != 0) { segment[i][e] = segment[i][j]+1; break; } } } } memo = new Integer[n][n]; System.out.print(solve(0, 0)); } static int solve(int i, int start) { if(i == n-1) { if(segment[start][i] != 0) { return 1; } return n; } if(memo[i][start] != null) { return memo[i][start]; } int min = n; if(segment[start][i] != 0) { min = Math.min(1+solve(i+1, i+1), solve(i+1, start)); } else { min = solve(i+1, start); } memo[i][start] = min; return min; } static class Reader { BufferedReader bufferedReader; StringTokenizer string; public Reader() { InputStreamReader inr = new InputStreamReader(System.in); bufferedReader = new BufferedReader(inr); } public String next() throws IOException { while(string == null || ! string.hasMoreElements()) { string = new StringTokenizer(bufferedReader.readLine()); } return string.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public String nextLine() throws IOException { return bufferedReader.readLine(); } } }
java
1311
E
E. Construct the Binary Treetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and dd. You need to construct a rooted binary tree consisting of nn vertices with a root at the vertex 11 and the sum of depths of all vertices equals to dd.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex vv is the last different from vv vertex on the path from the root to the vertex vv. The depth of the vertex vv is the length of the path from the root to the vertex vv. Children of vertex vv are all vertices for which vv is the parent. The binary tree is such a tree that no vertex has more than 22 children.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The only line of each test case contains two integers nn and dd (2≤n,d≤50002≤n,d≤5000) — the number of vertices in the tree and the required sum of depths of all vertices.It is guaranteed that the sum of nn and the sum of dd both does not exceed 50005000 (∑n≤5000,∑d≤5000∑n≤5000,∑d≤5000).OutputFor each test case, print the answer.If it is impossible to construct such a tree, print "NO" (without quotes) in the first line. Otherwise, print "{YES}" in the first line. Then print n−1n−1 integers p2,p3,…,pnp2,p3,…,pn in the second line, where pipi is the parent of the vertex ii. Note that the sequence of parents you print should describe some binary tree.ExampleInputCopy3 5 7 10 19 10 18 OutputCopyYES 1 2 1 3 YES 1 2 3 3 9 9 2 1 6 NO NotePictures corresponding to the first and the second test cases of the example:
[ "brute force", "constructive algorithms", "trees" ]
//package round624; 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() { for(int T = ni();T > 0;T--){ int n = ni(), d = ni(); int low = 0; for(int i = 0;i < n;i++){ low += Integer.numberOfTrailingZeros(Integer.highestOneBit(i+1)); } if(d < low || d > n*(n-1)/2){ out.println("NO"); }else{ out.println("YES"); int x = n*(n-1)/2; int[] par = new int[n]; for(int i = 1;i < n;i++){ par[i] = i-1; } int[] dep = new int[n]; int[] ch = new int[n]; for(int i = 0;i < n;i++){ ch[i] = i < n-1 ? 1 : 0; dep[i] = i; } out: for(int i = n-1;i >= 2 && x > d;i--){ int j = i-1; ch[par[i]]--; ch[i] = 0; while(x > d && j >= 1){ if(ch[j-1] == 2){ // tr("i", i, ch[n-1], dep[j-1]); for(int k = 0;k < n;k++){ if(k == i)continue; if(dep[k] == dep[j-1] && ch[k] < 2){ // tr("K", k); ch[j]--; par[i] = k; dep[i] = dep[k] + 1; x--; ch[k]++; continue out; } } break; } ch[j]--; j--; par[i] = j; ch[j]++; dep[i]--; x--; // tr(par, x, dep); } } assert x == d; for(int j = 1;j < n;j++){ out.print(par[j]+1 + " "); } out.println(); } } } 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
1316
E
E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j  — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres  — the maximum possible strength of the club.ExamplesInputCopy4 1 2 1 16 10 3 18 19 13 15 OutputCopy44 InputCopy6 2 3 78 93 9 17 13 78 80 97 30 52 26 17 56 68 60 36 84 55 OutputCopy377 InputCopy3 2 1 500 498 564 100002 3 422332 2 232323 1 OutputCopy422899 NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1.
[ "bitmasks", "dp", "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.ArrayList; import java.util.Objects; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.util.Collections; 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); ETeamBuilding solver = new ETeamBuilding(); solver.solve(1, in, out); out.close(); } static class ETeamBuilding { int n; int p; int k; int[] arr; int[][] s; long[][] dp; ArrayList<Pair> list; long[] psum; public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.nextInt(); p = in.nextInt(); k = in.nextInt(); arr = in.nextIntArray(n); s = in.nextIntMatrix(n, p); dp = new long[n][1 << p]; list = new ArrayList<>(); for (int i = 0; i < n; i++) { int a = arr[i]; list.add(new Pair(a, i)); } Collections.sort(list, Collections.reverseOrder()); psum = new long[n]; psum[0] = list.get(0).a; for (int i = 1; i < n; i++) { psum[i] = psum[i - 1] + list.get(i).a; } for (long[] r : dp) Arrays.fill(r, -1); out.println(rec(0, 0)); // for(long[] r:dp) out.println(r); } long rec(int i, int mask) { if (i >= n) return 0; if (dp[i][mask] != -1) return dp[i][mask]; // long ans = 0; if (i + 1 - Integer.bitCount(mask) <= k) { ans = Math.max(ans, rec(i + 1, mask) + list.get(i).a); } else { ans = Math.max(ans, rec(i + 1, mask)); } for (int j = 0; j < p; j++) { if (((1 << j) & mask) != 0) continue; ans = Math.max(ans, s[list.get(i).b][j] + rec(i + 1, mask | (1 << j))); } return dp[i][mask] = ans; } class Pair implements Comparable<Pair> { int a; int b; Pair(int a, int b) { this.a = a; this.b = b; } public int hashCode() { return Objects.hash(a, b); } public boolean equals(Object obj) { Pair that = (Pair) obj; return a == that.a && b == that.b; } public String toString() { return "[" + a + ", " + b + "]"; } public int compareTo(Pair v) { return a - v.a; } } } 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[] nextIntArray(int n) { int[] array = new int[n]; for (int i = 0; i < n; ++i) array[i] = nextInt(); return array; } public int nextInt() { return Integer.parseInt(next()); } public int[][] nextIntMatrix(int rows, int cols) { int[][] matrix = new int[rows][cols]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) matrix[i][j] = nextInt(); return matrix; } } 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); } } }
java
1295
A
A. Display The Numbertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a large electronic screen which can display up to 998244353998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 77 segments which can be turned on and off to compose different digits. The following picture describes how you can display all 1010 decimal digits:As you can see, different digits may require different number of segments to be turned on. For example, if you want to display 11, you have to turn on 22 segments of the screen, and if you want to display 88, all 77 segments of some place to display a digit should be turned on.You want to display a really large integer on the screen. Unfortunately, the screen is bugged: no more than nn segments can be turned on simultaneously. So now you wonder what is the greatest integer that can be displayed by turning on no more than nn segments.Your program should be able to process tt different test cases.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases in the input.Then the test cases follow, each of them is represented by a separate line containing one integer nn (2≤n≤1052≤n≤105) — the maximum number of segments that can be turned on in the corresponding testcase.It is guaranteed that the sum of nn over all test cases in the input does not exceed 105105.OutputFor each test case, print the greatest integer that can be displayed by turning on no more than nn segments of the screen. Note that the answer may not fit in the standard 3232-bit or 6464-bit integral data type.ExampleInputCopy2 3 4 OutputCopy7 11
[ "greedy" ]
import java.util.*; import java.io.*; public class coins { public static void main(String...args)throws IOException{ // Scanner sc=new Scanner(System.in); // BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); InputStreamReader r=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(r); int t=Integer.parseInt(br.readLine()); while(t-->0){ int n=Integer.parseInt(br.readLine()); int k=0; String str=""; int nine =0,seven=0,ct=0; ct=n/2; if(n%2!=0){ ct--; str=str+'7'; } while(ct-->0){ str+='1'; } System.out.println(str); } } }
java
1323
A
A. Even Subset Sum Problemtime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 22) or determine that there is no such subset.Both the given array and required subset may contain equal values.InputThe first line contains a single integer tt (1≤t≤1001≤t≤100), number of test cases to solve. Descriptions of tt test cases follow.A description of each test case consists of two lines. The first line contains a single integer nn (1≤n≤1001≤n≤100), length of array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), elements of aa. The given array aa can contain equal values (duplicates).OutputFor each test case output −1−1 if there is no such subset of elements. Otherwise output positive integer kk, number of elements in the required subset. Then output kk distinct integers (1≤pi≤n1≤pi≤n), indexes of the chosen elements. If there are multiple solutions output any of them.ExampleInputCopy3 3 1 4 3 1 15 2 3 5 OutputCopy1 2 -1 2 1 2 NoteThere are three test cases in the example.In the first test case; you can choose the subset consisting of only the second element. Its sum is 44 and it is even.In the second test case, there is only one non-empty subset of elements consisting of the first element, however sum in it is odd, so there is no solution.In the third test case, the subset consisting of all array's elements has even sum.
[ "brute force", "dp", "greedy", "implementation" ]
import java.util.*; public class Main { public static void main(String[] args) { Scanner inp = new Scanner(System.in); int n = inp.nextInt();//test cases ArrayList<int[]> list = new ArrayList<>(); for(int i =0 ; i < n ;i++){ int numbers= inp.nextInt(); int[] a = new int[numbers]; for(int j = 0 ; j<numbers;j++){ a[j]= inp.nextInt(); } list.add(a); } for(int i=0; i<list.size();i++){ ArrayList<Integer> ans = calc(list.get(i)); if(ans.size()==0){ System.out.println(-1); }else{ System.out.println(ans.size()); for(int x : ans){ System.out.print(x + " "); } System.out.println(); } } inp.close(); } public static ArrayList<Integer> calc(int[] a){ ArrayList<Integer> evens = new ArrayList<>(); for(int i = 0 ; i<a.length ; i++){ if(a[i] %2==0){ evens.add(i+1); return evens; }else { for(int j=i+1; j<a.length; j++){ if(a[j] % 2==1){ evens.add(i+1); evens.add(j+1); return evens; } } } } return new ArrayList<>(); } }
java
1305
G
G. Kuroni and Antihypetime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni isn't good at economics. So he decided to found a new financial pyramid called Antihype. It has the following rules: You can join the pyramid for free and get 00 coins. If you are already a member of Antihype, you can invite your friend who is currently not a member of Antihype, and get a number of coins equal to your age (for each friend you invite). nn people have heard about Antihype recently, the ii-th person's age is aiai. Some of them are friends, but friendship is a weird thing now: the ii-th person is a friend of the jj-th person if and only if ai AND aj=0ai AND aj=0, where ANDAND denotes the bitwise AND operation.Nobody among the nn people is a member of Antihype at the moment. They want to cooperate to join and invite each other to Antihype in a way that maximizes their combined gainings. Could you help them? InputThe first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105)  — the number of people.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤2⋅1050≤ai≤2⋅105)  — the ages of the people.OutputOutput exactly one integer  — the maximum possible combined gainings of all nn people.ExampleInputCopy3 1 2 3 OutputCopy2NoteOnly the first and second persons are friends. The second can join Antihype and invite the first one; getting 22 for it.
[ "bitmasks", "brute force", "dp", "dsu", "graphs" ]
import java.util.*; import java.io.*; import java.math.*; public class CodeForces { public static void main(String hi[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); int[] arr = new int[N]; st = new StringTokenizer(infile.readLine()); for(int i=0; i < N; i++) arr[i] = Integer.parseInt(st.nextToken()); int[] freq = new int[1<<18]; for(int x: arr) freq[x]++; freq[0]++; //dummy root DSU union = new DSU(); long res = 0L; matcha:for(int mask=(1<<18)-1; mask >= 0; mask--) for(int temp=mask; temp > 0; temp=(temp-1)&mask) { int submask = mask^temp; if(submask > temp) break; if(freq[temp] > 0 && freq[submask] > 0 && union.find(temp) != union.find(submask)) { res += (long)(freq[temp]+freq[submask]-1)*mask; freq[temp] = freq[submask] = 1; //one subtree each union.merge(temp, submask); } } for(int x: arr) res -= x; System.out.println(res); } } class DSU { public int[] dsu; public DSU() { dsu = new int[1<<18]; for(int i=0; i < (1<<18); i++) dsu[i] = i; } public int find(int x) { return dsu[x] == x ? x : (dsu[x] = find(dsu[x])); } public void merge(int x, int y) { int fx = find(x); int fy = find(y); dsu[fx] = fy; } }
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.util.*; import java.io.*; import javafx.util.Pair; public class F617 { static int memo[][]; static int [] depth; static int [] parent; static ArrayList<Integer> [] adj; static int log; public static void main(String [] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); adj = new ArrayList [n + 1]; log = (int)Math.ceil(Math.log(n) / Math.log(2)); memo = new int[n + 1][log + 1]; depth = new int[n + 1]; parent = new int [n+1]; for (int i = 0; i <= n; i++) Arrays.fill(memo[i], -1); for (int i = 1; i <= n; i++) adj[i] = new ArrayList<>(); Pair<Integer, Integer> [] edges = new Pair [n-1]; for (int i = 0; i < n - 1; i++) { int a = sc.nextInt(); int b = sc.nextInt(); adj[a].add(b); adj[b].add(a); edges[i] = new Pair(a, b); } dfs(1, 1); int m = sc.nextInt(); Query [] queries = new Query[m]; for (int i = 0; i < m; i++) { int a = sc.nextInt(); int b = sc.nextInt(); int g = sc.nextInt(); queries[i] = new Query(a, b, g); } Arrays.sort(queries); int [] bound = new int [n+1]; boolean ans = true; for (int i = 0; i < m; i++) { int start1 = queries[i].a; int start2 = queries[i].b; int beaut = queries[i].beauty; int lca = lca(start1, start2); boolean changed = false; while (start1 != lca) { int temp = bound[start1]; bound[start1] = Math.max(bound[start1], beaut); if (bound[start1] != temp || temp == beaut) changed = true; start1 = parent[start1]; } while (start2 != lca) { int temp = bound[start2]; bound[start2] = Math.max(bound[start2], beaut); if (bound[start2] != temp || temp == beaut) changed = true; start2 = parent[start2]; } if (!changed) ans = false; } HashSet<Integer> set = new HashSet<>(); for (int i = 2; i <= n; i++) set.add(bound[i]); for (int i = 0; i < m; i++) { if (!set.contains(queries[i].beauty)) { ans = false; break; } } if (ans) { for (int i = 0; i < n -1; i++) { Integer a = edges[i].getKey(); Integer b = edges[i].getValue(); if (parent[a] == b) { out.print(bound[a] == 0 ? 1 + " " : bound[a] + " "); } else { out.print(bound[b] == 0 ? 1 + " " : bound[b] + " "); } } } else { out.println(-1); } out.close(); } static class Query implements Comparable<Query> { int a; int b; int beauty; Query(int a , int b, int beauty) { this.a = a; this.b = b; this.beauty = beauty; } public int compareTo(Query q) { return q.beauty - beauty; } } static void dfs(int u, int p) { // Using recursion formula to calculate // the values of memo[][] parent[u] = p; memo[u][0] = p; for (int i = 1; i <= log; i++) memo[u][i] = memo[memo[u][i - 1]][i - 1]; for (int v : adj[u]) { if (v != p) { // Calculating the level of each node depth[v] = depth[u] + 1; dfs(v, u); } } } static int lca(int u, int v) { // The node which is present farthest // from the root node is taken as u // If v is farther from root node // then swap the two if (depth[u] < depth[v]) { int temp = u; u = v; v = temp; } // Finding the ancestor of u // which is at same level as v for (int i = log; i >= 0; i--) { if ((depth[u] - (int)Math.pow(2, i)) >= depth[v]) u = memo[u][i]; } // If v is the ancestor of u // then v is the LCA of u and v if (u == v) return u; // Finding the node closest to the root which is // not the common ancestor of u and v i.e. a node // x such that x is not the common ancestor of u // and v but memo[x][0] is for (int i = log; i >= 0; i--) { if (memo[u][i] != memo[v][i]) { u = memo[u][i]; v = memo[v][i]; } } // Returning the first ancestor // of above found node return memo[u][0]; } //-----------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
1320
E
E. Treeland and Virusestime limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThere are nn cities in Treeland connected with n−1n−1 bidirectional roads in such that a way that any city is reachable from any other; in other words, the graph of cities and roads is a tree. Treeland is preparing for a seasonal virus epidemic, and currently, they are trying to evaluate different infection scenarios.In each scenario, several cities are initially infected with different virus species. Suppose that there are kiki virus species in the ii-th scenario. Let us denote vjvj the initial city for the virus jj, and sjsj the propagation speed of the virus jj. The spread of the viruses happens in turns: first virus 11 spreads, followed by virus 22, and so on. After virus kiki spreads, the process starts again from virus 11.A spread turn of virus jj proceeds as follows. For each city xx not infected with any virus at the start of the turn, at the end of the turn it becomes infected with virus jj if and only if there is such a city yy that: city yy was infected with virus jj at the start of the turn; the path between cities xx and yy contains at most sjsj edges; all cities on the path between cities xx and yy (excluding yy) were uninfected with any virus at the start of the turn.Once a city is infected with a virus, it stays infected indefinitely and can not be infected with any other virus. The spread stops once all cities are infected.You need to process qq independent scenarios. Each scenario is described by kiki virus species and mimi important cities. For each important city determine which the virus it will be infected by in the end.InputThe first line contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Treeland.The following n−1n−1 lines describe the roads. The ii-th of these lines contains two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — indices of cities connecting by the ii-th road. It is guaranteed that the given graph of cities and roads is a tree.The next line contains a single integer qq (1≤q≤2⋅1051≤q≤2⋅105) — the number of infection scenarios. qq scenario descriptions follow.The description of the ii-th scenario starts with a line containing two integers kiki and mimi (1≤ki,mi≤n1≤ki,mi≤n) — the number of virus species and the number of important cities in this scenario respectively. It is guaranteed that ∑qi=1ki∑i=1qki and ∑qi=1mi∑i=1qmi do not exceed 2⋅1052⋅105.The following kiki lines describe the virus species. The jj-th of these lines contains two integers vjvj and sjsj (1≤vj≤n1≤vj≤n, 1≤sj≤1061≤sj≤106) – the initial city and the propagation speed of the virus species jj. It is guaranteed that the initial cities of all virus species within a scenario are distinct.The following line contains mimi distinct integers u1,…,umiu1,…,umi (1≤uj≤n1≤uj≤n) — indices of important cities.OutputPrint qq lines. The ii-th line should contain mimi integers — indices of virus species that cities u1,…,umiu1,…,umi are infected with at the end of the ii-th scenario.ExampleInputCopy7 1 2 1 3 2 4 2 5 3 6 3 7 3 2 2 4 1 7 1 1 3 2 2 4 3 7 1 1 3 3 3 1 1 4 100 7 100 1 2 3 OutputCopy1 2 1 1 1 1 1
[ "data structures", "dfs and similar", "dp", "shortest paths", "trees" ]
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeMap; public class C1320E { public static void main(String[] args) { var scanner = new BufferedScanner(); var writer = new PrintWriter(new BufferedOutputStream(System.out)); var n = scanner.nextInt(); // edges var edges = new HashMap<Integer, List<Integer>>(); for (int i = 0; i < n - 1; i++) { var x = scanner.nextInt(); var y = scanner.nextInt(); edges.putIfAbsent(x, new ArrayList<>()); edges.get(x).add(y); edges.putIfAbsent(y, new ArrayList<>()); edges.get(y).add(x); } var order = new int[n + 1]; // 原编号->新编号 var depth = new int[n + 1]; // 下标是原编号 var jump = new int[n + 1][(int) (Math.log(n + 1) / Math.log(2)) + 2]; // 第1维下标是原编号 prepare(n, edges, order, depth, jump); var q = scanner.nextInt(); var virusInit = new int[n + 1]; var spread = new int[n + 1]; for (int i = 0; i < q; i++) { var k = scanner.nextInt(); var m = scanner.nextInt(); // virus var cs = new HashSet<Integer>(); var infected = new HashMap<Integer, Integer>(); for (int j = 1; j <= k; j++) { // start city var v = scanner.nextInt(); // all different // spreading speed var s = scanner.nextInt(); virusInit[j] = v; spread[j] = s; infected.put(v, j); cs.add(v); } // important cities var important = new ArrayList<Integer>(); for (int j = 0; j < m; j++) { int u = scanner.nextInt(); important.add(u); } cs.addAll(important); var cities = new ArrayList<>(cs); cities.sort(Comparator.comparingInt(o -> order[o])); hardcore(depth, jump, virusInit, cities, spread, infected); for (int j = 0; j < m; j++) { writer.print(infected.get(important.get(j)) + " "); } writer.println(); } scanner.close(); writer.flush(); writer.close(); } private static void hardcore(int[] depth, int[][] jump, int[] virusInit, List<Integer> cities, int[] spread, Map<Integer, Integer> infected) { if (cities.size() == 1) { return; } // 从下到上来一遍 // var lcaFrom = new HashMap<Integer, Set<Integer>>(); var lcaFrom = new TreeMap<Integer, Set<Integer>>( Comparator.comparingInt(i -> depth[(int) i]).thenComparingInt(i -> (int) i)); var stack = new LinkedList<int[]>(); stack.push(new int[]{cities.get(0), cities.get(1), lca(cities.get(0), cities.get(1), depth, jump)}); for (int i = 2; i < cities.size(); i++) { var lca = lca(cities.get(i - 1), cities.get(i), depth, jump); var c = cities.get(i - 1); // 确保栈中lca深度是递增的 while (stack.size() > 0 && depth[lca] <= depth[stack.peek()[2]]) { var top = stack.pop(); infectUp(top[0], c, top[2], depth, virusInit, spread, infected); // infect(top[0], c, top[2], depth, jump, virusInit, spread, infected); lcaFrom.putIfAbsent(top[2], new HashSet<>()); lcaFrom.get(top[2]).add(top[0]); lcaFrom.get(top[2]).add(c); c = top[2]; } stack.push(new int[]{c, cities.get(i), lca}); } if (stack.size() > 0) { var c = stack.peek()[1]; while (stack.size() > 0) { var top = stack.pop(); infectUp(top[0], c, top[2], depth, virusInit, spread, infected); // infect(top[0], c, top[2], depth, jump, virusInit, spread, infected); lcaFrom.putIfAbsent(top[2], new HashSet<>()); lcaFrom.get(top[2]).add(top[0]); lcaFrom.get(top[2]).add(c); c = top[2]; } } // 从上到下来一遍 // var lcaList = new ArrayList<>(lcaFrom.keySet()); // lcaList.sort(Comparator.comparingInt(o -> depth[o])); // for (var lca : lcaList) { for (var lca : lcaFrom.keySet()) { for (var child : lcaFrom.get(lca)) { if (lca.equals(child)) { continue; } infect(lca, child, child, depth, jump, virusInit, spread, infected); } } } static int infinite = Integer.MAX_VALUE; private static void infect(int a, int b, int target, int[] depth, int[][] jump, int[] virusInit, int[] spread, Map<Integer, Integer> infected) { var va = infected.getOrDefault(a, 0); var vb = infected.getOrDefault(b, 0); var turnsA = turns(dist(virusInit[va], target, depth, jump), spread[va]); var turnsB = turns(dist(virusInit[vb], target, depth, jump), spread[vb]); if (turnsA == infinite && turnsB == infinite) { // 什么都不做 } else if (better(turnsA, va, turnsB, vb)) { infected.put(target, va); } else { infected.put(target, vb); } } private static boolean better(int turnsA, int va, int turnsB, int vb) { return turnsA < turnsB || turnsA == turnsB && va < vb; } private static int dist(int a, int b, int[] depth, int[][] jump) { var lca = lca(a, b, depth, jump); return depth[a] - depth[lca] + depth[b] - depth[lca]; } private static void infectUp(int a, int b, int lca, int[] depth, int[] virusInit, int[] spread, Map<Integer, Integer> infected) { var va = infected.getOrDefault(a, 0); var vb = infected.getOrDefault(b, 0); // 在沿着树向根走的过程中,initA和initB分别是a和b的孩子,所以也都是lca的孩子。 var turnsA = turns(depth[virusInit[va]] - depth[lca], spread[va]); var turnsB = turns(depth[virusInit[vb]] - depth[lca], spread[vb]); if (turnsA == infinite && turnsB == infinite) { // 什么都不做 } else if (better(turnsA, va, turnsB, vb)) { infected.put(lca, va); } else { infected.put(lca, vb); } } private static int turns(int dist, int speed) { return speed == 0 ? infinite : Math.floorDiv(dist - 1, speed) + 1; } private static int lca(int a, int b, int[] depth, int[][] jump) { if (depth[a] < depth[b]) { return lca(b, a, depth, jump); } // 先保持depth一致 { var i = jump[a].length - 1; while (depth[a] > depth[b]) { while (jump[a][i] == 0 || depth[jump[a][i]] < depth[b]) { i--; } a = jump[a][i]; } } // 再开始找lca { var i = jump[a].length - 1; while (a != b) { while (i > 0 && jump[a][i] == jump[b][i]) { i--; } a = jump[a][i]; b = jump[b][i]; } } return a; } /** * 做4件事: * <p> * 1)确定节点1为根。 * <p> * 2)重新给节点排序,使得同一颗子树的节点彼此紧挨着,可以用一个区间表示;任何子树的根一定在子树其他节点的前面。 * <p> * 3)计算每个节点的深度。 * <p> * 4)计算每个节点往根节点方向的跳跃表。 */ private static void prepare(int n, Map<Integer, List<Integer>> edges, int[] order, int[] depth, int[][] jump) { var q = new LinkedList<Integer>(); var parent = new int[n + 1]; q.add(1); depth[1] = 0; parent[1] = 0; var o = 1; while (q.size() > 0) { var h = q.poll(); order[h] = o++; var children = edges.get(h); if (children == null) { continue; } for (var next : children) { if (order[next] == 0) { q.addFirst(next); depth[next] = depth[h] + 1; parent[next] = h; calcJump(next, parent, jump); } } } } private static void calcJump(int start, int[] parent, int[][] jump) { var i = 0; jump[start][i] = parent[start]; var x = parent[start]; while (x > 0) { i++; jump[start][i] = jump[x][i - 1]; x = jump[x][i - 1]; } } public static class BufferedScanner { BufferedReader br; StringTokenizer st; public BufferedScanner(Reader reader) { br = new BufferedReader(reader); } public BufferedScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } static long gcd(long a, long b) { if (a < b) { return gcd(b, a); } while (b > 0) { long tmp = b; b = a % b; a = tmp; } return a; } static long inverse(long a, long m) { long[] ans = extgcd(a, m); return ans[0] == 1 ? (ans[1] + m) % m : -1; } private static long[] extgcd(long a, long m) { if (m == 0) { return new long[]{a, 1, 0}; } else { long[] ans = extgcd(m, a % m); long tmp = ans[1]; ans[1] = ans[2]; ans[2] = tmp; ans[2] -= ans[1] * (a / m); return ans; } } private static List<Integer> primes(double upperBound) { var limit = (int) Math.sqrt(upperBound); var isComposite = new boolean[limit + 1]; var primes = new ArrayList<Integer>(); for (int i = 2; i <= limit; i++) { if (isComposite[i]) { continue; } primes.add(i); int j = i + i; while (j <= limit) { isComposite[j] = true; j += i; } } return primes; } }
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.*; public class Main { public static void main(String[] args){ Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t>0){ int n=sc.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++){ a[i]=sc.nextInt(); } Arrays.sort(a); int c=n; for(int i=0;i<n-1;i++){ if(a[i]==a[i+1]){ c--; } } System.out.println(c); t=t-1; } } }
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.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.List; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ 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); BAromasSearch solver = new BAromasSearch(); solver.solve(1, in, out); out.close(); } static class BAromasSearch { public void solve(int testNumber, InputReader in, OutputWriter out) { long x0 = in.nextLong(); long y0 = in.nextLong(); long ax = in.nextLong(); long ay = in.nextLong(); long bx = in.nextLong(); long by = in.nextLong(); long xs = in.nextLong(); long ys = in.nextLong(); long t = in.nextLong(); long lim = Long.MAX_VALUE / 2; List<Long> x = new ArrayList<>(); List<Long> y = new ArrayList<>(); x.add(x0); y.add(y0); int n = 1; while ((lim - bx) / ax >= x.get(n - 1) && (lim - by) / ay >= y.get(n - 1)) { x.add(ax * x.get(n - 1) + bx); y.add(ay * y.get(n - 1) + by); n++; } int res = 0; for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { long len = x.get(j) - x.get(i) + y.get(j) - y.get(i); long left = Math.abs(xs - x.get(i)) + Math.abs(ys - y.get(i)); long right = Math.abs(xs - x.get(j)) + Math.abs(ys - y.get(j)); if (t - left >= len || t - right >= len) { res = Math.max(res, j - i + 1); } } } out.println(res); } } 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 long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return 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 OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(int i) { writer.println(i); } } }
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.*; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.math.BigInteger; public class Main{ static class Node { long sum, pre; Node(long a, long b) { this.sum = a; this.pre = b; } } static class SegmentTree { int l , r; // range responsible for SegmentTree left , right; long val; SegmentTree(int l,int r,long a[]) { this.l = l; this.r = r; // list= new ArrayList<>(); if(l == r) { val = a[l]; return ; } int mid = l + (r-l)/2; this.left = new SegmentTree(l ,mid , a); this.right = new SegmentTree(mid + 1 , r,a); this.val = Math.max(this.left.val , this.right.val); } public long query(int left ,int right) { if(this.l > right || this.r < left) { return 0l; } if(this.l >= left && this.r <= right) { return this.val; } return this.left.query(left , right ) + this.right.query(left , right ); } // public void pointUpdate(int index , long val) { // if(this.l > index || this.r < index) return; // if(this.l == this.r && this.l == index) { // this.val = val; // return ; // } // this.left.pointUpdate(index ,val); // this.right.pointUpdate(index , val); // this.val = join(this.left.val , this.right.val); // } // public void rangeUpdate(int left , int right,long val) { // if(this.l > right || this.r < left) return ; // if(this.l >= left && this.r <= right) { // this.val += val; // } // if(this.l == this.r) return; // this.left.rangeUpdate(left , right , val); // this.right.rangeUpdate(left , right , val); // } // public long valueAtK(int k) { // if(this.l > k || this.r < k) return 0; // if(this.l == this.r && this.l == k) { // return this.val; // } // return join(this.left.valueAtK(k) , this.right.valueAtK(k)); // } public int join(int a ,int b) { return a + b; } } static class Hash { long hash[] ,mod = (long)1e9 + 7 , powT[] , prime , inverse[]; Hash(char []s) { prime = 131; int n = s.length; powT = new long[n]; hash = new long[n]; inverse = new long[n]; powT[0] = 1; inverse[n-1] = pow(pow(prime , n-1 ,mod), mod-2 , mod); for(int i = 1;i < n; i++ ) { powT[i] = (powT[i-1]*prime)%mod; } for(int i = n-2; i>= 0;i-=1) { inverse[i] = (inverse[i+1]*prime)%mod; } hash[0] = (s[0] - 'a' + 1); for(int i = 1; i < n;i++ ) { hash[i] = hash[i-1] + ((s[i]-'a' + 1)*powT[i])%mod; hash[i] %= mod; } } public long hashValue(int l , int r) { if(l == 0) return hash[r]%mod; long ans = hash[r] - hash[l-1] +mod; ans %= mod; // System.out.println(inverse[l] + " " + pow(powT[l], mod- 2 , mod)); ans *= inverse[l]; ans %= mod; return ans; } } static class ConvexHull { Stack<Integer>stack; Stack<Integer>stack1; int n; Point arr[]; ConvexHull(Point arr[]) { n = arr.length; this.arr = arr; Arrays.sort(arr , (a , b)-> { if(a.x == b.x) return (int)(b.y-a.y); return (int)(a.x-b.x); }); Point min = arr[0]; stack = new Stack<>(); stack1 = new Stack<>(); stack.push(0); stack1.push(0); Point ob = new Point(2,2); for(int i =1;i < n;i++) { if(stack.size() < 2) stack.push(i); else { while(stack.size() >= 2) { int a = stack.pop() , b = stack.pop() ,c = i; int dir = ob.cross(arr[b] , arr[a] , arr[c]); if(dir < 0) { stack.push(b); stack.push(a); stack.push(c); break; } stack.push(b); } if(stack.size() < 2) { stack.push(i); } } } for(int i =1;i < n;i++) { if(stack1.size() < 2) stack1.push(i); else { while(stack1.size() >= 2) { int a = stack1.pop() , b = stack1.pop() ,c = i; int dir = ob.cross(arr[b] , arr[a] , arr[c]); if(dir > 0) { stack1.push(b); stack1.push(a); stack1.push(c); break; } stack1.push(b); } if(stack1.size() < 2) { stack1.push(i); } } } } public List<Point> getPoints() { boolean vis[] = new boolean[n]; List<Point> list = new ArrayList<>(); // for(int x : stack) { // list.add(arr[x]); // vis[x] = true; // } for(int x : stack1) { // if(vis[x]) continue; list.add(arr[x]); } return list; } } 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); } } static class Point { long x , y; Point(long x , long y) { this.x = x; this.y = y; } public String toString() { return this.x + " " + this.y; } public Point sub(Point a,Point b) { return new Point(a.x - b.x , a.y-b.y); } public int cross(Point a ,Point b , Point c) { Point g = sub(b,a) , l = sub(c, b); long ans = g.y*l.x - g.x*l.y; if(ans == 0) return 0; if(ans < 0) return -1; return 1; } } 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(new FileWriter(problemName + ".out")); r = new BufferedReader(new FileReader(problemName + ".in")); } // returns null if no more input 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 Kattio sc = new Kattio(); static long mod = 998244353l; // static Kattio out = new Kattio(); //Heapify function to maintain heap property. public static void swap(int i,int j,int arr[]) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } public static long max(long ...a) { return maxArray(a); } public static void swap(int i,int j,long arr[]) { long temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } public static void swap(int i,int j,char arr[]) { char temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static String endl = "\n" , gap = " "; static int size[]; static int parent[]; static HashMap<Integer , Long> value; // static HashMap<String , Boolean > dp; // static HashMap<Integer , List<int[]>> graph; static boolean vis[]; static int answer; static HashSet<String> guess; static long primePow[]; // static long dp[]; static int N; static int dis[]; static int height[]; static long p[]; // static long fac[]; // static long inv[]; static HashMap<Integer ,List<Integer>> graph; public static long rd() { return (long)((Math.random()*10) + 1); } public static void main(String[] args)throws IOException { long t = 1; // List<Integer> list = new ArrayList<>(); // int MAX = (int)4e4; // for(int i =1;i<=MAX;i++) { // if(isPalindrome(i + "")) list.add(i); // } // // System.out.println(list); // long dp[] = new long[MAX +1]; // dp[0] = 1; // long mod = (long)(1e9+7); // for(int x : list) { // for(int i =1;i<=MAX;i++) { // if(i >= x) { // dp[i] += dp[i-x]; // dp[i] %= mod; // } // } // } // int MAK = (int)1e6 + 10; // boolean seive[] = new boolean[MAK]; // Arrays.fill(seive , true); // seive[1] = false; // seive[0] = false; // for (int i = 1; i < MAK; i++) { // if(seive[i]) { // for (int j = i+i; j < MAK; j+=i) { // seive[j] = false; // } // } // } // TreeSet<Long>primeSet = new TreeSet<>(); // for(long i = 2;i <= (long)1e6;i++) { // if(seive[(int)i])primeSet.add(i); // } // List<Integer> list = new ArrayList<>(); // for (int i = 1; i < seive.length; i++) { // if(seive[i]) list.add(i); // } int test_case = 1; while(t-->0) { // sc.print("Case #"+(test_case++)+": "); solve(); } sc.close(); } static int endTime[]; static int time; public static int dis(int a[] , int b[]) { return (a[0]-b[0])*(a[0]-b[0]) + (a[1]-b[1])*(a[1]-b[1]); } // static Long dp[][][]; static long fac[], inv[]; public static long ncr(int a , int b) { if(a == b) return 1l; return (((fac[a]*inv[b])%mod)*inv[a-b])%mod; } static Long dp[][]; public static void solve() throws IOException { char s[] = rac(); long ans = 0; int cnt[] = new int[26]; int n = s.length; for(char ch : s) cnt[ch-'a']++; for(int i =0;i < 26;i++) ans = Math.max(ans ,cnt[i]); HashMap<String ,Long> map = new HashMap<>(); for(int i = 0;i < n;i++) { cnt[s[i]-'a']--; for(char c = 'a';c <= 'z';c++) { String g = s[i]+""+c; map.put(g , map.getOrDefault(g , 0l) + cnt[c-'a']); } } for(String k : map.keySet()) ans = Math.max(ans , map.get(k)); System.out.println(ans); } public static void print(PriorityQueue<long[]> que ) { for(long a[] : que) { System.out.print(a[1] + " "); } System.out.println(); } public static String slope(Point a , Point b) { if((a.x-b.x) == 0) return "inf"; long n = a.y- b.y; if(n == 0) return "0"; long m = a.x-b.x; boolean neg = (n*m < 0?true:false); n = Math.abs(n); m = Math.abs(m); long g = gcd(Math.abs(n),Math.abs(m)); n /= g; m /= g; String ans = n+"/"+m; if(neg) ans = "-" + ans; return ans; } public static int lis(int A[], int size) { int[] tailTable = new int[size]; int len; tailTable[0] = A[0]; len = 1; for (int i = 1; i < size; i++) { if (A[i] < tailTable[0]) tailTable[0] = A[i]; else if (A[i] > tailTable[len - 1]) tailTable[len++] = A[i]; else tailTable[CeilIndex(tailTable, -1, len - 1, A[i])] = A[i]; } return len; } public static int CeilIndex(int A[], int l, int r, int key) { while (r - l > 1) { int m = l + (r - l) / 2; if (A[m] >= key) r = m; else l = m; } return r; } public static int lcs(char a[] , char b[]) { int n = a.length , m = b.length; int dp[][] = new int[n + 1][m + 1]; for(int i =1;i <= n;i++) { for(int j =1;j <= m;j++) { if(a[i-1] == b[j-1]) dp[i][j] = 1 + dp[i-1][j-1]; else dp[i][j] = Math.max(dp[i-1][j] , dp[i][j-1]); } } return dp[n][m]; } public static int find(int node) { if(node == parent[node]) return node; return parent[node] = find(parent[node]); } public static void merge(int a ,int b ) { a = find(a); b = find(b); if(a == b) return; if(size[a] >= size[b]) { parent[b] = a; size[a] += size[b]; // primePow[a] += primePow[b]; // primePow[b] = 0; } else { parent[a] = b; size[b] += size[a]; // primePow[b] += primePow[a]; // primePow[a] = 0; } } public static void processPowerOfP(long arr[]) { int n = arr.length; arr[0] = 1; long mod = (long)1e9 + 7; for(int i =1;i<n;i++) { arr[i] = arr[i-1]*51; arr[i] %= mod; } } public static long hashValue(char s[]) { int n = s.length; long powerOfP[] = new long[n]; processPowerOfP(powerOfP); long ans =0; long mod = (long)1e9 + 7; for(int i =0;i<n;i++) { ans += (s[i]-'a'+1)*powerOfP[i]; ans %= mod; } return ans; } public static void dfs(int r,int c,char arr[][]) { int n = arr.length , m = arr[0].length; arr[r][c] = '#'; for(int i =0;i<4;i++) { int nr = r + colx[i] , nc = c + coly[i]; if(nr < 0 || nc < 0 || nc >= m || nr>=n) continue; if(arr[nr][nc] == '#') continue; dfs(nr,nc,arr); } } public static double getSlope(int a , int b,int x,int y) { if(a-x == 0) return Double.MAX_VALUE; if(b-y == 0) return 0.0; return ((double)b-(double)y)/((double)a-(double)x); } public static boolean collinearr(long a[] , long b[] , long c[]) { return (b[1]-a[1])*(b[0]-c[0]) == (b[0]-a[0])*(b[1]-c[1]); } public static boolean isSquare(long sum) { long root = (int)Math.sqrt(sum); return root*root == sum; } 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; } public static boolean isPalindrome(String s) { int i =0 , j = s.length() -1; while(i <= j && s.charAt(i) == s.charAt(j)) { i++; j--; } return i>j; } // digit dp hint; public static long callfun(String num , int N, int last ,int secondLast ,int bound ,long dp[][][][]) { if(N == 1) { if(last == -1 || secondLast == -1) return 0; long answer = 0; int max = (bound==1)?(num.charAt(num.length()-N)-'0') : 9; for(int i = 0;i<=max;i++) { if(last > secondLast && last > i) { answer++; } if(last < secondLast && last < i) { answer++; } } return answer; } if(secondLast == -1 || last == -1 ){ long answer = 0l; int max = (bound==1)?(num.charAt(num.length()-N)-'0') : 9; for(int i =0;i<=max;i++) { int nl , nsl , newbound = bound==0?0:i==max?1:0; if(last == - 1&& secondLast == -1 && i == 0) { nl = -1 ; nsl = -1; } else { nl = i;nsl = last; } long temp = callfun(num , N-1 , nl , nsl ,newbound, dp); answer += temp; if(last != -1 && secondLast != -1 &&((last > secondLast && last > i)||(last < secondLast && last < i))) answer++; } return answer; } if(dp[N][last][secondLast][bound] != -1) return dp[N][last][secondLast][bound]; long answer = 0l; int max = (bound==1)?(num.charAt(num.length()-N)-'0') : 9; for(int i =0;i<=max;i++) { int nl , nsl , newbound = bound==0?0:i==max?1:0; if(last == - 1&& secondLast == -1 && i == 0) { nl = -1 ; nsl = -1; } else { nl = i;nsl = last; } long temp = callfun(num , N-1 , nl , nsl ,newbound,dp); answer += temp; if(last != -1 && secondLast != -1 &&((last > secondLast && last > i)||(last < secondLast && last < i))) answer++; } return dp[N][last][secondLast][bound] = answer; } public static Long callfun(int index ,int pair,int arr[],Long dp[][]) { long mod = 998244353l; if(index >= arr.length) return 1l; if(dp[index][pair] != null) return dp[index][pair]; Long sum = 0l , ans = 0l; if(arr[index]%2 == pair) { return dp[index][pair] = callfun(index + 1,pair^1 , arr,dp)%mod + callfun(index + 1 ,pair , arr , dp)%mod; } else { return dp[index][pair] = callfun(index + 1,pair , arr,dp)%mod; } // for(int i =index;i<arr.length;i++) { // sum += arr[i]; // if(sum%2 == pair) { // ans = ans + callfun(i + 1,pair^1,arr , dp)%mod; // ans%=mod; // } // } // return dp[index][pair] = ans; } public static boolean callfun(int index , int n,int neg , int pos , String s) { if(neg < 0 || pos < 0) return false; if(index >= n) return true; if(s.charAt(0) == 'P') { if(neg <= 0) return false; return callfun(index + 1,n , neg-1 , pos , s.charAt(1) + "N"); } else { if(pos <= 0) return false; return callfun(index + 1 , n , neg , pos-1 , s.charAt(1) + "P"); } } public static void getPerm(int n , char arr[] , String s ,List<String>list) { if(n == 0) { list.add(s); return; } for(char ch : arr) { getPerm(n-1 , arr , s+ ch,list); } } public static int getLen(int i ,int j , char s[]) { while(i >= 0 && j < s.length && s[i] == s[j]) { i--; j++; } i++; j--; if(i>j) return 0; return j-i + 1; } public static int getMaxCount(String x) { char s[] = x.toCharArray(); int max = 0; int n = s.length; for(int i =0;i<n;i++) { max = Math.max(max,Math.max(getLen(i , i,s) , getLen(i ,i+1,s))); } return max; } public static double getDis(int arr[][] , int x, int y) { double ans = 0.0; for(int a[] : arr) { int x1 = a[0] , y1 = a[1]; ans += Math.sqrt((x-x1)*(x-x1) + (y-y1)*(y-y1)); } return ans; } public static boolean valid(String x ) { if(x.length() == 0) return true; if(x.length() == 1) return false; char s[] = x.toCharArray(); if(x.length() == 2) { if(s[0] == s[1]) { return false; } return true; } int r = 0 , b = 0; for(char ch : x.toCharArray()) { if(ch == 'R') r++; else b++; } return (r >0 && b >0); } public static void primeDivisor(HashMap<Long , Long >cnt , long num) { for(long i = 2;i*i<=num;i++) { while(num%i == 0) { cnt.put(i ,(cnt.getOrDefault(i,0l) + 1)); num /= i; } } if(num > 2) { cnt.put(num ,(cnt.getOrDefault(num,0l) + 1)); } } public static boolean isSubsequene(char a[], char b[] ) { int i =0 , j = 0; while(i < a.length && j <b.length) { if(a[i] == b[j]) { j++; } i++; } return j >= b.length; } public static long fib(int n ,long M) { if (n == 0) { return 0; } else if (n == 1) { return 1; } else { long[][] mat = {{1, 1}, {1, 0}}; mat = pow(mat, n-1 , M); return mat[0][0]; } } public static long[][] pow(long[][] mat, int n ,long M) { if (n == 1) return mat; else if (n % 2 == 0) return pow(mul(mat, mat , M), n/2 , M); else return mul(pow(mul(mat, mat,M), n/2,M), mat , M); } static long[][] mul(long[][] p, long[][] q,long M) { long a = (p[0][0]*q[0][0] + p[0][1]*q[1][0])%M; long b = (p[0][0]*q[0][1] + p[0][1]*q[1][1])%M; long c = (p[1][0]*q[0][0] + p[1][1]*q[1][0])%M; long d = (p[1][0]*q[0][1] + p[1][1]*q[1][1])%M; return new long[][] {{a, b}, {c, d}}; } public static long[] kdane(long arr[]) { int n = arr.length; long dp[] = new long[n]; dp[0] = arr[0]; long ans = dp[0]; for(int i = 1;i<n;i++) { dp[i] = Math.max(dp[i-1] + arr[i] , arr[i]); ans = Math.max(ans , dp[i]); } return dp; } public static void update(int low , int high , int l , int r, int val , int treeIndex ,int tree[]) { if(low > r || high < l || high < low) return; if(l <= low && high <= r) { System.out.println("At " +low + " and " + high + " ans ttreeIndex " + treeIndex); tree[treeIndex] += val; return; } int mid = low + (high - low)/2; update(low , mid , l , r , val , treeIndex*2 + 1, tree); update(mid + 1 , high , l , r , val , treeIndex*2 + 2 , tree); } // static int colx[] = {1 ,1, -1,-1 , 2,2,-2,-2}; // static int coly[] = {-2 ,2, 2,-2,1,-1,1,-1}; static int colx[] = {1 ,-1, 0,0 , 1,1,-1,-1}; static int coly[] = {0 ,0, 1,-1,1,-1,1,-1}; public static void reverse(char arr[]) { int i =0 , j = arr.length-1; while(i < j) { swap(i , j , arr); i++; j--; } } public static void reverse(long arr[]) { int i =0 , j = arr.length-1; while(i < j) { swap(i , j , arr); i++; j--; } } public static void reverse(int arr[]) { int i =0 , j = arr.length-1; while(i < j) { swap(i , j , arr); i++; j--; } } public static long inverse(long x , long mod) { return pow(x , mod -2 , mod); } public static int maxArray(int arr[]) { int ans = arr[0] , n = arr.length; for(int i =1;i<n;i++) { ans = Math.max(ans , arr[i]); } return ans; } public static long maxArray(long arr[]) { long ans = arr[0]; int n = arr.length; for(int i =1;i<n;i++) { ans = Math.max(ans , arr[i]); } return ans; } public static int minArray(int arr[]) { int ans = arr[0] , n = arr.length; for(int i =0;i<n;i++ ) { ans = Math.min(ans ,arr[i]); } return ans; } public static long minArray(long arr[]) { long ans = arr[0]; int n = arr.length; for(int i =0;i<n;i++ ) { ans = Math.min(ans ,arr[i]); } return ans; } public static int sumArray(int arr[]) { int ans = 0; for(int x : arr) { ans += x; } return ans; } public static long sumArray(long arr[]) { long ans = 0; for(long x : arr) { ans += x; } return ans; } public static long rl() { return sc.nextLong(); } public static char[] rac() { return sc.next().toCharArray(); } public static String rs() { return sc.next(); } public static char rc() { return sc.next().charAt(0); } public static int [] rai(int n) { int ans[] = new int[n]; for(int i =0;i<n;i++) { ans[i] = sc.nextInt(); } return ans; } public static long [] ral(int n) { long ans[] = new long[n]; for(int i =0;i<n;i++) { ans[i] = sc.nextLong(); } return ans; } public static int ri() { return sc.nextInt(); } public static int getValue(int num ) { int ans = 0; while(num > 0) { ans++; num = num&(num-1); } return ans; } public static boolean isValid(int x ,int y , int n,char arr[][],boolean visited[][][][]) { return x>=0 && x<n && y>=0 && y <n && !(arr[x][y] == '#'); } // public static Pair join(Pair a , Pair b) { // Pair res = new Pair(Math.min(a.min , b.min) , Math.max(a.max , b.max) , a.count + b.count); // return res; // } // segment tree query over range // public static int query(int node,int l , int r,int a,int b ,Pair tree[] ) { // if(tree[node].max < a || tree[node].min > b) return 0; // if(l > r) return 0; // if(tree[node].min >= a && tree[node].max <= b) { // return tree[node].count; // } // int mid = l + (r-l)/2; // int ans = query(node*2 ,l , mid ,a , b , tree) + query(node*2 +1,mid + 1, r , a , b, tree); // return ans; // } // // segment tree update over range // public static void update(int node, int i , int j ,int l , int r,long value, long arr[] ) { // if(l >= i && j >= r) { // arr[node] += value; // return; // } // if(j < l|| r < i) return; // int mid = l + (r-l)/2; // update(node*2 ,i ,j ,l,mid,value, arr); // update(node*2 +1,i ,j ,mid + 1,r, value , arr); // } public static long pow(long a , long b , long mod) { if(b == 1) return a; if(b == 0) return 1; long ans = pow(a , b/2 , mod)%mod; if(b%2 == 0) { return (ans*ans)%mod; } else { return ((ans*ans)%mod*a)%mod; } } public static long pow(long a , long b ) { if(b == 1) return a; if(b == 0) return 1; long ans = pow(a , b/2); if(b%2 == 0) { return (ans*ans); } else { return ((ans*ans)*a); } } public static boolean isVowel(char ch) { if(ch == 'a' || ch == 'e'||ch == 'i' || ch == 'o' || ch == 'u') return true; if((ch == 'A' || ch == 'E'||ch == 'I' || ch == 'O' || ch == 'U')) return true; return false; } // public static int getFactor(int num) { // if(num==1) return 1; // int ans = 2; // int k = num/2; // for(int i = 2;i<=k;i++) { // if(num%i==0) ans++; // } // return Math.abs(ans); // } public static int[] readarr()throws IOException { int n = sc.nextInt(); int arr[] = new int[n]; for(int i =0;i<n;i++) { arr[i] = sc.nextInt(); } return arr; } public static boolean isPowerOfTwo (long x) { return x!=0 && ((x&(x-1)) == 0); } public static boolean isPrime(long num) { if(num==1) return false; if(num<=3) return true; if(num%2==0||num%3==0) return false; for(long i =5;i*i<=num;i+=6) { if(num%i==0 || num%(i+2) == 0) return false; } return true; } public static boolean isPrime(int num) { // System.out.println("At pr " + num); if(num==1) return false; if(num<=3) return true; if(num%2==0||num%3==0) return false; for(int i =5;i*i<=num;i+=6) { if(num%i==0 || num%(i+2) == 0) return false; } return true; } // public static boolean isPrime(long num) { // if(num==1) return false; // if(num<=3) return true; // if(num%2==0||num%3==0) return false; // for(int i =5;i*i<=num;i+=6) { // if(num%i==0) return false; // } // return true; // } public static void allMultiple() { // int MAX = 0 , n = nums.length; // for(int x : nums) MAX = Math.max(MAX ,x); // int cnt[] = new int[MAX + 1]; // int ans[] = new int[MAX + 1]; // for (int i = 0; i < n; ++i) cnt[nums[i]]++; // for (int i = 1; i <= MAX; ++i) { // for (int j = i; j <= MAX; j += i) ans[i] += cnt[j]; // } } public static long gcd(long a , long b) { if (b == 0) return a; return gcd(b, a % b); } public static int gcd(int a , int b) { if (b == 0) return a; return gcd(b, a % b); } public static int get_gcd(int a , int b) { if (b == 0) return a; return gcd(b, a % b); } public static long get_gcd(long a , long b) { if (b == 0) return a; return gcd(b, a % b); } // public static long fac(long num) { // long ans = 1; // int mod = (int)1e9+7; // for(long i = 2;i<=num;i++) { // ans = (ans*i)%mod; // } // return ans; // } }
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.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; public class Main { static int n, m; static ArrayList<Integer>[] adj; static boolean [] visited; public static void main (String [] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); for (int i=0; i<t; i++) { int n = Integer.parseInt(br.readLine()); int x = 1, y = 1, z = 1; for (int a=2; a<=Math.sqrt(n); a++) { if (n % a == 0) { int k = n / a; for (int b=2; b<=Math.sqrt(k); b++) { if (k % b == 0 && a!=k/b && a!=b && b!=k/b && k > b) { x = a; y = b; z = k / b; } } } } if (x==1 && y==1 && z==1) { System.out.println("NO"); } else { System.out.println("YES"); System.out.println(x + " " + y + " " + z); } } } }
java
1294
A
A. Collecting Coinstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp has three sisters: Alice; Barbara, and Cerene. They're collecting coins. Currently, Alice has aa coins, Barbara has bb coins and Cerene has cc coins. Recently Polycarp has returned from the trip around the world and brought nn coins.He wants to distribute all these nn coins between his sisters in such a way that the number of coins Alice has is equal to the number of coins Barbara has and is equal to the number of coins Cerene has. In other words, if Polycarp gives AA coins to Alice, BB coins to Barbara and CC coins to Cerene (A+B+C=nA+B+C=n), then a+A=b+B=c+Ca+A=b+B=c+C.Note that A, B or C (the number of coins Polycarp gives to Alice, Barbara and Cerene correspondingly) can be 0.Your task is to find out if it is possible to distribute all nn coins between sisters in a way described above.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 new line and consists of four space-separated integers a,b,ca,b,c and nn (1≤a,b,c,n≤1081≤a,b,c,n≤108) — the number of coins Alice has, the number of coins Barbara has, the number of coins Cerene has and the number of coins Polycarp has.OutputFor each test case, print "YES" if Polycarp can distribute all nn coins between his sisters and "NO" otherwise.ExampleInputCopy5 5 3 2 8 100 101 102 105 3 2 1 100000000 10 20 15 14 101 101 101 3 OutputCopyYES YES NO NO YES
[ "math" ]
import static java.lang.System.out; import java.util.*; public class A1294{ public static void main(String args[]){ Scanner in = new Scanner(System.in); int t = in.nextInt(); while(t-->0){ int a = in.nextInt(); int b = in.nextInt(); int c = in.nextInt(); int n = in.nextInt(); int max = a+b+c+n; if(max%3 ==0 && a<=max/3 && b<=max/3 && c<=max/3){ out.println("YES"); }else{ out.println ("NO"); } } } }
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.util.*; public class Sleeping_Schedule { 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 = Integer.MAX_VALUE, iMin = Integer.MIN_VALUE; private static final long lMax = Long.MAX_VALUE, lMin = Long.MIN_VALUE; 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 int[][] dp; private static void solve() { int n = fs.nextInt(), h = fs.nextInt(); int l = fs.nextInt(), r = fs.nextInt(); int[] arr = readIntArray(n); dp = new int[n + 1][h + 1]; for (int[] row : dp) Arrays.fill(row, -1); int ans = goodSleeps(0, 0, arr, n, h, l, r); fw.out.println(ans); } private static int goodSleeps(int i, int time, int[] arr, int n, int h, int l, int r) { if (i >= n) return 0; if (dp[i][time] != -1) return dp[i][time]; int ff = (time + arr[i]) % h; int ss = (time + arr[i] - 1 + h) % h; int ans = Math.max((util(ff, l, r) ? 1 : 0) + goodSleeps(i + 1, ff, arr, n, h, l, r), (util(ss, l, r) ? 1 : 0) + goodSleeps(i + 1, ss, arr, n, h, l, r)); return dp[i][time] = ans; } private static boolean util(int x, int l, int r) { return (x >= l && x <= r); } 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 SCC { private final int n; private final List<List<Integer>> adjList; SCC(int _n, List<List<Integer>> _adjList) { n = _n; adjList = _adjList; } private List<List<Integer>> getSCC() { List<List<Integer>> ans = new ArrayList<>(); Stack<Integer> stack = new Stack<>(); boolean[] vis = new boolean[n]; for (int i = 0; i < n; i++) { if (!vis[i]) dfs(i, adjList, vis, stack); } vis = new boolean[n]; List<List<Integer>> rev_adjList = rev_graph(n, adjList); while (!stack.isEmpty()) { int curr = stack.pop(); if (!vis[curr]) { List<Integer> scc_list = new ArrayList<>(); dfs2(curr, rev_adjList, vis, scc_list); ans.add(scc_list); } } return ans; } private void dfs(int curr, List<List<Integer>> adjList, boolean[] vis, Stack<Integer> stack) { vis[curr] = true; for (int x : adjList.get(curr)) { if (!vis[x]) dfs(x, adjList, vis, stack); } stack.add(curr); } private void dfs2(int curr, List<List<Integer>> adjList, boolean[] vis, List<Integer> scc_list) { vis[curr] = true; scc_list.add(curr); for (int x : adjList.get(curr)) { if (!vis[x]) dfs2(x, adjList, vis, scc_list); } } } private static List<List<Integer>> rev_graph(int n, List<List<Integer>> adjList) { List<List<Integer>> ans = new ArrayList<>(); for (int i = 0; i < n; i++) ans.add(new ArrayList<>()); for (int i = 0; i < n; i++) { for (int x : adjList.get(i)) { ans.get(x).add(i); } } return ans; } 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_with_mod(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 int random_between_two_numbers(int l, int r) { Random ran = new Random(); return ran.nextInt(r - l) + l; } 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) { long result = 1; while (b > 0) { if ((b & 1L) == 1) { result = (result * a); } a = (a * a); b >>= 1; } return result; } private static long pow_with_mod(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 int sumOfDigits(long num) { int cnt = 0; while (num > 0) { cnt += (num % 10); num /= 10; } return cnt; } private static int noOfDigits(long num) { int cnt = 0; while (num > 0) { cnt++; num /= 10; } 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
1301
A
A. Three Stringstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three strings aa, bb and cc of the same length nn. The strings consist of lowercase English letters only. The ii-th letter of aa is aiai, the ii-th letter of bb is bibi, the ii-th letter of cc is cici.For every ii (1≤i≤n1≤i≤n) you must swap (i.e. exchange) cici with either aiai or bibi. So in total you'll perform exactly nn swap operations, each of them either ci↔aici↔ai or ci↔bici↔bi (ii iterates over all integers between 11 and nn, inclusive).For example, if aa is "code", bb is "true", and cc is "help", you can make cc equal to "crue" taking the 11-st and the 44-th letters from aa and the others from bb. In this way aa becomes "hodp" and bb becomes "tele".Is it possible that after these swaps the string aa becomes exactly the same as the string bb?InputThe input consists of multiple test cases. The first line contains a single 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 string of lowercase English letters aa.The second line of each test case contains a string of lowercase English letters bb.The third line of each test case contains a string of lowercase English letters cc.It is guaranteed that in each test case these three strings are non-empty and have the same length, which is not exceeding 100100.OutputPrint tt lines with answers for all test cases. For each test case:If it is possible to make string aa equal to string bb print "YES" (without quotes), otherwise print "NO" (without quotes).You can print either lowercase or uppercase letters in the answers.ExampleInputCopy4 aaa bbb ccc abc bca bca aabb bbaa baba imi mii iim OutputCopyNO YES YES NO NoteIn the first test case; it is impossible to do the swaps so that string aa becomes exactly the same as string bb.In the second test case, you should swap cici with aiai for all possible ii. After the swaps aa becomes "bca", bb becomes "bca" and cc becomes "abc". Here the strings aa and bb are equal.In the third test case, you should swap c1c1 with a1a1, c2c2 with b2b2, c3c3 with b3b3 and c4c4 with a4a4. Then string aa becomes "baba", string bb becomes "baba" and string cc becomes "abab". Here the strings aa and bb are equal.In the fourth test case, it is impossible to do the swaps so that string aa becomes exactly the same as string bb.
[ "implementation", "strings" ]
/***** ---> :) Vijender Srivastava (: <--- *****/ import java.util.*; import java.lang.*; import java.io.*; public class Main { static FastReader sc =new FastReader(); static PrintWriter out=new PrintWriter(System.out); static long mod=(long)998244353; static StringBuilder sb = new StringBuilder(); /* start */ public static void main(String [] args) { int testcases = 1; testcases = i(); // calc(); while(testcases-->0) { solve(); } out.flush(); out.close(); } static void solve() { char a[] = inputC(),b[] = inputC(),c[] = inputC(); int n = a.length; for(int i=0;i<n;i++) { if(a[i]!=b[i] && (c[i]!=a[i] && c[i]!=b[i])) { pl("NO"); return; } if(a[i]==b[i] && c[i]!=b[i]) { pl("NO"); return ; } } pl("YES"); } /* end */ 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; } } // print code start static void p(Object o) { out.print(o); } static void pl(Object o) { out.println(o); } static void pl() { out.println(""); } // print code end // static int i() { return sc.nextInt(); } static String s() { return sc.next(); } static long l() { return sc.nextLong(); } static char[] inputC() { String s = sc.nextLine(); return s.toCharArray(); } static int[] input(int n) { int A[]=new int[n]; for(int i=0;i<n;i++) { A[i]=sc.nextInt(); } return A; } static long[] inputL(int n) { long A[]=new long[n]; for(int i=0;i<n;i++) { A[i]=sc.nextLong(); } return A; } static long[] putL(long a[]) { long A[]=new long[a.length]; for(int i=0;i<a.length;i++) { A[i]=a[i]; } return A; } static String[] inputS(int n) { String A[]=new String[n]; for(int i=0;i<n;i++) { A[i]=sc.next(); } return A; } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } static String reverse(String s) { StringBuffer p=new StringBuffer(s); p.reverse(); return p.toString(); } static int min(int a,int b) { return Math.min(a, b); } static int min(int a,int b,int c) { return Math.min(a, Math.min(b, c)); } static int min(int a,int b,int c,int d) { return Math.min(a, Math.min(b, Math.min(c, d))); } static int max(int a,int b) { return Math.max(a, b); } static int max(int a,int b,int c) { return Math.max(a, Math.max(b, c)); } static int max(int a,int b,int c,int d) { return Math.max(a, Math.max(b, Math.max(c, d))); } static long min(long a,long b) { return Math.min(a, b); } static long min(long a,long b,long c) { return Math.min(a, Math.min(b, c)); } static long min(long a,long b,long c,long d) { return Math.min(a, Math.min(b, Math.min(c, d))); } static long max(long a,long b) { return Math.max(a, b); } static long max(long a,long b,long c) { return Math.max(a, Math.max(b, c)); } static long max(long a,long b,long c,long d) { return Math.max(a, Math.max(b, Math.max(c, d))); } static long sum(int A[]) { long sum=0; for(int i : A) { sum+=i; } return sum; } static long sum(long A[]) { long sum=0; for(long i : A) { sum+=i; } return sum; } static long mod(long x) { return ((x%mod + mod)%mod); } static long sum_mod(long x,long y) { return mod(mod(x)+mod(y)); } public static long ncr_mod(long n,long r){ long top=fac_mod(n); long bottom=mul_mod(fac_mod(r),fac_mod(n-r)); long ans=mul_mod(top,power_mod(bottom,mod-2)); return ans; } public static long power_mod(long a,long b){ if(b==0)return 1; if(b==1)return a; long res=1; while(b>0){ if((b&1)==1) res=mul_mod(res,a); a=mul_mod(a,a); b/=2; } return res; } public static long fac_mod(long n){ if(n==0)return 1; return mul_mod(fac_mod(n-1),n); } static long mul_mod(long x,long y) { return mod(mod(x)*mod(y)); } static long power(long x, long y) { if(y==0) return 1; if(x==0) return 0; long res = 1; while (y > 0) { if (y % 2 == 1) res = (res * x) ; y = y >> 1; x = (x * x); } return res; } static boolean prime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static boolean prime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; double sq=Math.sqrt(n); for (int i = 5; i <= sq; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static long[] sort(long a[]) { ArrayList<Long> arr = new ArrayList<>(); for(long i : a) { arr.add(i); } Collections.sort(arr); for(int i = 0; i < arr.size(); i++) { a[i] = arr.get(i); } return a; } static int[] sort(int a[]) { ArrayList<Integer> arr = new ArrayList<>(); for(Integer i : a) { arr.add(i); } Collections.sort(arr); for(int i = 0; i < arr.size(); i++) { a[i] = arr.get(i); } return a; } static int[] sortInd(int a[]) { int n = a.length; int ii[] = new int[n]; for(int i=0;i<n;i++)ii[i] = i; ii = Arrays.stream(ii).boxed().sorted((i,j)->a[i]-a[j]).mapToInt($->$).toArray(); return ii; } //pair class private static class Pair implements Comparable<Pair> { long first, second; public Pair(long f, long s) { first = f; second = s; } @Override public int compareTo(Pair p) { if (first < p.first) return 1; else if (first > p.first) return -1; else { if (second > p.second) return 1; else if (second < p.second) return -1; else return 0; } } } // segment t start static long seg[] ; static void build(long a[], int v, int tl, int tr) { if (tl == tr) { seg[v] = a[tl]; } else { int tm = (tl + tr) / 2; build(a, v*2, tl, tm); build(a, v*2+1, tm+1, tr); seg[v] = Math.min(seg[v*2] , seg[v*2+1]); } } static long query(int v, int tl, int tr, int l, int r) { if (l > r || tr < tl) return Integer.MAX_VALUE; if (l == tl && r == tr) { return seg[v]; } int tm = (tl + tr) / 2; return (query(v*2, tl, tm, l, min(r, tm))+ query(v*2+1, tm+1, tr, max(l, tm+1), r)); } static void update(int v, int tl, int tr, int pos, long new_val) { if (tl == tr) { seg[v] = new_val; } else { int tm = (tl + tr) / 2; if (pos <= tm) update(v*2, tl, tm, pos, new_val); else update(v*2+1, tm+1, tr, pos, new_val); seg[v] = Math.min(seg[v*2] , seg[v*2+1]); } } // segment t end // }
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.util.*; public class Main { public static void main(String[] args) { Solution sol = new Solution(); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int mod = sc.nextInt(); int l = sc.nextInt(); int r = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } System.out.println(sol.solutionn(l, r, arr, mod)); } } class Solution { int l, r, mod; int n; int[] arr; int[][] dp; public int solutionn(int l_, int r_, int[] arr_, int mod_) { n = arr_.length; l = l_; r = r_; arr = arr_; mod = mod_; dp = new int[n + 1][mod]; for (int i = l; i <= r; i ++) dp[n][i] = 1; for (int i = n - 1; i >= 0; i --) { for (int j = 0; j < mod; j ++) { dp[i][j] = Math.max(dp[i + 1][(j + arr[i]) % mod], dp[i + 1][(j + arr[i] - 1) % mod]); if (i > 0 && j >= l && j <= r) dp[i][j] ++; } } return dp[0][0]; } private int dfs(int i, int sum) { int ans = 0; if (i > 0 && sum >= l && sum <= r) ans ++; if (i == n) return ans; if (dp[i][sum] != -1) return dp[i][sum]; ans += Math.max(dfs(i + 1, (sum + arr[i]) % mod), dfs(i + 1, (sum + arr[i] - 1) % mod)); dp[i][sum] = ans; return ans; } }
java
1303
C
C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following: if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem); otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5 ababa codedoca abcda zxzytyz abcdefghijklmnopqrstuvwxyza OutputCopyYES bacdefghijklmnopqrstuvwxyz YES edocabfghijklmnpqrstuvwxyz NO YES xzytabcdefghijklmnopqrsuvw NO
[ "dfs and similar", "greedy", "implementation" ]
import java.io.*; import java.util.*; public class CF1562C extends PrintWriter { CF1562C() { super(System.out); } public static Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1562C o = new CF1562C(); o.main(); o.flush(); } static long calculate(long p, long q) { long mod = 1000000007, expo; expo = mod - 2; // Loop to find the value // until the expo is not zero while (expo != 0) { // Multiply p with q // if expo is odd if ((expo & 1) == 1) { p = (p * q) % mod; } q = (q * q) % mod; // Reduce the value of // expo by 2 expo >>= 1; } return p; } static String longestPalSubstr(String str) { // The result (length of LPS) int maxLength = 1; int start = 0; int len = str.length(); int low, high; // One by one consider every // character as center // point of even and length // palindromes for (int i = 1; i < len; ++i) { // Find the longest even // length palindrome with // center points as i-1 and i. low = i - 1; high = i; while (low >= 0 && high < len && str.charAt(low) == str.charAt(high)) { --low; ++high; } // Move back to the last possible valid palindrom substring // as that will anyway be the longest from above loop ++low; --high; if (str.charAt(low) == str.charAt(high) && high - low + 1 > maxLength) { start = low; maxLength = high - low + 1; } // Find the longest odd length // palindrome with center point as i low = i - 1; high = i + 1; while (low >= 0 && high < len && str.charAt(low) == str.charAt(high)) { --low; ++high; } // Move back to the last possible valid palindrom substring // as that will anyway be the longest from above loop ++low; --high; if (str.charAt(low) == str.charAt(high) && high - low + 1 > maxLength) { start = low; maxLength = high - low + 1; } } return str.substring(start, start + maxLength - 1); } long check(long a){ long ret=0; for(long k=2;(k*k*k)<=a;k++){ ret=ret+(a/(k*k*k)); } return ret; } /*public static int getFirstSetBitPos(int n) { return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1; } public static int bfsq(int n, int m, HashMap<Integer,ArrayList<Integer>>h,boolean v ){ v[n]=true; if(n==m) return 1; else { int a=h.get(n).get(0); int b=h.get(n).get(1); if(b>m) return(m-n); else { int a1=bfsq(a,m,h,v); int b1=bfsq(b,m,h,v); return 1+Math.min(a1,b1); } } }*/ static long nCr(int n, int r) { return fact(n) / (fact(r) * fact(n - r)); } // Returns factorial of n static long fact(long n) { long res = 1; for (long i = 2; i <= n; i++) res = res * i; return res; } /*void bfs(int src, HashMap<Integer,ArrayList<Integer,Integer>>h,int deg, boolean v[] ){ a[src]=deg; Queue<Integer>= new LinkedList<Integer>(); q.add(src); while(!q.isEmpty()){ (int a:h.get(src)){ if() } } }*/ /* void dfs(int root, int par, HashMap<Integer,ArrayList<Integer>>h,int dp[], int child[]) { dp[root]=0; child[root]=1; for(int x: h.get(root)){ if(x == par) continue; dfs(x,root,h,in,dp); child[root]+=child[x]; } ArrayList<Integer> mine= new ArrayList<Integer>(); for(int x: h.get(root)) { if(x == par) continue; mine.add(x); } if(mine.size() >=2){ int y= Math.max(child[mine.get(0)] - 1 + dp[mine.get(1)] , child[mine.get(1)] -1 + dp[mine.get(0)]); dp[root]=y;} else if(mine.size() == 1) dp[root]=child[mine.get(0)] - 1; } */ class Pair implements Comparable<Pair>{ int i; int j; Pair (int a, int b){ i = a; j = b; } public int compareTo(Pair A){ return (int)(this.i-A.i); }} /*static class Pair { int i; int j; Pair() { } Pair(int i, int j) { this.i = i; this.j = j; } }*/ /*ArrayList<Integer> check(int a[], int b){ int n=a.length; long ans=0;int k=0; ArrayList<Integer>ab= new ArrayList<Integer>(); for(int i=0;i<n;i++){ if(a[i]%m==0) {k=a[i]; while(a[i]%m==0){ a[i]=a[i]/m; } for(int z=0;z<k/a[i];z++){ ab.add(a[i]); } } else{ ab.add(a[i]); } } return ab; } */ /*int check[]; int tree[]; static void build( int []arr) { // insert leaf nodes in tree for (int i = 0; i < n; i++) tree[n + i] = arr[i]; // build the tree by calculating // parents for (int i = n - 1; i > 0; --i){ int ans= Math.min(tree[i << 1], tree[i << 1 | 1]); int ans1=Math.max((tree[i << 1], tree[i << 1 | 1])); if(ans==0) } }*/ /*static void ab(long n) { // Note that this loop runs till square root for (long i=1; i<=Math.sqrt(n); i++) { if(i==1) { p.add(n/i); continue; } if (n%i==0) { // If divisors are equal, print only one if (n/i == i) p.add(i); else // Otherwise print both { p.add(i); p.add(n/i); } } } }*/ void main() { int g=sc.nextInt(); int mod=1000000007; sc.nextLine(); for(int w1=0;w1<g;w1++){ String s=sc.nextLine(); boolean v[]= new boolean[26]; HashMap<Character,HashSet<Character>>h= new HashMap<Character,HashSet<Character>>(); for(int i=0;i<26;i++){ char ch=(char)('a'+i); h.put(ch,new HashSet<Character>()); } boolean ans1=true; for(int i=0;i<s.length()-1;i++){ char ch=s.charAt(i); char b=s.charAt(i+1); h.get(ch).add(b); h.get(b).add(ch); if(h.get(ch).size()>2||h.get(b).size()>2) ans1=false; } if(!ans1){ println("NO"); continue;} ArrayList<Character>ans= new ArrayList<Character>(); for(int i=0;i<26;i++){ if(v[i]==false&&h.get((char)(i+'a')).size()==1){ Queue<Integer>q= new LinkedList<Integer>(); q.add(i); while(!q.isEmpty()){ int a=q.poll(); v[a]=true; char ch=(char)(a+'a'); ans.add(ch); for(char p:h.get(ch)){ int w=(int)(p-'a'); if(v[w]==false) q.add(w); } } } } for(int i=0;i<26;i++){ if(v[i]==false && h.get((char)(i+'a')).size()==0) {char x=(char)(i+'a'); ans.add(x);} } if(ans.size()!=26){ println("NO"); continue;} else println("YES"); for(int i=0;i<26;i++) print(ans.get(i)); println(); } } }
java
1286
B
B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3 2 0 0 2 2 0 OutputCopyYES 1 2 1 InputCopy5 0 1 1 3 2 1 3 0 2 0 OutputCopyYES 2 3 2 1 2
[ "constructive algorithms", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
import java.util.*; public class Solution { static ArrayList<Integer> tree[]; static int c[]; public static void main(String[] args) { Scanner input=new Scanner(System.in); int n=input.nextInt(); c=new int[n+1]; tree=new ArrayList[n+1]; for (int i = 0; i <=n ; i++) { tree[i]=new ArrayList<>(); } for (int i = 1; i <=n ; i++) { int x=input.nextInt(); tree[x].add(i); c[i]=input.nextInt(); } ArrayList<Integer> res=dfs(tree[0].get(0)); if (!flag) { int a[] = new int[n + 1]; for (int i = 0; i < n; i++) { a[res.get(i)] = i + 1; } System.out.println("YES"); for (int i = 1; i <= n; i++) { System.out.print(a[i] + " "); } }else { System.out.println("NO"); } } static boolean flag=false; private static ArrayList<Integer> dfs(Integer root) { ArrayList<Integer> res=new ArrayList<>(); for (Integer a:tree[root]) { res.addAll(dfs(a)); if (flag){ return new ArrayList<>(); } } if (c[root]>res.size()){ flag=true; return new ArrayList<>(); } res.add(c[root],root); return res; } }
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" ]
import java.io.*; import java.util.*; public class MotaracksBirthday { 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(); Integer[] arr = readIntArray(n); int max = iMin, min = iMax; for (int i = 0; i < n; i++) { if (arr[i] == -1) continue; boolean legal = (i - 1 >= 0 && arr[i - 1] == -1) || (i + 1 < n && arr[i + 1] == -1); if (legal) { max = Math.max(max, arr[i]); min = Math.min(min, arr[i]); } } if (max == iMin) { fw.out.println(0 + " " + 69); return; } int[] result = new int[]{(int) (2e9 + 100), -1}; int temp = (max + min) / 2; util(max, min, temp, result); util(max, min, Math.max(0, temp - 1), result); util(max, min, temp + 1, result); for (int i = 0; i < (n - 1); i++) { if (arr[i] == -1 || arr[i + 1] == -1) continue; result[0] = Math.max(result[0], Math.abs(arr[i] - arr[i + 1])); } fw.out.println(result[0] + " " + result[1]); } private static void util(int max, int min, int x, int[] result) { int diff = Math.max(Math.abs(max - x), Math.abs(min - x)); if (result[0] > diff) { result[0] = diff; result[1] = x; } } 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 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 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 <T> void randomizeArr(T[] arr, int n) { Random r = new Random(); for (int i = (n - 1); i > 0; i--) { int j = r.nextInt(i + 1); swap(arr, i, j); } } private static Integer[] readIntArray(int n) { Integer[] arr = new Integer[n]; for (int i = 0; i < n; i++) arr[i] = fs.nextInt(); 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 <T> void swap(T[] arr, int i, int j) { T temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } private static <T> void displayArr(T[] arr) { for (T x : arr) fw.out.print(x + " "); fw.out.println(); } private static <T> void displayList(List<T> list) { for (T x : list) fw.out.print(x + " "); fw.out.println(); } 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
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" ]
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Main { public static void main (String[] args) throws java.lang.Exception { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); for(int p=0;p<t;p++) { int n=sc.nextInt(); int[] arr=new int[2*n]; for(int q=0;q<2*n;q++) { arr[q]=sc.nextInt(); } Arrays.sort(arr); System.out.println(arr[n]-arr[n-1]); } } }
java
1288
D
D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5 5 0 3 1 2 1 8 9 1 3 1 2 3 4 5 9 1 0 3 7 2 3 0 6 3 6 4 1 7 0 OutputCopy1 5
[ "binary search", "bitmasks", "dp" ]
import java.util.*; import java.io.*; public class Main{ static int n, m; static int[]t; static int[][] a; static int x, y; static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); static int nextInt()throws Exception{ in.nextToken(); return (int)in.nval; } static boolean check(int v){ Arrays.fill(t, 0); for(int i=1; i<=n; i++){ int c = 0; for(int j=0; j<m; j++) c += a[i][j]>=v?1<<j:0; if(t[c]==0) t[c] = i; } for(int i=0; i<(1<<m); i++) if(t[i]>0) for(int j=i; j<(1<<m); j++) if(t[j]>0&&(i|j)==(1<<m)-1){ x = t[i]; y = t[j]; return true; } return false; } public static void main(String[] args)throws Exception{ n = nextInt(); m = nextInt(); if(n==1){ System.out.println(1+" "+1); return; } a = new int[n+1][m]; t = new int[(1<<m)]; for(int i=1; i<=n; i++) for(int j=0; j<m; j++) a[i][j] = nextInt(); int l, r; l = 0; r = 1000000000; while(l<=r){ int mid = l + r >> 1; if(check(mid)) l = mid+1; else r = mid - 1; } System.out.println(x+" "+y); } }
java
1307
A
A. Cow and Haybalestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of nn haybale piles on the farm. The ii-th pile contains aiai haybales. However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an adjacent pile. Formally, in one day she can choose any two indices ii and jj (1≤i,j≤n1≤i,j≤n) such that |i−j|=1|i−j|=1 and ai>0ai>0 and apply ai=ai−1ai=ai−1, aj=aj+1aj=aj+1. She may also decide to not do anything on some days because she is lazy.Bessie wants to maximize the number of haybales in pile 11 (i.e. to maximize a1a1), and she only has dd days to do so before Farmer John returns. Help her find the maximum number of haybales that may be in pile 11 if she acts optimally!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. Next 2t2t lines contain a description of test cases  — two lines per test case.The first line of each test case contains integers nn and dd (1≤n,d≤1001≤n,d≤100) — the number of haybale piles and the number of days, respectively. The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1000≤ai≤100)  — the number of haybales in each pile.OutputFor each test case, output one integer: the maximum number of haybales that may be in pile 11 after dd days if Bessie acts optimally.ExampleInputCopy3 4 5 1 0 3 2 2 2 100 1 1 8 0 OutputCopy3 101 0 NoteIn the first test case of the sample; this is one possible way Bessie can end up with 33 haybales in pile 11: On day one, move a haybale from pile 33 to pile 22 On day two, move a haybale from pile 33 to pile 22 On day three, move a haybale from pile 22 to pile 11 On day four, move a haybale from pile 22 to pile 11 On day five, do nothing In the second test case of the sample, Bessie can do nothing on the first day and move a haybale from pile 22 to pile 11 on the second day.
[ "greedy", "implementation" ]
import java.util.Scanner; public class Problems { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); while (t > 0) { int n = in.nextInt(); int d = in.nextInt(); int[] array = new int[n]; for (int i = 0; i <n; i++) { array[i] = in.nextInt(); } while(d-- > 0) { for (int i = 1; i < array.length; i++) { if(array[i] > 0) { array[i]--; array[i-1]++; break; } } } System.out.println(array[0]); t--; } } }
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.*; public class HelloWorld{ static class Point{ int x, y; Point(int x, int y){ this.x = x; this.y = y; } public boolean equal(Point other){ return x == other.x && y == other.y; } } private static void notpossible(){ System.out.println("INVALID"); System.exit(0); } public static void main(String []args)throws IOException{ BufferedReader re = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(re.readLine()), cx[] = {-1, +1, 0, 0}, cy[] = {0, 0, +1, -1}; char output[][] = new char[n][n], dir[] = {'U', 'D', 'R', 'L'}, revdir[] = {'D', 'U', 'L', 'R'}; Point fin[][] = new Point[n][n]; Queue<Point> q = new LinkedList<>(); for(int i=0; i<n; i++){ StringTokenizer tk = new StringTokenizer(re.readLine()); for(int j=0; j<n; j++){ output[i][j] = ' '; int x = Integer.parseInt(tk.nextToken()), y = Integer.parseInt(tk.nextToken()); if(x == -1 && y == -1) fin[i][j] = new Point(-1, -1); else fin[i][j] = new Point(x-1, y-1); } } for(int i=0; i<n; i++){ for(int j=0; j<n; j++){ int fx = fin[i][j].x, fy = fin[i][j].y; if(fx == -1 && fy == -1){ for(int k=0; k<4; k++){ int nx = i+cx[k], ny = j+cy[k]; if(nx >= 0 && nx < n && ny >= 0 && ny < n && fin[nx][ny].equal(fin[i][j])){ output[i][j] = dir[k]; q.add(new Point(i, j)); } } if(output[i][j] == ' ') notpossible(); } else if(i == fx && j == fy){ output[i][j] = 'X'; q.add(new Point(i, j)); } } } /*for(int i=0; i<n; i++){ for(int j=0; j<n; j++) System.out.print(output[i][j]); System.out.println(); } System.out.println();*/ while(!q.isEmpty()){ Point curr = q.poll(); int x = curr.x, y = curr.y; //System.out.println(+x+" "+y); /*if(output[x][y] == '\0'){ if(fin[x][y].x == x && fin[x][y].y == y) output[x][y] = 'X'; else{ for(int i=0; i<4; i++){ int nx = x + cx[i], ny = y + cy[i]; if(nx >= 0 && nx < n && ny >= 0 && ny < n && fin[nx][ny].equal(fin[x][y])){ output[x][y] = dir[i]; break; } } /*if(fin[x][y].x == -1 && fin[x][y].y == -1 && output[x][y] == '\0'){ for(int i=0; i<4; i++){ int nx = x + cx[i], ny = y + cy[i]; if(nx >= 0 && nx < n && ny >= 0 && ny < n && fin[nx][ny].equal(fin[x][y])){ output[x][y] = dir[i]; break; } } } if(output[x][y] == '\0') notpossible(); } }*/ for(int i=0; i<4; i++){ int nx = x + cx[i], ny = y + cy[i]; if(nx >= 0 && nx < n && ny >= 0 && ny < n && fin[nx][ny].equal(fin[x][y]) && output[nx][ny] == ' '){ output[nx][ny] = revdir[i]; q.add(new Point(nx, ny)); } } } /*for(int i=0; i<n; i++){ for(int j=0; j<n; j++) System.out.print(output[i][j]); System.out.println(); }*/ for(int i=0; i<n; i++){ for(int j=0; j<n; j++){ if(output[i][j] == ' ') notpossible(); } } PrintWriter pw = new PrintWriter(System.out); pw.println("VALID"); for(int i=0; i<n; i++){ for(int j=0; j<n; j++) pw.print(output[i][j]); pw.println(); } pw.flush(); pw.close(); } }
java
1313
C2
C2. Skyscrapers (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThis is a harder version of the problem. In this version n≤500000n≤500000The outskirts of the capital are being actively built up in Berland. The company "Kernel Panic" manages the construction of a residential complex of skyscrapers in New Berlskva. All skyscrapers are built along the highway. It is known that the company has already bought nn plots along the highway and is preparing to build nn skyscrapers, one skyscraper per plot.Architects must consider several requirements when planning a skyscraper. Firstly, since the land on each plot has different properties, each skyscraper has a limit on the largest number of floors it can have. Secondly, according to the design code of the city, it is unacceptable for a skyscraper to simultaneously have higher skyscrapers both to the left and to the right of it.Formally, let's number the plots from 11 to nn. Then if the skyscraper on the ii-th plot has aiai floors, it must hold that aiai is at most mimi (1≤ai≤mi1≤ai≤mi). Also there mustn't be integers jj and kk such that j<i<kj<i<k and aj>ai<akaj>ai<ak. Plots jj and kk are not required to be adjacent to ii.The company wants the total number of floors in the built skyscrapers to be as large as possible. Help it to choose the number of floors for each skyscraper in an optimal way, i.e. in such a way that all requirements are fulfilled, and among all such construction plans choose any plan with the maximum possible total number of floors.InputThe first line contains a single integer nn (1≤n≤5000001≤n≤500000) — the number of plots.The second line contains the integers m1,m2,…,mnm1,m2,…,mn (1≤mi≤1091≤mi≤109) — the limit on the number of floors for every possible number of floors for a skyscraper on each plot.OutputPrint nn integers aiai — the number of floors in the plan for each skyscraper, such that all requirements are met, and the total number of floors in all skyscrapers is the maximum possible.If there are multiple answers possible, print any of them.ExamplesInputCopy51 2 3 2 1OutputCopy1 2 3 2 1 InputCopy310 6 8OutputCopy10 6 6 NoteIn the first example, you can build all skyscrapers with the highest possible height.In the second test example, you cannot give the maximum height to all skyscrapers as this violates the design code restriction. The answer [10,6,6][10,6,6] is optimal. Note that the answer of [6,6,8][6,6,8] also satisfies all restrictions, but is not optimal.
[ "data structures", "dp", "greedy" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Stack; import java.util.StringTokenizer; public class Main{ public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); StringTokenizer zer = new StringTokenizer(br.readLine()); long[] a = new long[n]; for(int i = 0; i < n; i++){ a[i] = Long.parseLong(zer.nextToken()); } int pse[], nse[]; pse = new int[n]; Arrays.fill(pse, -1); nse = new int[n]; Arrays.fill(nse, -1); Stack<Integer> stk = new Stack<>(); stk.push(0); for(int i = 1; i < n; i++){ while(!stk.empty() && a[stk.peek()] > a[i]){ nse[stk.pop()] = i; } stk.push(i); } while(!stk.empty()){ stk.pop(); } stk.push(n - 1); for(int i = n - 2; i >= 0; i--){ while(!stk.empty() && a[stk.peek()] > a[i]){ pse[stk.pop()] = i; } stk.push(i); } long[] dlr = new long[n]; long[] drl = new long[n]; dlr[0] = a[0]; for(int i = 1; i < n; i++){ if(pse[i] == -1){ dlr[i] = a[i] * (i + 1); }else{ dlr[i] = dlr[pse[i]] + a[i] * (i - pse[i]); } } drl[n - 1] = a[n - 1]; for(int i = n - 2; i >= 0; i--){ if(nse[i] == -1){ drl[i] = a[i] * (n - i); }else{ drl[i] = drl[nse[i]] + a[i] * (nse[i] - i); } } int aidx = 0; long maxans = -1; for(int i = 0; i < n; i++){ long curans = dlr[i] + drl[i] - a[i]; if(curans > maxans){ maxans = curans; aidx = i; } } long[] ans = new long[n]; ans[aidx] = a[aidx]; for(int i = aidx + 1; i < n; i++){ ans[i] = Math.min(ans[i - 1], a[i]); } for(int i = aidx - 1; i >= 0; i--){ ans[i] = Math.min(ans[i + 1], a[i]); } for(long e : ans){ System.out.print(e + " "); } System.out.println(); } }
java
1286
B
B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3 2 0 0 2 2 0 OutputCopyYES 1 2 1 InputCopy5 0 1 1 3 2 1 3 0 2 0 OutputCopyYES 2 3 2 1 2
[ "constructive algorithms", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
import java.util.*; import java.io.*; public class B612 { static ArrayList<Integer> [] adj; static int [] c, a, sz; static boolean bad; public static void main(String[] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); adj = new ArrayList[n + 1]; sz = new int[n + 1]; c = new int[n + 1]; a = new int[n + 1]; for (int i = 1; i <= n; i++) adj[i] = new ArrayList<>(); int root = -1; for (int i = 1; i <= n; i++) { int p = sc.nextInt(); int less = sc.nextInt(); c[i] = less; if (p == 0) { root = i; continue; } adj[p].add(i); adj[i].add(p); } ArrayList<Integer> vals = new ArrayList<>(); for (int i = 1; i <= n; i++) vals.add(i); dfs1(root, -1); dfs(root, -1, vals); if (bad) { out.println("NO"); } else { out.println("YES"); for (int i = 1; i <= n; i++) out.print(a[i] + " "); } out.close(); } static void dfs1(int cur, int par) { sz[cur] = 1; for (Integer next: adj[cur]) { if (next != par) { dfs1(next, cur); sz[cur] += sz[next]; } } } static void dfs(int cur, int par, ArrayList<Integer> vals) { int seen = 0; if (c[cur] >= sz[cur]) { bad = true; return; } for (Integer i: vals) { if (seen == c[cur]) { a[cur] = i; } ++seen; } vals.remove((Object) a[cur]); int idx = 0; boolean ok = true; for (Integer next: adj[cur]) { if (next != par) { ArrayList<Integer> add = new ArrayList<>(); if (idx + sz[next] - 1 > vals.size() - 1) { ok = false; break; } int finish = idx + sz[next] - 1; for (; idx <= finish; idx++) { add.add(vals.get(idx)); } idx = finish + 1; dfs(next, cur, add); } } if (!ok) { bad = true; } } //-----------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
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.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Random; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; public final class CFPS { static FastReader fr = new FastReader(); static PrintWriter out = new PrintWriter(System.out); static final int gigamod = 1000000007; static final int mod = 998244353; static int t = 1; static boolean[] isPrime; static int[] smallestFactorOf; static final int UP = 0, LEFT = 1, DOWN = 2, RIGHT = 3; static int cmp; @SuppressWarnings({"unused"}) public static void main(String[] args) throws Exception { t = fr.nextInt(); OUTER: for (int tc = 0; tc < t; tc++) { long s = fr.nextLong(); long spent = 0; while (s >= 10) { // largest multiple of 10 under 's' long mul = s / 10; long amt = mul * 10; s -= amt; s += amt / 10; spent += amt; } spent += s; out.println(spent); } out.close(); } static boolean isPalindrome(char[] s) { char[] rev = s.clone(); reverse(rev); return Arrays.compare(s, rev) == 0; } static class Segment implements Comparable<Segment> { int size; long val; int stIdx; Segment left, right; Segment(int ss, long vv, int ssii) { size = ss; val = vv; stIdx = ssii; } @Override public int compareTo(Segment that) { cmp = size - that.size; if (cmp == 0) cmp = stIdx - that.stIdx; if (cmp == 0) cmp = Long.compare(val, that.val); return cmp; } } static class Pair implements Comparable<Pair> { int first, second; int idx; Pair() { first = second = 0; } Pair (int ff, int ss) {first = ff; second = ss;} Pair (int ff, int ss, int ii) { first = ff; second = ss; idx = ii; } public int compareTo(Pair that) { cmp = first - that.first; if (cmp == 0) cmp = second - that.second; return (int) cmp; } } // (range add - segment min) segTree static int nn; static int[] arr; static int[] tree; static int[] lazy; static void build(int node, int leftt, int rightt) { if (leftt == rightt) { tree[node] = arr[leftt]; return; } int mid = (leftt + rightt) >> 1; build(node << 1, leftt, mid); build(node << 1 | 1, mid + 1, rightt); tree[node] = Math.min(tree[node << 1], tree[node << 1 | 1]); } static void segAdd(int node, int leftt, int rightt, int segL, int segR, int val) { if (lazy[node] != 0) { tree[node] += lazy[node]; if (leftt != rightt) { lazy[node << 1] += lazy[node]; lazy[node << 1 | 1] += lazy[node]; } lazy[node] = 0; } if (segL > rightt || segR < leftt) return; if (segL <= leftt && rightt <= segR) { tree[node] += val; if (leftt != rightt) { lazy[node << 1] += val; lazy[node << 1 | 1] += val; } lazy[node] = 0; return; } int mid = (leftt + rightt) >> 1; segAdd(node << 1, leftt, mid, segL, segR, val); segAdd(node << 1 | 1, mid + 1, rightt, segL, segR, val); tree[node] = Math.min(tree[node << 1], tree[node << 1 | 1]); } static int minQuery(int node, int leftt, int rightt, int segL, int segR) { if (lazy[node] != 0) { tree[node] += lazy[node]; if (leftt != rightt) { lazy[node << 1] += lazy[node]; lazy[node << 1 | 1] += lazy[node]; } lazy[node] = 0; } if (segL > rightt || segR < leftt) return Integer.MAX_VALUE / 10; if (segL <= leftt && rightt <= segR) return tree[node]; int mid = (leftt + rightt) >> 1; return Math.min(minQuery(node << 1, leftt, mid, segL, segR), minQuery(node << 1 | 1, mid + 1, rightt, segL, segR)); } static void compute_automaton(String s, int[][] aut) { s += '#'; int n = s.length(); int[] pi = prefix_function(s.toCharArray()); for (int i = 0; i < n; i++) { for (int c = 0; c < 26; c++) { int j = i; while (j > 0 && 'A' + c != s.charAt(j)) j = pi[j-1]; if ('A' + c == s.charAt(j)) j++; aut[i][c] = j; } } } static void timeDFS(int current, int from, UGraph ug, int[] time, int[] tIn, int[] tOut) { tIn[current] = ++time[0]; for (int adj : ug.adj(current)) if (adj != from) timeDFS(adj, current, ug, time, tIn, tOut); tOut[current] = ++time[0]; } static boolean areCollinear(long x1, long y1, long x2, long y2, long x3, long y3) { // we will check if c3 lies on line through (c1, c2) long a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2); return a == 0; } static int[] treeDiameter(UGraph ug) { int n = ug.V(); int farthest = -1; int[] distTo = new int[n]; diamDFS(0, -1, 0, ug, distTo); int maxDist = -1; for (int i = 0; i < n; i++) if (maxDist < distTo[i]) { maxDist = distTo[i]; farthest = i; } distTo = new int[n + 1]; diamDFS(farthest, -1, 0, ug, distTo); distTo[n] = farthest; return distTo; } static void diamDFS(int current, int from, int dist, UGraph ug, int[] distTo) { distTo[current] = dist; for (int adj : ug.adj(current)) if (adj != from) diamDFS(adj, current, dist + 1, ug, distTo); } static class TreeDistFinder { UGraph ug; int n; int[] depthOf; LCA lca; TreeDistFinder(UGraph ug) { this.ug = ug; n = ug.V(); depthOf = new int[n]; depthCalc(0, -1, ug, 0, depthOf); lca = new LCA(ug, 0); } TreeDistFinder(UGraph ug, int a) { this.ug = ug; n = ug.V(); depthOf = new int[n]; depthCalc(a, -1, ug, 0, depthOf); lca = new LCA(ug, a); } private void depthCalc(int current, int from, UGraph ug, int depth, int[] depthOf) { depthOf[current] = depth; for (int adj : ug.adj(current)) if (adj != from) depthCalc(adj, current, ug, depth + 1, depthOf); } public int dist(int a, int b) { int lc = lca.lca(a, b); return (depthOf[a] - depthOf[lc] + depthOf[b] - depthOf[lc]); } } public static long[][] GCDSparseTable(long[] a) { int n = a.length; int b = 32-Integer.numberOfLeadingZeros(n); long[][] ret = new long[b][]; for(int i = 0, l = 1;i < b;i++, l*=2) { if(i == 0) { ret[i] = a; } else { ret[i] = new long[n-l+1]; for(int j = 0;j < n-l+1;j++) { ret[i][j] = gcd(ret[i-1][j], ret[i-1][j+l/2]); } } } return ret; } public static long sparseRangeGCDQ(long[][] table, int l, int r) { // [a,b) if(l > r)return 1; // 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3 int t = 31-Integer.numberOfLeadingZeros(r-l); return gcd(table[t][l], table[t][r-(1<<t)]); } static class Trie { TrieNode root; Trie(char[][] strings) { root = new TrieNode('A', false); construct(root, strings); } public Stack<String> set(TrieNode root) { Stack<String> set = new Stack<>(); StringBuilder sb = new StringBuilder(); for (TrieNode next : root.next) collect(sb, next, set); return set; } private void collect(StringBuilder sb, TrieNode node, Stack<String> set) { if (node == null) return; sb.append(node.character); if (node.isTerminal) set.add(sb.toString()); for (TrieNode next : node.next) collect(sb, next, set); if (sb.length() > 0) sb.setLength(sb.length() - 1); } private void construct(TrieNode root, char[][] strings) { // we have to construct the Trie for (char[] string : strings) { if (string.length == 0) continue; root.next[string[0] - 'a'] = put(root.next[string[0] - 'a'], string, 0); if (root.next[string[0] - 'a'] != null) root.isLeaf = false; } } private TrieNode put(TrieNode node, char[] string, int idx) { boolean isTerminal = (idx == string.length - 1); if (node == null) node = new TrieNode(string[idx], isTerminal); node.character = string[idx]; node.isTerminal |= isTerminal; if (!isTerminal) { node.isLeaf = false; node.next[string[idx + 1] - 'a'] = put(node.next[string[idx + 1] - 'a'], string, idx + 1); } return node; } class TrieNode { char character; TrieNode[] next; boolean isTerminal, isLeaf; boolean canWin, canLose; TrieNode(char c, boolean isTerminallll) { character = c; isTerminal = isTerminallll; next = new TrieNode[26]; isLeaf = true; } } } static class Edge implements Comparable<Edge> { int from, to; long weight, ans; int id; // int hash; Edge(int fro, int t, long wt, int i) { from = fro; to = t; id = i; weight = wt; // hash = Objects.hash(from, to, weight); } /*public int hashCode() { return hash; }*/ public int compareTo(Edge that) { return Long.compare(this.id, that.id); } } public static long[][] minSparseTable(long[] a) { int n = a.length; int b = 32-Integer.numberOfLeadingZeros(n); long[][] ret = new long[b][]; for(int i = 0, l = 1;i < b;i++, l*=2) { if(i == 0) { ret[i] = a; }else { ret[i] = new long[n-l+1]; for(int j = 0;j < n-l+1;j++) { ret[i][j] = Math.min(ret[i-1][j], ret[i-1][j+l/2]); } } } return ret; } public static long sparseRangeMinQ(long[][] table, int l, int r) { // [a,b) if(l >= r)return Integer.MAX_VALUE; // 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3 int t = 31-Integer.numberOfLeadingZeros(r-l); return Math.min(table[t][l], table[t][r-(1<<t)]); } public static long[][] maxSparseTable(long[] a) { int n = a.length; int b = 32-Integer.numberOfLeadingZeros(n); long[][] ret = new long[b][]; for(int i = 0, l = 1;i < b;i++, l*=2) { if(i == 0) { ret[i] = a; }else { ret[i] = new long[n-l+1]; for(int j = 0;j < n-l+1;j++) { ret[i][j] = Math.max(ret[i-1][j], ret[i-1][j+l/2]); } } } return ret; } public static long sparseRangeMaxQ(long[][] table, int l, int r) { // [a,b) if(l >= r)return Integer.MIN_VALUE; // 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3 int t = 31-Integer.numberOfLeadingZeros(r-l); return Math.max(table[t][l], table[t][r-(1<<t)]); } static class LCA { int[] height, first, segtree; ArrayList<Integer> euler; boolean[] visited; int n; LCA(UGraph ug, int root) { n = ug.V(); height = new int[n]; first = new int[n]; euler = new ArrayList<>(); visited = new boolean[n]; dfs(ug, root, 0); int m = euler.size(); segtree = new int[m * 4]; build(1, 0, m - 1); } void dfs(UGraph ug, int node, int h) { visited[node] = true; height[node] = h; first[node] = euler.size(); euler.add(node); for (int adj : ug.adj(node)) { if (!visited[adj]) { dfs(ug, adj, h + 1); euler.add(node); } } } void build(int node, int b, int e) { if (b == e) { segtree[node] = euler.get(b); } else { int mid = (b + e) / 2; build(node << 1, b, mid); build(node << 1 | 1, mid + 1, e); int l = segtree[node << 1], r = segtree[node << 1 | 1]; segtree[node] = (height[l] < height[r]) ? l : r; } } int query(int node, int b, int e, int L, int R) { if (b > R || e < L) return -1; if (b >= L && e <= R) return segtree[node]; int mid = (b + e) >> 1; int left = query(node << 1, b, mid, L, R); int right = query(node << 1 | 1, mid + 1, e, L, R); if (left == -1) return right; if (right == -1) return left; return height[left] < height[right] ? left : right; } int lca(int u, int v) { int left = first[u], right = first[v]; if (left > right) { int temp = left; left = right; right = temp; } return query(1, 0, euler.size() - 1, left, right); } } static class FenwickTree { long[] array; // 1-indexed array, In this array We save cumulative information to perform efficient range queries and updates public FenwickTree(int size) { array = new long[size + 1]; } public long rsq(int ind) { assert ind > 0; long sum = 0; while (ind > 0) { sum += array[ind]; //Extracting the portion up to the first significant one of the binary representation of 'ind' and decrementing ind by that number ind -= ind & (-ind); } return sum; } public long rsq(int a, int b) { assert b >= a && a > 0 && b > 0; return rsq(b) - rsq(a - 1); } public void update(int ind, long value) { assert ind > 0; while (ind < array.length) { array[ind] += value; //Extracting the portion up to the first significant one of the binary representation of 'ind' and incrementing ind by that number ind += ind & (-ind); } } public int size() { return array.length - 1; } } static class Point implements Comparable<Point> { long x; long y; long z; long id; // private int hashCode; Point() { x = z = y = 0; // this.hashCode = Objects.hash(x, y, cost); } Point(Point p) { this.x = p.x; this.y = p.y; this.z = p.z; this.id = p.id; // this.hashCode = Objects.hash(x, y, cost); } Point(long x, long y, long z, long id) { this.x = x; this.y = y; this.z = z; this.id = id; // this.hashCode = Objects.hash(x, y, id); } Point(long a, long b) { this.x = a; this.y = b; this.z = 0; // this.hashCode = Objects.hash(a, b); } Point(long x, long y, long id) { this.x = x; this.y = y; this.id = id; } @Override public int compareTo(Point o) { if (this.x < o.x) return -1; if (this.x > o.x) return 1; if (this.y < o.y) return -1; if (this.y > o.y) return 1; if (this.z < o.z) return -1; if (this.z > o.z) return 1; return 0; } @Override public boolean equals(Object that) { return this.compareTo((Point) that) == 0; } } static class BinaryLift { // FUNCTIONS: k-th ancestor and LCA in log(n) int[] parentOf; int maxJmpPow; int[][] binAncestorOf; int n; int[] lvlOf; // How this works? // a. For every node, we store the b-ancestor for b in {1, 2, 4, 8, .. log(n)}. // b. When we need k-ancestor, we represent 'k' in binary and for each set bit, we // lift level in the tree. public BinaryLift(UGraph tree) { n = tree.V(); maxJmpPow = logk(n, 2) + 1; parentOf = new int[n]; binAncestorOf = new int[n][maxJmpPow]; lvlOf = new int[n]; for (int i = 0; i < n; i++) Arrays.fill(binAncestorOf[i], -1); parentConstruct(0, -1, tree, 0); binConstruct(); } // TODO: Implement lvlOf[] initialization public BinaryLift(int[] parentOf) { this.parentOf = parentOf; n = parentOf.length; maxJmpPow = logk(n, 2) + 1; binAncestorOf = new int[n][maxJmpPow]; lvlOf = new int[n]; for (int i = 0; i < n; i++) Arrays.fill(binAncestorOf[i], -1); UGraph tree = new UGraph(n); for (int i = 1; i < n; i++) tree.addEdge(i, parentOf[i]); binConstruct(); parentConstruct(0, -1, tree, 0); } private void parentConstruct(int current, int from, UGraph tree, int depth) { parentOf[current] = from; lvlOf[current] = depth; for (int adj : tree.adj(current)) if (adj != from) parentConstruct(adj, current, tree, depth + 1); } private void binConstruct() { for (int node = 0; node < n; node++) for (int lvl = 0; lvl < maxJmpPow; lvl++) binConstruct(node, lvl); } private int binConstruct(int node, int lvl) { if (node < 0) return -1; if (lvl == 0) return binAncestorOf[node][lvl] = parentOf[node]; if (node == 0) return binAncestorOf[node][lvl] = -1; if (binAncestorOf[node][lvl] != -1) return binAncestorOf[node][lvl]; return binAncestorOf[node][lvl] = binConstruct(binConstruct(node, lvl - 1), lvl - 1); } // return ancestor which is 'k' levels above this one public int ancestor(int node, int k) { if (node < 0) return -1; if (node == 0) if (k == 0) return node; else return -1; if (k > (1 << maxJmpPow) - 1) return -1; if (k == 0) return node; int ancestor = node; int highestBit = Integer.highestOneBit(k); while (k > 0 && ancestor != -1) { ancestor = binAncestorOf[ancestor][logk(highestBit, 2)]; k -= highestBit; highestBit = Integer.highestOneBit(k); } return ancestor; } public int lca(int u, int v) { if (u == v) return u; // The invariant will be that 'u' is below 'v' initially. if (lvlOf[u] < lvlOf[v]) { int temp = u; u = v; v = temp; } // Equalizing the levels. u = ancestor(u, lvlOf[u] - lvlOf[v]); if (u == v) return u; // We will now raise level by largest fitting power of two until possible. for (int power = maxJmpPow - 1; power > -1; power--) if (binAncestorOf[u][power] != binAncestorOf[v][power]) { u = binAncestorOf[u][power]; v = binAncestorOf[v][power]; } return ancestor(u, 1); } } static class DFSTree { // NOTE: The thing is made keeping in mind that the whole // input graph is connected. UGraph tree; UGraph backUG; int hasBridge; int n; Edge backEdge; DFSTree(UGraph ug) { this.n = ug.V(); tree = new UGraph(n); hasBridge = -1; backUG = new UGraph(n); treeCalc(0, -1, new boolean[n], ug); } private void treeCalc(int current, int from, boolean[] marked, UGraph ug) { if (marked[current]) { // This is a backEdge. backUG.addEdge(from, current); backEdge = new Edge(from, current, 1, 0); return; } if (from != -1) tree.addEdge(from, current); marked[current] = true; for (int adj : ug.adj(current)) if (adj != from) treeCalc(adj, current, marked, ug); } public boolean hasBridge() { if (hasBridge != -1) return (hasBridge == 1); // We have to determine the bridge. bridgeFinder(); return (hasBridge == 1); } int[] levelOf; int[] dp; private void bridgeFinder() { // Finding the level of each node. levelOf = new int[n]; levelDFS(0, -1, 0); // Applying DP solution. // dp[i] -> Highest level reachable from subtree of 'i' using // some backEdge. dp = new int[n]; Arrays.fill(dp, Integer.MAX_VALUE / 100); dpDFS(0, -1); // Now, we will check each edge and determine whether its a // bridge. for (int i = 0; i < n; i++) for (int adj : tree.adj(i)) { // (i -> adj) is the edge. if (dp[adj] > levelOf[i]) hasBridge = 1; } if (hasBridge != 1) hasBridge = 0; } private void levelDFS(int current, int from, int lvl) { levelOf[current] = lvl; for (int adj : tree.adj(current)) if (adj != from) levelDFS(adj, current, lvl + 1); } private int dpDFS(int current, int from) { dp[current] = levelOf[current]; for (int back : backUG.adj(current)) dp[current] = Math.min(dp[current], levelOf[back]); for (int adj : tree.adj(current)) if (adj != from) dp[current] = Math.min(dp[current], dpDFS(adj, current)); return dp[current]; } } static class UnionFind { // Uses weighted quick-union with path compression. private int[] parent; // parent[i] = parent of i private int[] size; // size[i] = number of sites in tree rooted at i // Note: not necessarily correct if i is not a root node private int count; // number of components public UnionFind(int n) { count = n; parent = new int[n]; size = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; } } // Number of connected components. public int count() { return count; } // Find the root of p. public int find(int p) { while (p != parent[p]) p = parent[p]; return p; } public boolean connected(int p, int q) { return find(p) == find(q); } public int numConnectedTo(int node) { return size[find(node)]; } // Weighted union. public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make smaller root point to larger one if (size[rootP] < size[rootQ]) { parent[rootP] = rootQ; size[rootQ] += size[rootP]; } else { parent[rootQ] = rootP; size[rootP] += size[rootQ]; } count--; } public static int[] connectedComponents(UnionFind uf) { // We can do this in nlogn. int n = uf.size.length; int[] compoColors = new int[n]; for (int i = 0; i < n; i++) compoColors[i] = uf.find(i); HashMap<Integer, Integer> oldToNew = new HashMap<>(); int newCtr = 0; for (int i = 0; i < n; i++) { int thisOldColor = compoColors[i]; Integer thisNewColor = oldToNew.get(thisOldColor); if (thisNewColor == null) thisNewColor = newCtr++; oldToNew.put(thisOldColor, thisNewColor); compoColors[i] = thisNewColor; } return compoColors; } } static class UGraph { // Adjacency list. private HashSet<Integer>[] adj; private static final String NEWLINE = "\n"; private int E; @SuppressWarnings("unchecked") public UGraph(int V) { adj = (HashSet<Integer>[]) new HashSet[V]; E = 0; for (int i = 0; i < V; i++) adj[i] = new HashSet<Integer>(); } public void addEdge(int from, int to) { if (adj[from].contains(to)) return; E++; adj[from].add(to); adj[to].add(from); } public HashSet<Integer> adj(int from) { return adj[from]; } public int degree(int v) { return adj[v].size(); } public int V() { return adj.length; } public int E() { return E; } public String toString() { StringBuilder s = new StringBuilder(); s.append(V() + " vertices, " + E() + " edges " + NEWLINE); for (int v = 0; v < V(); v++) { s.append(v + ": "); for (int w : adj[v]) { s.append(w + " "); } s.append(NEWLINE); } return s.toString(); } public static void dfsMark(int current, boolean[] marked, UGraph g) { if (marked[current]) return; marked[current] = true; Iterable<Integer> adj = g.adj(current); for (int adjc : adj) dfsMark(adjc, marked, g); } public static void dfsMark(int current, int from, long[] distTo, boolean[] marked, UGraph g, ArrayList<Integer> endPoints) { if (marked[current]) return; marked[current] = true; if (from != -1) distTo[current] = distTo[from] + 1; HashSet<Integer> adj = g.adj(current); int alreadyMarkedCtr = 0; for (int adjc : adj) { if (marked[adjc]) alreadyMarkedCtr++; dfsMark(adjc, current, distTo, marked, g, endPoints); } if (alreadyMarkedCtr == adj.size()) endPoints.add(current); } public static void bfsOrder(int current, UGraph g) { } public static void dfsMark(int current, int[] colorIds, int color, UGraph g) { if (colorIds[current] != -1) return; colorIds[current] = color; Iterable<Integer> adj = g.adj(current); for (int adjc : adj) dfsMark(adjc, colorIds, color, g); } public static int[] connectedComponents(UGraph g) { int n = g.V(); int[] componentId = new int[n]; Arrays.fill(componentId, -1); int colorCtr = 0; for (int i = 0; i < n; i++) { if (componentId[i] != -1) continue; dfsMark(i, componentId, colorCtr, g); colorCtr++; } return componentId; } public static boolean hasCycle(UGraph ug) { int n = ug.V(); boolean[] marked = new boolean[n]; boolean[] hasCycleFirst = new boolean[1]; for (int i = 0; i < n; i++) { if (marked[i]) continue; hcDfsMark(i, ug, marked, hasCycleFirst, -1); } return hasCycleFirst[0]; } // Helper for hasCycle. private static void hcDfsMark(int current, UGraph ug, boolean[] marked, boolean[] hasCycleFirst, int parent) { if (marked[current]) return; if (hasCycleFirst[0]) return; marked[current] = true; HashSet<Integer> adjc = ug.adj(current); for (int adj : adjc) { if (marked[adj] && adj != parent && parent != -1) { hasCycleFirst[0] = true; return; } hcDfsMark(adj, ug, marked, hasCycleFirst, current); } } } static class Digraph { // Adjacency list. private HashSet<Integer>[] adj; private static final String NEWLINE = "\n"; private int E; @SuppressWarnings("unchecked") public Digraph(int V) { adj = (HashSet<Integer>[]) new HashSet[V]; E = 0; for (int i = 0; i < V; i++) adj[i] = new HashSet<Integer>(); } public void addEdge(int from, int to) { if (adj[from].contains(to)) return; E++; adj[from].add(to); } public HashSet<Integer> adj(int from) { return adj[from]; } public int V() { return adj.length; } public int E() { return E; } public Digraph reversed() { Digraph dg = new Digraph(V()); for (int i = 0; i < V(); i++) for (int adjVert : adj(i)) dg.addEdge(adjVert, i); return dg; } public String toString() { StringBuilder s = new StringBuilder(); s.append(V() + " vertices, " + E() + " edges " + NEWLINE); for (int v = 0; v < V(); v++) { s.append(v + ": "); for (int w : adj[v]) { s.append(w + " "); } s.append(NEWLINE); } return s.toString(); } public static int[] KosarajuSharirSCC(Digraph dg) { int[] id = new int[dg.V()]; Digraph reversed = dg.reversed(); // Gotta perform topological sort on this one to get the stack. Stack<Integer> revStack = Digraph.topologicalSort(reversed); // Initializing id and idCtr. id = new int[dg.V()]; int idCtr = -1; // Creating a 'marked' array. boolean[] marked = new boolean[dg.V()]; while (!revStack.isEmpty()) { int vertex = revStack.pop(); if (!marked[vertex]) sccDFS(dg, vertex, marked, ++idCtr, id); } return id; } private static void sccDFS(Digraph dg, int source, boolean[] marked, int idCtr, int[] id) { marked[source] = true; id[source] = idCtr; for (Integer adjVertex : dg.adj(source)) if (!marked[adjVertex]) sccDFS(dg, adjVertex, marked, idCtr, id); } public static Stack<Integer> topologicalSort(Digraph dg) { // dg has to be a directed acyclic graph. // We'll have to run dfs on the digraph and push the deepest nodes on stack first. // We'll need a Stack<Integer> and a int[] marked. Stack<Integer> topologicalStack = new Stack<Integer>(); boolean[] marked = new boolean[dg.V()]; // Calling dfs for (int i = 0; i < dg.V(); i++) if (!marked[i]) runDfs(dg, topologicalStack, marked, i); return topologicalStack; } static void runDfs(Digraph dg, Stack<Integer> topologicalStack, boolean[] marked, int source) { marked[source] = true; for (Integer adjVertex : dg.adj(source)) if (!marked[adjVertex]) runDfs(dg, topologicalStack, marked, adjVertex); topologicalStack.add(source); } } static class FastReader { private BufferedReader bfr; private StringTokenizer st; public FastReader() { bfr = new BufferedReader(new InputStreamReader(System.in)); } String next() { if (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(bfr.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()); } char nextChar() { return next().toCharArray()[0]; } String nextString() { return next(); } int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } double[] nextDoubleArray(int n) { double[] arr = new double[n]; for (int i = 0; i < arr.length; i++) arr[i] = nextDouble(); return arr; } long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } int[][] nextIntGrid(int n, int m) { int[][] grid = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) grid[i][j] = fr.nextInt(); } return grid; } } @SuppressWarnings("serial") static class CountMap<T> extends TreeMap<T, Integer>{ CountMap() { } CountMap(Comparator<T> cmp) { } CountMap(T[] arr) { this.putCM(arr); } public Integer putCM(T key) { return super.put(key, super.getOrDefault(key, 0) + 1); } public Integer removeCM(T key) { int count = super.getOrDefault(key, -1); if (count == -1) return -1; if (count == 1) return super.remove(key); else return super.put(key, count - 1); } public Integer getCM(T key) { return super.getOrDefault(key, 0); } public void putCM(T[] arr) { for (T l : arr) this.putCM(l); } } static long dioGCD(long a, long b, long[] x0, long[] y0) { if (b == 0) { x0[0] = 1; y0[0] = 0; return a; } long[] x1 = new long[1], y1 = new long[1]; long d = dioGCD(b, a % b, x1, y1); x0[0] = y1[0]; y0[0] = x1[0] - y1[0] * (a / b); return d; } static boolean diophantine(long a, long b, long c, long[] x0, long[] y0, long[] g) { g[0] = dioGCD(Math.abs(a), Math.abs(b), x0, y0); if (c % g[0] > 0) { return false; } x0[0] *= c / g[0]; y0[0] *= c / g[0]; if (a < 0) x0[0] = -x0[0]; if (b < 0) y0[0] = -y0[0]; return true; } static long[][] prod(long[][] mat1, long[][] mat2) { int n = mat1.length; long[][] prod = new long[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) // determining prod[i][j] // it will be the dot product of mat1[i][] and mat2[][i] for (int k = 0; k < n; k++) prod[i][j] += mat1[i][k] * mat2[k][j]; return prod; } static long[][] matExpo(long[][] mat, long power) { int n = mat.length; long[][] ans = new long[n][n]; if (power == 0) return null; if (power == 1) return mat; long[][] half = matExpo(mat, power / 2); ans = prod(half, half); if (power % 2 == 1) { ans = prod(ans, mat); } return ans; } static int KMPNumOcc(char[] text, char[] pat) { int n = text.length; int m = pat.length; char[] patPlusText = new char[n + m + 1]; for (int i = 0; i < m; i++) patPlusText[i] = pat[i]; patPlusText[m] = '^'; // Seperator for (int i = 0; i < n; i++) patPlusText[m + i] = text[i]; int[] fullPi = piCalcKMP(patPlusText); int answer = 0; for (int i = 0; i < n + m + 1; i++) if (fullPi[i] == m) answer++; return answer; } static int[] piCalcKMP(char[] s) { int n = s.length; int[] pi = new int[n]; for (int i = 1; i < n; i++) { int j = pi[i - 1]; while (j > 0 && s[i] != s[j]) j = pi[j - 1]; if (s[i] == s[j]) j++; pi[i] = j; } return pi; } static boolean[] prefMatchesSuff(char[] s) { int n = s.length; boolean[] res = new boolean[n + 1]; int[] pi = prefix_function(s); res[0] = true; for (int p = n; p != 0; p = pi[p]) res[p] = true; return res; } static int[] prefix_function(char[] s) { int n = s.length; int[] pi = new int[n]; for (int i = 1; i < n; i++) { int j = pi[i-1]; while (j > 0 && s[i] != s[j]) j = pi[j-1]; if (s[i] == s[j]) j++; pi[i] = j; } return pi; } static long hash(long key) { long h = Long.hashCode(key); h ^= (h >>> 20) ^ (h >>> 12) ^ (h >>> 7) ^ (h >>> 4); return h & (gigamod-1); } static void Yes() {out.println("Yes");}static void YES() {out.println("YES");}static void yes() {out.println("Yes");}static void No() {out.println("No");}static void NO() {out.println("NO");}static void no() {out.println("no");} static int mapTo1D(int row, int col, int n, int m) { // Maps elements in a 2D matrix serially to elements in // a 1D array. return row * m + col; } static int[] mapTo2D(int idx, int n, int m) { // Inverse of what the one above does. int[] rnc = new int[2]; rnc[0] = idx / m; rnc[1] = idx % m; return rnc; } static long mapTo1D(long row, long col, long n, long m) { // Maps elements in a 2D matrix serially to elements in // a 1D array. return row * m + col; } static boolean[] primeGenerator(int upto) { // Sieve of Eratosthenes: isPrime = new boolean[upto + 1]; smallestFactorOf = new int[upto + 1]; Arrays.fill(smallestFactorOf, 1); Arrays.fill(isPrime, true); isPrime[1] = isPrime[0] = false; for (long i = 2; i < upto + 1; i++) if (isPrime[(int) i]) { smallestFactorOf[(int) i] = (int) i; // Mark all the multiples greater than or equal // to the square of i to be false. for (long j = i; j * i < upto + 1; j++) { if (isPrime[(int) j * (int) i]) { isPrime[(int) j * (int) i] = false; smallestFactorOf[(int) j * (int) i] = (int) i; } } } return isPrime; } static HashMap<Integer, Integer> smolNumPrimeFactorization(int num) { if (smallestFactorOf == null) primeGenerator(num + 1); HashMap<Integer, Integer> fnps = new HashMap<>(); while (num != 1) { fnps.put(smallestFactorOf[num], fnps.getOrDefault(smallestFactorOf[num], 0) + 1); num /= smallestFactorOf[num]; } return fnps; } static HashMap<Long, Integer> primeFactorization(long num) { // Returns map of factor and its power in the number. HashMap<Long, Integer> map = new HashMap<>(); while (num % 2 == 0) { num /= 2; Integer pwrCnt = map.get(2L); map.put(2L, pwrCnt != null ? pwrCnt + 1 : 1); } for (long i = 3; i * i <= num; i += 2) { while (num % i == 0) { num /= i; Integer pwrCnt = map.get(i); map.put(i, pwrCnt != null ? pwrCnt + 1 : 1); } } // If the number is prime, we have to add it to the // map. if (num != 1) map.put(num, 1); return map; } static HashSet<Long> divisors(long num) { HashSet<Long> divisors = new HashSet<Long>(); divisors.add(1L); divisors.add(num); for (long i = 2; i * i <= num; i++) { if (num % i == 0) { divisors.add(num/i); divisors.add(i); } } return divisors; } static void coprimeGenerator(int m, int n, ArrayList<Point> coprimes, int limit, int numCoprimes) { if (m > limit) return; if (m <= limit && n <= limit) coprimes.add(new Point(m, n)); if (coprimes.size() > numCoprimes) return; coprimeGenerator(2 * m - n, m, coprimes, limit, numCoprimes); coprimeGenerator(2 * m + n, m, coprimes, limit, numCoprimes); coprimeGenerator(m + 2 * n, n, coprimes, limit, numCoprimes); } static long nCr(long n, long r, long[] fac) { long p = gigamod; if (r == 0) return 1; return (fac[(int)n] * modInverse(fac[(int)r], p) % p * modInverse(fac[(int)n - (int)r], p) % p) % p; } static long modInverse(long n, long p) { return power(n, p - 2, p); } static long modDiv(long a, long b){return mod(a * power(b, mod - 2, mod), mod);} static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1)==1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static int logk(long n, long k) { return (int)(Math.log(n) / Math.log(k)); } 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 gcd(long[] arr) { int n = arr.length; long gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static int gcd(int[] arr) { int n = arr.length; int gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static long lcm(long[] arr) { long lcm = arr[0]; int n = arr.length; for (int i = 1; i < n; i++) { lcm = (lcm * arr[i]) / gcd(lcm, arr[i]); } return lcm; } static long lcm(long a, long b) { return (a * b)/gcd(a, b); } static boolean less(int a, int b) { return a < b ? true : false; } static boolean isSorted(int[] a) { for (int i = 1; i < a.length; i++) { if (less(a[i], a[i - 1])) return false; } return true; } static boolean isSorted(long[] a) { for (int i = 1; i < a.length; i++) { if (a[i] < a[i - 1]) return false; } return true; } static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(long[] a, int i, int j) { long temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(double[] a, int i, int j) { double temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(char[] a, int i, int j) { char temp = a[i]; a[i] = a[j]; a[j] = temp; } static void sort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void reverseSort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverse(char[] arr) { int n = arr.length; for (int i = 0; i < n / 2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void shuffleArray(long[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { long tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(int[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(double[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { double tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(char[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { char tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static boolean isPrime(long n) {if (n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(long i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;} static String toString(int[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();} static String toString(boolean[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();} static String toString(long[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();} static String toString(char[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+"");return sb.toString();} static String toString(int[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();} static String toString(long[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++) {sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();} static String toString(double[][] dp){StringBuilder sb=new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();} static String toString(char[][] dp){StringBuilder sb = new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+"");}sb.append('\n');}return sb.toString();} static long mod(long a, long m){return(a%m+1000000L*m)%m;} } /* * * int[] arr = new int[] {1810, 1700, 1710, 2320, 2000, 1785, 1780 , 2130, 2185, 1430, 1460, 1740, 1860, 1100, 1905, 1650}; int n = arr.length; sort(arr); int bel1700 = 0, bet1700n1900 = 0, abv1900 = 0; for (int i = 0; i < n; i++) if (arr[i] < 1700) bel1700++; else if (1700 <= arr[i] && arr[i] < 1900) bet1700n1900++; else if (arr[i] >= 1900) abv1900++; out.println("COUNT: " + n); out.println("PERFS: " + toString(arr)); out.println("MEDIAN: " + arr[n / 2]); out.println("AVERAGE: " + Arrays.stream(arr).average().getAsDouble()); out.println("[0, 1700): " + bel1700 + "/" + n); out.println("[1700, 1900): " + bet1700n1900 + "/" + n); out.println("[1900, 2400): " + abv1900 + "/" + n); * * */ // NOTES: // ASCII VALUE OF 'A': 65 // ASCII VALUE OF 'a': 97 // Range of long: 9 * 10^18 // ASCII VALUE OF '0': 48 // Primes upto 'n' can be given by (n / (logn)).
java
1305
F
F. Kuroni and the Punishmenttime limit per test2.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is very angry at the other setters for using him as a theme! As a punishment; he forced them to solve the following problem:You have an array aa consisting of nn positive integers. An operation consists of choosing an element and either adding 11 to it or subtracting 11 from it, such that the element remains positive. We say the array is good if the greatest common divisor of all its elements is not 11. Find the minimum number of operations needed to make the array good.Unable to match Kuroni's intellect, the setters failed to solve the problem. Help them escape from Kuroni's punishment!InputThe first line contains an integer nn (2≤n≤2⋅1052≤n≤2⋅105)  — the number of elements in the array.The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤10121≤ai≤1012)  — the elements of the array.OutputPrint a single integer  — the minimum number of operations required to make the array good.ExamplesInputCopy3 6 2 4 OutputCopy0 InputCopy5 9 8 7 3 1 OutputCopy4 NoteIn the first example; the first array is already good; since the greatest common divisor of all the elements is 22.In the second example, we may apply the following operations: Add 11 to the second element, making it equal to 99. Subtract 11 from the third element, making it equal to 66. Add 11 to the fifth element, making it equal to 22. Add 11 to the fifth element again, making it equal to 33. The greatest common divisor of all elements will then be equal to 33, so the array will be good. It can be shown that no sequence of three or less operations can make the array good.
[ "math", "number theory", "probabilities" ]
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.stream.IntStream; import java.util.Random; import java.util.HashMap; import java.io.BufferedOutputStream; import java.util.HashSet; import java.nio.charset.Charset; import java.util.StringTokenizer; import java.util.Map; import java.io.OutputStreamWriter; import java.io.OutputStream; import java.util.stream.LongStream; import java.util.Set; import java.io.IOException; import java.io.InputStreamReader; import java.io.UncheckedIOException; import java.io.Writer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author mikit */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; LightScanner in = new LightScanner(inputStream); LightWriter out = new LightWriter(outputStream); FKuroniAndThePunishment solver = new FKuroniAndThePunishment(); solver.solve(1, in, out); out.close(); } static class FKuroniAndThePunishment { private static final Random rand = new Random(); public void solve(int testNumber, LightScanner in, LightWriter out) { int n = in.ints(); long[] a = in.longs(n); Set<Long> cand = new HashSet<>(); for (int i = 0; i < 20; i++) { long x = a[rand.nextInt(n)]; if (x == 1) continue; cand.addAll(IntMath.primeFactorize(x - 1).keySet()); cand.addAll(IntMath.primeFactorize(x).keySet()); cand.addAll(IntMath.primeFactorize(x + 1).keySet()); } long ans = n; for (long x : cand) { long t = 0; for (int i = 0; i < n; i++) { if (a[i] <= x) t += x - a[i]; else { long r = a[i] % x; t += Math.min(r, x - r); } } ans = Math.min(ans, t); } out.ans(ans).ln(); } } static class LightScanner { private BufferedReader reader = null; private StringTokenizer tokenizer = null; public LightScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public String string() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new UncheckedIOException(e); } } return tokenizer.nextToken(); } public int ints() { return Integer.parseInt(string()); } public long longs() { return Long.parseLong(string()); } public long[] longs(int length) { return IntStream.range(0, length).mapToLong(x -> longs()).toArray(); } } static final class IntMath { private IntMath() { } public static Map<Long, Integer> primeFactorize(long p) { Map<Long, Integer> factor = new HashMap<>(); if ((p & 1) == 0) { int c = 0; do { c++; p >>= 1; } while ((p & 1) == 0); factor.put(2L, c); } for (long i = 3; i * i <= p; i += 2) { if (p % i == 0) { int c = 0; do { c++; p /= i; } while ((p % i) == 0); factor.put(i, c); } } if (p > 1) { factor.put(p, 1); } return factor; } } static interface Verified { } static class LightWriter implements AutoCloseable { private final Writer out; private boolean autoflush = false; private boolean breaked = true; public LightWriter(Writer out) { this.out = out; } public LightWriter(OutputStream out) { this(new OutputStreamWriter(new BufferedOutputStream(out), Charset.defaultCharset())); } public LightWriter print(char c) { try { out.write(c); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter print(String s) { try { out.write(s, 0, s.length()); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter ans(String s) { if (!breaked) { print(' '); } return print(s); } public LightWriter ans(long l) { return ans(Long.toString(l)); } public LightWriter ln() { print(System.lineSeparator()); breaked = true; if (autoflush) { try { out.flush(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } return this; } public void close() { try { out.close(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } } }
java
1312
B
B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3 1 7 4 1 1 3 5 6 3 2 1 5 6 4 OutputCopy7 1 5 1 3 2 4 6 1 3 5
[ "constructive algorithms", "sortings" ]
// @Author : Ritik Rawat import java.util.*; import java.math.*; import java.lang.reflect.Array; import java.net.http.HttpClient; import java.util.*; import java.io.*; public class Main { static ArrayList<Integer> prime = new ArrayList<>(); static int mod = (int)(1e9 + 7 ) ; static ArrayList<Integer> arr; static ArrayList<Long> prefix; static ArrayList<Long> pre = new ArrayList<>(); static int dr[] = {0, 1, 0, -1}; static int dc[] = { -1, 0, 1, 0}; static String direction = "LDRU"; 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; } public int[] nextIntArr() throws IOException { String[] str = br.readLine().split("\\s+"); int[] inp = new int[str.length]; for (int i = 0; i < str.length; i++) { inp[i] = Integer.parseInt(str[i]); } return inp; } } 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 class Pair { int first; int second; Pair(int first , int second ) { this.first = first ; this.second = second; } } public static void main(String[] args) { try { FastReader in = new FastReader(); FastWriter out = new FastWriter(); int t = in.nextInt(); while ( t-- > 0 ) { long ans1 = 0, ans2 = 0, ans3 = 0, ans4 = 0; int n = in.nextInt(); int arr[] = in.nextIntArr(); Arrays.sort(arr); for ( int i = n - 1; i >= 0; --i ) { out.print(arr[i] + " "); } out.println(""); } out.close(); } catch (Exception e) { return; } // Collections.sort(arr, new Comparator<Pair>() { // @Override public int compare(Pair o1, Pair o2) { // if (o1.second < o2.second ) { // change (>) for desending order // return -1; // } else if (o1.second == o2.second ) { // return 0; // } else { // return 1; // } // } // }); } public static int freq( String s ) { HashSet<Character> hs = new HashSet<>(); for ( char ch : s.toCharArray() ) { hs.add(ch); } return hs.size(); } public static String solve(String s , String s1 ) { for ( int i = 0; i < s1.length(); ++i ) { if ( s.charAt(i) == s1.charAt(i) || s.charAt(i) == '?' || s1.charAt(i) == '?' ) continue; else return "No"; } return "Yes"; } public static int bfs( int node , ArrayList<Integer> arr ) { Queue<Integer> q = new LinkedList<>(); q.add(node); int steps = 0; while ( !q.isEmpty() ) { int no = q.peek(); q.remove(); int n = arr.get(no); steps++; if ( n == node ) break; q.add(n); } return steps; } public static long lcm( long a, long b ) { long g = GCD(a, b); return (a * b) / g; } public static boolean isSatisfy( ArrayList<Integer> arr , int l , int r ) { int ans = 0; if ( l == 0 || arr.get(l) < arr.get(l - 1) ) ans++; if ( r == arr.size() - 1 || arr.get(r) < arr.get(r + 1) ) ans++; if ( ans == 2 ) return true; return false; } public static ArrayList<Long> prefixSum() { int mod = 100000; // ArrayList<Integer> arr ; ArrayList<Long> prefix = new ArrayList<>(); long prev = 0; for ( long i = 0; i <= mod; ++i ) { prev += i; prefix.add(prev); } return prefix; } public static long sumRem(int x ) { if ( x <= 1 ) return 1; return x + sumRem(x - 1); } public static boolean isSquare( int n ) { int sqrt = (int) Math.sqrt(n); return (sqrt * sqrt == n ); } public static void swap ( int l , int r , ArrayList<Integer> a ) { int t = a.get(l) ; a.add(l, a.get(r) ); a.add(r, t); } public static void fib( int a , int b , int n) { int x = Math.floorMod(a, mod); int y = Math.floorMod(b, mod); arr = new ArrayList<>(); arr.add(a); arr.add(b); for ( int i = 2; i <= n; ++i ) { int cur = Math.floorMod((y - x), mod); x = y; y = cur; arr.add(y); } } public static String reverseString( String s1 ) { String s = ""; for ( int i = s1.length() - 1; i >= 0; --i ) { s += s1.charAt(i); } return s; } public static long countSetBits(long n) { long count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count; } public static void sortbykey(HashMap<Long, Long> map) { TreeMap<Long, Long> sorted = new TreeMap<>(); sorted.putAll(map); } public static long sum(int n) { if ( n <= 1 ) return n; return n + sum(n - 1); } public static ArrayList<Long> prefix( ArrayList<Long> arr1 ) { Collections.sort(arr1); ArrayList<Long> arr = new ArrayList<>(); long prefix = 0; for ( int i = 0; i < arr1.size(); ++i ) { prefix += arr1.get(i); arr.add(prefix); } return arr; } public static int solve(int[][] m, int n) { int ans = 0; int vis[][] = new int[n][n]; int di[] = {1, 0, 0, -1}; int dj[] = {0, -1, 1, 0}; if (m[0][0] == 1) mazerunner(0, 0, m, n, ans, "", vis, di, dj); return ans; } public static void mazerunner(int i, int j, int m[][], int n, int ans, String move, int vis[][], int di[] , int dj[]) { if ( i == n - 1 && j == n - 1) { ans++; return; } String dir = "DLRU"; for (int ind = 0; ind < 4; ind++) { int nexti = i + di[ind]; int nextj = j + dj[ind]; if (nexti >= 0 && nextj >= 0 && nexti < n && nextj < n && vis[nexti][nextj] == 0 && m[nexti][nextj] == 1) { vis[i][j] = 0; mazerunner(nexti, nextj, m, n, ans, move + dir.charAt(ind), vis, di, dj); vis[i][j] = -1; } } } public static long pow( long k , long n ) { long ans = 1; while ( n > 0 ) { if ( n % 2 == 1 ) { ans = (ans * k) % mod; n--; } else { k = (k * k) % mod; n /= 2; } } return ans % mod; } public static long fact(long n ) { long ans = 0; for (int i = 1; i < n; ++i) { ans += (long)i; } return ans; } public static boolean isValid( long mid, long arr[] , long k ) { long req = 0; for ( int i = 1; i < arr.length; ++i) { req += Math.min( (arr[i] - arr[i - 1] ) , mid ); } req += mid; if ( req >= k ) return true; return false; } public static String sortString(String inputString) { char tempArray[] = inputString.toCharArray(); Arrays.sort(tempArray); return new String(tempArray); } private static void reverse( ArrayList<Long> arr , int i, int j ) { while ( i <= j ) { swap( arr, i, j); i++; j--; } } private static void swap( ArrayList<Long> arr , int i, int j ) { long temp = arr.get(i); arr.set(i, arr.get(j)); arr.set(j, temp); } private static boolean isPrime(long n ) { if ( n <= 1 ) return false; for ( int i = 2; i * i <= n; i++) { if ( n % i == 0 ) { return false ; } } return true; } private static boolean[] sieve() { int n = 100000000; boolean sieve[] = new boolean[n + 1]; Arrays.fill(sieve, true); for ( int i = 2; i * i <= n; i++) { for ( int j = i * i; j <= n; j += i) { sieve[j] = false; } } return sieve; } private static ArrayList<Integer> generatePrimes(int n ) { boolean sieve[] = sieve(); for ( int i = 2; i <= n; i++) { if ( sieve[i] == true ) { prime.add(i); } } return prime; } private static void segmentedSieve( int l , int r ) { int n = (int) Math.sqrt(r); ArrayList<Integer> pr = generatePrimes(n); int dummy[] = new int[r - l + 1]; Arrays.fill(dummy, 1); for ( int p : pr ) { int firstMultiple = (l / p) * p; if ( firstMultiple < l ) firstMultiple += p; for ( int j = Math.max(firstMultiple, p * p); j <= r; j += p) { dummy[j - l] = 0; } } for ( int i = l; i <= r; i++) { if ( dummy[i - l] == 1 ) { System.out.println(i); } } } private static int[] primeFactors() { int n = 1000000; int prime[] = new int[n + 1]; for (int i = 1; i <= n; i++) { prime[i] = i; } for (int i = 2; i * i <= n; i++) { if ( prime[i] == i ) { for (int j = i * i; j <= n; j += i) { if ( prime[j] == j ) { prime[j] = i; } } } } return prime; } private static void primeFactors(HashSet<Integer> hs , int n ) { for ( int i = 2; i * i <= n; ++i ) { if ( n % i == 0 ) { int c = 0; while ( n % i == 0 ) { c++; n /= i; } while ( c-- > 0) hs.add(i); } } if ( n > 1 ) hs.add(n); } private static boolean isPalindrome(String s ) { int i = 0, j = s.length() - 1; while ( i <= j ) { if ( s.charAt(i) != s.charAt(j) ) { return false; } i++; j--; } return true; } private static long power( long a , long b ) { long ans = 1; while ( b > 0 ) { if ( (b & 1) != 0 ) { ans = binMultiply(ans, a); } a = binMultiply(a, a ); b >>= 1; } return ans; } private static long binMultiply(long a , long b ) { long ans = 0; while ( b > 0 ) { if ( (b & 1) != 0 ) { ans = (ans + a % mod ); // if m is given in ques than use ans = ans+a % m ; } a = (a + a) % mod; // if m is given in ques than use a = (a+a)%m; b >>= 1; } return ans; } private static long GCD ( long a , long b ) { if ( b == 0) return a; return GCD( b , a % b); } private static int binarySearch(int l , int r , int[] arr , int find ) { int mid = l + (r - l) / 2; if ( arr[mid] == find ) { return mid; } else if ( arr[mid] > find ) { return binarySearch(l, mid - 1, arr, find); } return binarySearch(mid + 1, r, arr, find); } private static int upper_bound(ArrayList<Integer> arr , int element ) { int l = 0 ; int h = arr.size() - 1; int mid = 0; while ( h - l > 1 ) { mid = (h + l) / 2; if ( arr.get(mid) <= element ) { l = mid + 1; } else { h = mid ; } } if ( arr.get(l) > element ) return l; if ( arr.get(h) > element ) return h; return -1; } private static int lower_bound( long arr[] , long element ) { int l = 0 ; int h = arr.length - 1; int mid = 0; while ( h - l > 1 ) { mid = (h - l) / 2; if ( arr[mid] < element ) { l = mid + 1; } else { h = mid ; } } if ( arr[l] >= element ) return l; if ( arr[h] >= element ) return h; return -1; } //////////////////////////////////////////// #### CODE FOR FAST READER WRITTER ### ///////////////////////////////////////////// //////////////////////////////////////// #### END FOR FAST READER WRITTER ### ////////////////////////////////////////////////// } class DisjointSet { List<Integer> rank = new ArrayList<>(); List<Integer> parent = new ArrayList<>(); List<Integer> size = new ArrayList<>(); public DisjointSet(int n ) { for ( int i = 0; i <= n; ++i ) { rank.add(0); parent.add(i); size.add(1); } } public int findUPar(int node ) { if ( node == parent.get(node) ) return node; int ulp = findUPar(parent.get(node)); parent.set(node, ulp); return parent.get(node); } public void unionBySize(int u, int v) { int ulp_u = findUPar(u); int ulp_v = findUPar(v); if ( ulp_u == ulp_v ) return ; if ( size.get(ulp_u) < size.get(ulp_v) ) { parent.set(ulp_u, ulp_v); size.set(ulp_v, size.get(ulp_v) + size.get(ulp_u) ); } else { parent.set(ulp_v, ulp_u); size.set(ulp_u, size.get(ulp_v) + size.get(ulp_u) ); } } public void unionByRank(int u, int v) { int ulp_u = findUPar(u); int ulp_v = findUPar(v); if ( ulp_u == ulp_v ) return ; if ( rank.get(ulp_u) < rank.get(ulp_v) ) { parent.set(ulp_u, ulp_v); } else if ( rank.get(ulp_v) < rank.get(ulp_u) ) { parent.set(ulp_v, ulp_u); } else { parent.set(ulp_v, ulp_u); int rankU = rank.get(ulp_u); rank.set(ulp_u, rankU + 1); } } } class Pair { int first; int second; StringBuilder list; Pair(int first , int second , StringBuilder list ) { this.first = first ; this.second = second; this.list = list; } }
java
1288
D
D. Minimax Problemtime limit per test5 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given nn arrays a1a1, a2a2, ..., anan; each array consists of exactly mm integers. We denote the yy-th element of the xx-th array as ax,yax,y.You have to choose two arrays aiai and ajaj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j). After that, you will obtain a new array bb consisting of mm integers, such that for every k∈[1,m]k∈[1,m] bk=max(ai,k,aj,k)bk=max(ai,k,aj,k).Your goal is to choose ii and jj so that the value of mink=1mbkmink=1mbk is maximum possible.InputThe first line contains two integers nn and mm (1≤n≤3⋅1051≤n≤3⋅105, 1≤m≤81≤m≤8) — the number of arrays and the number of elements in each array, respectively.Then nn lines follow, the xx-th line contains the array axax represented by mm integers ax,1ax,1, ax,2ax,2, ..., ax,max,m (0≤ax,y≤1090≤ax,y≤109).OutputPrint two integers ii and jj (1≤i,j≤n1≤i,j≤n, it is possible that i=ji=j) — the indices of the two arrays you have to choose so that the value of mink=1mbkmink=1mbk is maximum possible. If there are multiple answers, print any of them.ExampleInputCopy6 5 5 0 3 1 2 1 8 9 1 3 1 2 3 4 5 9 1 0 3 7 2 3 0 6 3 6 4 1 7 0 OutputCopy1 5
[ "binary search", "bitmasks", "dp" ]
import java.util.*; import javax.swing.text.PlainDocument; import java.io.*; public class Main { static int n, m; static int[][] grid; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); n = sc.nextInt(); m = sc.nextInt(); grid = new int[n][m]; int max = 0; for (int i = 0; i < n; i++) { grid[i] = sc.nextIntArray(m); } int start = 0; int end = (int) 1e9; Integer[] result = new Integer[2]; while (start <= end) { int mid = (start + end) / 2; HashMap<Integer, Integer> set = new HashMap<>(); for (int i = 0; i < n; i++) { int mask = 0; for (int j = 0; j < m; j++) { if (grid[i][j] >= mid) mask = setBit(mask, j); } if (set.getOrDefault(mask, -1) == -1) set.put(mask, i); // pw.println(set.toString()); if (set.size() == (1 << m)) break; } boolean flag = false; for (Integer integer : set.keySet()) { for (Integer integer2 : set.keySet()) { if ((integer | integer2) == ((1 << m) - 1)) { result = new Integer[] { set.get(integer) + 1, set.get(integer2) + 1 }; flag = true; break; } } if (flag) break; } if (flag) start = mid + 1; else end = mid - 1; } pw.println(toString(result)); pw.close(); } static long[][] memo; public static long dp(int idx1) { if (idx1 == n) return 0; long res = 0; for (int i = idx1; i < n; i++) { res = Math.max(res, getMin(grid[idx1], grid[i])); } return res; } public static int getMin(int[] arr1, int arr2[]) { int min = Integer.MAX_VALUE; for (int i = 0; i < arr2.length; i++) { min = Math.min(min, Math.max(arr2[i], arr1[i])); } return min; } public static int setBit(int mask, int ind) { return mask | (1 << ind); } public static boolean checkBit(int mask, int ind) { return (mask & (1 << ind)) != 0; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader r) { br = new BufferedReader(r); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public long[] nextlongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Long[] nextLongArray(int n) throws IOException { Long[] a = new Long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public boolean ready() throws IOException { return br.ready(); } } static class pair implements Comparable<pair> { long x; long y; public pair(long x, long y) { this.x = x; this.y = y; } public String toString() { return x + " " + y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair) o; return p.x == x && p.y == y; } return false; } public int hashCode() { return new Long(x).hashCode() * 31 + new Long(y).hashCode(); } public int compareTo(pair other) { if (this.x == other.x) { return Long.compare(this.y, other.y); } return Long.compare(this.x, other.x); } } static class tuble implements Comparable<tuble> { int x; int y; int z; public tuble(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public String toString() { return x + " " + y + " " + z; } public int compareTo(tuble other) { if (this.x == other.x) { if (this.y == other.y) { return this.z - other.z; } return this.y - other.y; } else { return this.x - other.x; } } } public static String toString(int[] arr) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { sb.append(arr[i] + " "); } return sb.toString().trim(); } public static String toString(Integer[] arr) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { sb.append(arr[i] + " "); } return sb.toString().trim(); } static long mod = 1000000007; static Random rn = new Random(); static Scanner sc = new Scanner(System.in); static PrintWriter pw = new PrintWriter(System.out); }
java
1304
E
E. 1-Trees and Queriestime limit per test4 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputGildong was hiking a mountain; walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with nn vertices, then he will ask you qq queries. Each query contains 55 integers: xx, yy, aa, bb, and kk. This means you're asked to determine if there exists a path from vertex aa to bb that contains exactly kk edges after adding a bidirectional edge between vertices xx and yy. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.InputThe first line contains an integer nn (3≤n≤1053≤n≤105), the number of vertices of the tree.Next n−1n−1 lines contain two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) each, which means there is an edge between vertex uu and vv. All edges are bidirectional and distinct.Next line contains an integer qq (1≤q≤1051≤q≤105), the number of queries Gildong wants to ask.Next qq lines contain five integers xx, yy, aa, bb, and kk each (1≤x,y,a,b≤n1≤x,y,a,b≤n, x≠yx≠y, 1≤k≤1091≤k≤109) – the integers explained in the description. It is guaranteed that the edge between xx and yy does not exist in the original tree.OutputFor each query, print "YES" if there exists a path that contains exactly kk edges from vertex aa to bb after adding an edge between vertices xx and yy. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy5 1 2 2 3 3 4 4 5 5 1 3 1 2 2 1 4 1 3 2 1 4 1 3 3 4 2 3 3 9 5 2 3 3 9 OutputCopyYES YES NO YES NO NoteThe image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines). Possible paths for the queries with "YES" answers are: 11-st query: 11 – 33 – 22 22-nd query: 11 – 22 – 33 44-th query: 33 – 44 – 22 – 33 – 44 – 22 – 33 – 44 – 22 – 33
[ "data structures", "dfs and similar", "shortest paths", "trees" ]
/* "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 int MAX = 100005, DEPTH = 25; static int[] tin = new int[MAX]; static int[] tout = new int[MAX]; static int time = 1; static int[] distance = new int[MAX]; // distance[i] is the distance from root node (1) to node i static int[][] ancestor = new int[MAX][DEPTH]; // ancestor[i][j] is the jth ancestor of node i. static Map<Integer, List<Integer>> graph = new HashMap<>(); 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(); for (int i = 1; i <= n; i++) { graph.put(i, new ArrayList<>()); } for (int i = 0; i < n - 1; i++) { int u = sc.nextInt(); int v = sc.nextInt(); graph.get(u).add(v); graph.get(v).add(u); } dfs(1, 1); // say root is 1, dfs from root int q = sc.nextInt(); for (int i = 0; i < q; i++) { // add edge between x and y int x = sc.nextInt(); int y = sc.nextInt(); // find a path from a to b having exactly k edges int a = sc.nextInt(); int b = sc.nextInt(); int k = sc.nextInt(); // if path length between a and b is l, then since a path can contain the same vertices and same edges multiple times, // we can also find a path between a and b with length l + 2 * constant // we should find a path with length l <= k, which have parity same as parity of k List<Integer> possiblePathLengths = new ArrayList<>(); // case1 : path from a to b without using added edge between x and y possiblePathLengths.add(findDistanceBetweenTwoNodes(a, b)); // case2 : path from a to x, then use added edge from x to y (only once, otherwise it won't affect the parity), and then from y to b possiblePathLengths.add(findDistanceBetweenTwoNodes(a, x) + 1 + findDistanceBetweenTwoNodes(b, y)); // case3 : path from a to y, then use added edge from y to x (only once, otherwise it won't affect the parity), and then from x to b possiblePathLengths.add(findDistanceBetweenTwoNodes(a, y) + 1 + findDistanceBetweenTwoNodes(b, x)); boolean found = false; for (int length : possiblePathLengths) { if (length <= k && (length % 2 == k % 2)) { found = true; break; } } out.println(found ? "YES" : "NO"); } } private static void dfs(int currNode, int parent) { tin[currNode] = time++; ancestor[currNode][0] = parent; for (int j = 1; j < DEPTH; j++) { ancestor[currNode][j] = ancestor[ancestor[currNode][j - 1]][j - 1]; } for (int adjacentNode : graph.get(currNode)) { if (adjacentNode == parent) { continue; } distance[adjacentNode] = distance[currNode] + 1; dfs(adjacentNode, currNode); } tout[currNode] = time++; } private static int findDistanceBetweenTwoNodes(int u, int v) { int lcaNode = findLCA(u, v); return distance[u] + distance[v] - 2 * distance[lcaNode]; } private static int findLCA(int u, int v) { if (isAncestor(u, v)) { return u; } if (isAncestor(v, u)) { return v; } for (int j = DEPTH - 1; j >= 0; j--) { if (!isAncestor(ancestor[u][j], v)) { u = ancestor[u][j]; } } return ancestor[u][0]; } private static boolean isAncestor(int u, int v) { // check if u is ancestor of v return tin[u] <= tin[v] && tout[u] >= tout[v]; } 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
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.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Stack; import java.io.BufferedOutputStream; import java.io.UncheckedIOException; import java.util.Vector; import java.nio.charset.Charset; 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 * * @author mikit */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; LightScanner in = new LightScanner(inputStream); LightWriter out = new LightWriter(outputStream); CWaterBalance solver = new CWaterBalance(); solver.solve(1, in, out); out.close(); } static class CWaterBalance { public void solve(int testNumber, LightScanner in, LightWriter out) { int n = in.ints(); Stack<CWaterBalance.Node> stack = new Stack<>(); for (int i = 0; i < n; i++) { CWaterBalance.Node node = new CWaterBalance.Node(1, in.ints()); while (!stack.isEmpty() && stack.peek().compareTo(node) > 0) { node.merge(stack.pop()); } stack.push(node); } for (CWaterBalance.Node node : stack) { int _z = node.length(); for (int i = 0; i < _z; i++) { out.ans(node.value(), 9).ln(); } } } private static class Node implements Comparable<CWaterBalance.Node> { int count; long sum; Node(int count, long sum) { this.count = count; this.sum = sum; } int length() { return count; } double value() { return sum / (double) length(); } public int compareTo(CWaterBalance.Node o) { return Long.compare(sum * o.length(), o.sum * length()); } void merge(CWaterBalance.Node o) { this.count += o.count; this.sum += o.sum; } } } static class LightScanner { private BufferedReader reader = null; private StringTokenizer tokenizer = null; public LightScanner(InputStream in) { reader = new BufferedReader(new InputStreamReader(in)); } public String string() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new UncheckedIOException(e); } } return tokenizer.nextToken(); } public int ints() { return Integer.parseInt(string()); } } static class LightWriter implements AutoCloseable { private final Writer out; private boolean autoflush = false; private boolean breaked = true; public LightWriter(Writer out) { this.out = out; } public LightWriter(OutputStream out) { this(new OutputStreamWriter(new BufferedOutputStream(out), Charset.defaultCharset())); } public LightWriter print(char c) { try { out.write(c); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter print(String s) { try { out.write(s, 0, s.length()); breaked = false; } catch (IOException ex) { throw new UncheckedIOException(ex); } return this; } public LightWriter ans(double x, int n) { if (!breaked) { print(' '); } if (x < 0) { print('-'); x = -x; } x += Math.pow(10, -n) / 2; print(Long.toString((long) x)).print('.'); x -= (long) x; for (int i = 0; i < n; i++) { x *= 10; print((char) ('0' + ((int) x))); x -= (int) x; } return this; } public LightWriter ln() { print(System.lineSeparator()); breaked = true; if (autoflush) { try { out.flush(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } return this; } public void close() { try { out.close(); } catch (IOException ex) { throw new UncheckedIOException(ex); } } } }
java
1311
C
C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in ss. I.e. if s=s="abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend mm wrong tries to perform the combo and during the ii-th try you will make a mistake right after pipi-th button (1≤pi<n1≤pi<n) (i.e. you will press first pipi buttons right and start performing the combo from the beginning). It is guaranteed that during the m+1m+1-th try you press all buttons right and finally perform the combo.I.e. if s=s="abca", m=2m=2 and p=[1,3]p=[1,3] then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.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.Then tt test cases follow.The first line of each test case contains two integers nn and mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤2⋅1051≤m≤2⋅105) — the length of ss and the number of tries correspondingly.The second line of each test case contains the string ss consisting of nn lowercase Latin letters.The third line of each test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n) — the number of characters pressed right during the ii-th try.It is guaranteed that the sum of nn and the sum of mm both does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105, ∑m≤2⋅105∑m≤2⋅105).It is guaranteed that the answer for each letter does not exceed 2⋅1092⋅109.OutputFor each test case, print the answer — 2626 integers: the number of times you press the button 'a', the number of times you press the button 'b', ……, the number of times you press the button 'z'.ExampleInputCopy3 4 2 abca 1 3 10 5 codeforces 2 8 3 2 9 26 10 qwertyuioplkjhgfdsazxcvbnm 20 10 1 2 3 5 10 5 9 4 OutputCopy4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0 2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2 NoteThe first test case is described in the problem statement. Wrong tries are "a"; "abc" and the final try is "abca". The number of times you press 'a' is 44, 'b' is 22 and 'c' is 22.In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is 99, 'd' is 44, 'e' is 55, 'f' is 33, 'o' is 99, 'r' is 33 and 's' is 11.
[ "brute force" ]
import java.util.*; public class PerformtheCombo { public static void main(String args[]) { int i,j,k,t,n; Scanner sc=new Scanner(System.in); t=sc.nextInt(); while(t-->0) { n=sc.nextInt(); k=sc.nextInt(); int a[]=new int[n]; String s=sc.next(); int b[]=new int[k]; for(i=0;i<k;i++) { b[i]=sc.nextInt(); a[b[i]-1]=a[b[i]-1]+1; } for(i=n-2;i>=0;i--) { a[i]=a[i]+a[i+1]; } for(i=0;i<26;i++) { int ans=0; int count=0; char ch=(char)('a'+i); for(j=0;j<s.length();j++) { if(s.charAt(j)==ch) { count++; ans=ans+a[j]; } } System.out.print((ans+count)+" "); } System.out.println(""); } } }
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.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { static int globalVariable = 123456789; static String author = "pl728 on codeforces"; public static void main(String[] args) { FastReader sc = new FastReader(); PrintWriter pw = new PrintWriter(System.out); MathUtils mathUtils = new MathUtils(); ArrayUtils arrayUtils = new ArrayUtils(); int n = sc.ni(); int m = sc.ni(); // if (n == 1) { // System.out.println(1); // return; // } // fix [L,R] // // 1! to 250000! // long[] factorials = new long[250005]; factorials[0] = 1; for(int i = 1; i <= n; i++) { factorials[i] = ((factorials[i - 1] % m) * (i % m)) % m; } long ans = 0; for (int length = 1; length <= n; length++) { // for each length of [L,R] we have (n - len + 1)! * (len)! permutations // for each length [l, r] we have len pairs long temp = ((factorials[n - length + 1] % m) * (factorials[length] * length % m)) % m; ans = ((ans % m) + (temp % m)) % m; } System.out.println(ans); } static class FastReader { /** * Uses BufferedReader and StringTokenizer for quick java I/O * get next int, long, double, string * get int, long, double, string arrays, both primitive and wrapped object when array contains all elements * on one line, and we know the array size (n) * next: gets next space separated item * nextLine: returns entire line as space */ BufferedReader br; StringTokenizer st; public FastReader() { this.br = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } // to parse something else: // T x = T.parseT(fastReader.next()); public int ni() { return Integer.parseInt(next()); } public String ns() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public String[] readStringArrayLine(int n) { String line = ""; try { line = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return line.split(" "); } public String[] readStringArrayLines(int n) { String[] result = new String[n]; for (int i = 0; i < n; i++) { result[i] = this.next(); } return result; } public int[] readIntArray(int n) { int[] result = new int[n]; for (int i = 0; i < n; i++) { result[i] = this.ni(); } return result; } public long[] readLongArray(int n) { long[] result = new long[n]; for (int i = 0; i < n; i++) { result[i] = this.nl(); } return result; } public Integer[] readIntArrayObject(int n) { Integer[] result = new Integer[n]; for (int i = 0; i < n; i++) { result[i] = this.ni(); } return result; } public long nl() { return Long.parseLong(next()); } public char[] readCharArray(int n) { return this.ns().toCharArray(); } } static class MathUtils { public MathUtils() { } public long gcdLong(long a, long b) { if (a % b == 0) return b; else return gcdLong(b, a % b); } public long lcmLong(long a, long b) { return a * b / gcdLong(a, b); } } static class ArrayUtils { public ArrayUtils() { } public static int[] reverse(int[] a) { int n = a.length; int[] b = new int[n]; int j = n; for (int i = 0; i < n; i++) { b[j - 1] = a[i]; j = j - 1; } return b; } public int sumIntArrayInt(int[] a) { int ans = 0; for (int i = 0; i < a.length; i++) { ans += a[i]; } return ans; } public long sumLongArrayLong(int[] a) { long ans = 0; for (int i = 0; i < a.length; i++) { ans += a[i]; } return ans; } } public static int lowercaseToIndex(char c) { return (int) c - 97; } }
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.StringTokenizer; public class LetterA { static class Point{ long x,y; Point(long x, long y){ this.x=x; this.y=y; } } static class Segment{ long x1,y1,x2,y2; Point p1,p2; Segment(String sr){ StringTokenizer st= new StringTokenizer(sr); this.x1=Integer.parseInt(st.nextToken()); this.y1=Integer.parseInt(st.nextToken()); this.x2=Integer.parseInt(st.nextToken()); this.y2=Integer.parseInt(st.nextToken()); this.p1= new Point(x1,y1); this.p2=new Point(x2,y2); } } static boolean acute(Point p1, Point p2, Point p3){ long area=(long)(p1.x-p3.x)*(p2.y-p3.y)-(long)(p1.y-p3.y)*(p2.x-p3.x); long a=(long)(p1.x-p3.x)*(p1.x-p3.x)+(long) (p1.y-p3.y)*(p1.y-p3.y) ; long b=(long)(p2.x-p3.x)*(p2.x-p3.x)+(long) (p2.y-p3.y)*(p2.y-p3.y); long c=(long)(p2.x-p1.x)*(p2.x-p1.x)+(long) (p2.y-p1.y)*(p2.y-p1.y); return area!=0 && c<=a+b; } static boolean verticalSegment(Segment a, Segment b){ if(a.p1.x==b.p1.x && a.p1.y==b.p1.y){ return acute(a.p2,b.p2,a.p1); } if(a.p2.x==b.p2.x && a.p2.y==b.p2.y){ return acute(a.p1,b.p1,a.p2); } if(a.p1.x==b.p2.x && a.p1.y==b.p2.y){ return acute(a.p2,b.p1,a.p1); } if(a.p2.x==b.p1.x && a.p2.y==b.p1.y){ return acute(a.p1,b.p2,a.p2); } return false; } static boolean intersecting(Segment s,Point p){ if(p.x<Math.min(s.p1.x,s.p2.x) || p.x>Math.max(s.p1.x,s.p2.x) || p.y<Math.min(s.p1.y,s.p2.y)|| p.y>Math.max(s.p1.y,s.p2.y)) return false; int x=(int) Math.abs(s.p1.x-s.p2.x); int y= (int) Math.abs(s.p1.y-s.p2.y); int xm= (int) Math.min(Math.abs(s.p1.x-p.x),Math.abs(s.p2.x-p.x)); int ym= (int) Math.min(Math.abs(s.p1.y-p.y),Math.abs(s.p2.y-p.y)); return x<=5*xm && y<=5*ym && (long)(p.x-s.p2.x)*(s.p1.y-s.p2.y)==(long)(p.y-s.p2.y)*(s.p1.x-s.p2.x); } static boolean check(Segment a, Segment b, Segment c){ return verticalSegment(a,b) && (intersecting(a,c.p1) && intersecting(b,c.p2) || intersecting(b,c.p1) && intersecting(a,c.p2)); } 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++) { Segment a=new Segment(br.readLine()); Segment b= new Segment(br.readLine()); Segment c= new Segment(br.readLine()); System.out.println(check(a,b,c)||check(b,c,a)||check(c,a,b)?"YES":"NO"); } } }
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" ]
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(); int a[] = sc.readIntArray(n); HashMap<Long, List<int[]>> map = new HashMap<>(); for (int i = 0; i < n; i++) { long sum = 0; for (int j = i; j < n; j++) { sum += (long) a[j]; map.putIfAbsent(sum, new ArrayList<>()); map.get(sum).add(new int[] { i + 1, j + 1 }); } } List<int[]> ans = new ArrayList<>(); for (long key : map.keySet()) { List<int[]> al = new ArrayList<>(); for (int i = map.get(key).size() - 1; i >= 0; i--) { if (al.isEmpty() || al.get(al.size() - 1)[0] > map.get(key).get(i)[1]) { al.add(map.get(key).get(i)); } } if (al.size() > ans.size()) { ans = al; } } out.println(ans.size()); for (int x[] : ans) out.println(x[0] + " " + x[1]); } 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
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" ]
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; public class C1320D { static long modulo1 = (long) 1e9 + 9; static long modulo2 = (long) 1e9 + 9;//7; static long r1 = 3; static long r2 = 5; static int[] bits1 = new int[]{1, 2}; static int[] bits2 = new int[]{2, 3}; public static void main(String[] args) { var scanner = new BufferedScanner(); var writer = new PrintWriter(new BufferedOutputStream(System.out)); var n = scanner.nextInt(); var t = scanner.next(); var count0 = new int[n + 1]; { count0[0] = 0; for (int len = 1; len <= n; len++) { count0[len] = count0[len - 1] + (t.charAt(len - 1) == '0' ? 1 : 0); } } var power1 = new long[n + 1]; var power2 = new long[n + 1]; power1[0] = 1; power2[0] = 1; for (int i = 1; i <= n; i++) { power1[i] = power1[i - 1] * r1 % modulo1; power2[i] = power2[i - 1] * r2 % modulo2; } var hashEven1 = new long[n + 1][]; var hashOdd1 = new long[n + 1][]; calcHash(t, n, power1, hashEven1, hashOdd1, count0, modulo1, r1, bits1); var hashEven2 = new long[n + 1][]; var hashOdd2 = new long[n + 1][]; calcHash(t, n, power2, hashEven2, hashOdd2, count0, modulo2, r2, bits2); var q = scanner.nextInt(); for (int qi = 0; qi < q; qi++) { var l1 = scanner.nextInt() - 1; var l2 = scanner.nextInt() - 1; var len = scanner.nextInt(); var ans = false; // 首先,0的个数得一样多 if (count0[l1 + len] - count0[l1] == count0[l2 + len] - count0[l2]) { // 其次,从各子串开头算起的0的下标得对应位同奇偶。 var fp11 = fingerprint(l1, l1 + len - 1, power1, hashEven1, hashOdd1, count0, modulo1); var fp21 = fingerprint(l2, l2 + len - 1, power1, hashEven1, hashOdd1, count0, modulo1); var fp12 = fingerprint(l1, l1 + len - 1, power2, hashEven2, hashOdd2, count0, modulo2); var fp22 = fingerprint(l2, l2 + len - 1, power2, hashEven2, hashOdd2, count0, modulo2); // System.out.println(String.format("[%d] %d,%d %d,%d", qi + 1, fp11, fp21, fp12, fp22)); if (fp11 == fp21 && fp12 == fp22) { ans = true; } } writer.println(ans ? "Yes" : "No"); } scanner.close(); writer.flush(); writer.close(); } private static void calcHash(String t, int n, long[] power, long[][] hashEven, long[][] hashOdd, int[] count0, long modulo, long r, int[] bits) { var limit = r * modulo; // System.out.println(String.format("modulo=%d,r=%d,bits=%s", modulo, r, Arrays.toString(bits))); for (int len = 1; len <= n; len <<= 1) { hashEven[len] = new long[n]; hashOdd[len] = new long[n]; var he = 0L; var ho = 0L; for (int i = 0; i < n; i++) { if (t.charAt(i) == '0') { var bitEven = bits[i & 1]; // 对偶数开头子字符串来说,i是偶数在子字符串也是偶数位,用0表示;否则用1。 var bitOdd = bits[1 - (i & 1)]; // 对奇数位开头的子字符串来说,i是偶数在子字符串是奇数位,用1表示;否则用0。 he = (he * r + bitEven) % modulo; ho = (ho * r + bitOdd) % modulo; } if (i >= len && t.charAt(i - len) == '0') { var bitEven0 = bits[(i - len) & 1]; var bitOdd0 = bits[1 - ((i - len) & 1)]; var cnt0 = count0[i + 1] - count0[i + 1 - len]; he = (he + limit - power[cnt0] * bitEven0) % modulo; // power[cnt0]*bitEven0<modulo*r ho = (ho + limit - power[cnt0] * bitOdd0) % modulo; // power[cnt0]*bitOdd0<modulo*r } if (i >= len - 1) { hashEven[len][i - len + 1] = he; hashOdd[len][i - len + 1] = ho; } if (he < 0 || ho < 0) { throw new RuntimeException("wtf"); } } } } private static long fingerprint(int start, int end, long[] power, long[][] hashEven, long[][] hashOdd, int[] count0, long modulo) { if ((start & 1) == 0) { return fingerprint(start, end, power, hashEven, count0, modulo); } else { return fingerprint(start, end, power, hashOdd, count0, modulo); } } private static long fingerprint(int start, int end, long[] power, long[][] hash, int[] count0, long modulo) { var len = 1 << (int) (Math.log(end - start + 1) / Math.log(2)); var fp = 0L; while (start <= end) { var cnt0 = count0[start + len] - count0[start]; fp = (fp * power[cnt0] + hash[len][start]) % modulo; if (fp < 0) { throw new RuntimeException("wtf"); } start += len; while (len > 0 && start + len - 1 > end) { len >>= 1; } } return fp; } public static class BufferedScanner { BufferedReader br; StringTokenizer st; public BufferedScanner(Reader reader) { br = new BufferedReader(reader); } public BufferedScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } static long gcd(long a, long b) { if (a < b) { return gcd(b, a); } while (b > 0) { long tmp = b; b = a % b; a = tmp; } return a; } static long inverse(long a, long m) { long[] ans = extgcd(a, m); return ans[0] == 1 ? (ans[1] + m) % m : -1; } private static long[] extgcd(long a, long m) { if (m == 0) { return new long[]{a, 1, 0}; } else { long[] ans = extgcd(m, a % m); long tmp = ans[1]; ans[1] = ans[2]; ans[2] = tmp; ans[2] -= ans[1] * (a / m); return ans; } } private static List<Integer> primes(double upperBound) { var limit = (int) Math.sqrt(upperBound); var isComposite = new boolean[limit + 1]; var primes = new ArrayList<Integer>(); for (int i = 2; i <= limit; i++) { if (isComposite[i]) { continue; } primes.add(i); int j = i + i; while (j <= limit) { isComposite[j] = true; j += i; } } return primes; } }
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 Scanner obj = new Scanner(System.in); public static PrintWriter out = new PrintWriter(System.out); public static class Node { int[] a=new int[27]; } public static void main(String[] args) { int len = 1; while (len-- != 0) { String s=obj.next(); int n=s.length(); Node[] a=new Node[n+1]; a[n]=new Node(); for(int i=n-1;i>=0;i--) { a[i]=new Node(); a[i].a[s.charAt(i)-'a']=1; for(int j=0;j<27;j++) a[i].a[j]+=a[i+1].a[j]; } long ans=0; HashMap<String,Long> map=new HashMap<>(); for(int i=0;i<n;i++) { for(int j=0;j<26;j++) { StringBuffer sb=new StringBuffer(); sb.append(s.charAt(i)); sb.append((char)('a'+j)); if(a[i+1].a[j]>0)map.put(sb.toString(), map.getOrDefault(sb.toString(), 0L)+a[i+1].a[j]); } } for(int i=0;i<27;i++)ans=Math.max(ans, a[0].a[i]); for(Map.Entry<String,Long> m:map.entrySet()) { ans=Math.max(ans,m.getValue()); } out.println(ans); } out.flush(); } }
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" ]
// 17-05 // import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class C { static class SGTree { int seg[]; SGTree(int n) { seg = new int[n]; } void build(int idx, int low, int high, int a[]) { if (low == high) { seg[idx] = a[low]; return; } int mid = (low + high) / 2; build(2 * idx + 1, low, mid, a); build(2 * idx + 2, mid + 1, high, a); seg[idx] = Math.min(seg[2 * idx + 1], seg[2 * idx + 2]); } int query(int idx, int low, int high, int l, int r) { // min value query // no overlap if (l > high || r < low) { return inf; } // complete overlap if (l <= low && r >= high) { return seg[idx]; } // partial overlap int mid = (low + high) / 2; int left = query(2 * idx + 1, low, mid, l, r); int right = query(2 * idx + 2, mid + 1, high, l, r); return Math.min(left, right); } } static int par[], rank[]; static void union(int a, int b) { if (rank[a] > rank[b]) { rank[a]++; par[b] = par[a]; } else { rank[b]++; par[a] = par[b]; } } static int get(int a) { if (a == par[a]) return a; return par[a] = get(par[a]); } static String temp; static char s[], t[]; static int n, m; static int dp[][][]; static List<Integer> g[]; static boolean is[], vis[]; public static void main(String[] args) { Scanner sc = new Scanner(); int tt = sc.nextInt(); o: while (tt-- > 0) { n = sc.nextInt(); int a[] = sc.readArray(n); int idx = n - 1; for (int i = 0; i < n; i++) { if (a[i] < i) { idx = i - 1; break; } } if (idx == -1 || idx == n - 1) { System.out.println("YES"); continue o; } for (int i = idx + 1; i < n; i++) { if (a[i] < n - i - 1) { System.out.println("NO"); continue o; } } if (a[idx] <= a[idx + 1] && a[idx + 1] == n - idx - 2) { System.out.println("NO"); continue o; } System.out.println("YES"); } } static class pp implements Comparable<pp> { int a; int b; pp(int a, int b) { this.a = a; this.b = b; } public int compareTo(pp o) { return this.a - o.a; } } static class Scanner { 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()); } double nextDouble() { return Double.parseDouble(next()); } String str = ""; String nextLine() { try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } static void sort(int[] a) { int n = a.length; Random r = new Random(); for (int i = 0; i < a.length; i++) { int oi = r.nextInt(n), temp = a[i]; a[i] = a[oi]; a[oi] = temp; } Arrays.sort(a); } static final int M = 1_000_000_007; static final int inf = Integer.MAX_VALUE; static final int ninf = inf + 1; }
java
1304
F1
F1. Animal Observation (easy version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤min(m,20)1≤k≤min(m,20)) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2 0 2 1 1 0 0 0 3 1 2 1 0 4 3 1 3 3 0 0 4 OutputCopy25 InputCopy3 3 1 1 2 3 4 5 6 7 8 9 OutputCopy31 InputCopy3 3 2 1 2 3 4 5 6 7 8 9 OutputCopy44 InputCopy3 3 3 1 2 3 4 5 6 7 8 9 OutputCopy45 NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4:
[ "data structures", "dp" ]
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.StringTokenizer; public class F { static int n, m, k; static int[][] ani; // animals public static void main(String[] args) { var scanner = new BufferedScanner(); var writer = new PrintWriter(new BufferedOutputStream(System.out)); n = scanner.nextInt(); m = scanner.nextInt(); k = scanner.nextInt(); ani = new int[n + 1][m + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { ani[i][j] = scanner.nextInt(); } } writer.println(solve()); scanner.close(); writer.flush(); writer.close(); } private static int solve() { dfsCache = new int[n + 1][m + 1]; for (var i = 1; i <= n; i++) { Arrays.fill(dfsCache[i], -1); } leftMaxCache = new int[n + 1][m + 1]; leftMaxAlready = new int[n + 1]; Arrays.fill(leftMaxAlready, 0); for (int i = 1; i <= n; i++) { Arrays.fill(leftMaxCache[i], -1); leftMaxCache[i][0] = 0; } rightMaxCache = new int[n + 1][m + 2]; rightMaxAlready = new int[n + 1]; Arrays.fill(rightMaxAlready, m - k + 2); for (int i = 1; i <= n; i++) { Arrays.fill(rightMaxCache[i], -1); rightMaxCache[i][m - k + 2] = 0; } rangeCache = new int[n + 1][m + 1]; for (int i = 1; i <= n; i++) { rangeCache[i][0] = 0; for (int j = 1; j <= m; j++) { rangeCache[i][j] = rangeCache[i][j - 1] + ani[i][j]; } } var ans = 0; for (int start = 1; start + k - 1 <= m; start++) { ans = Math.max(ans, dfs(2, start) + range(1, start, start + k - 1)); } return ans; } static int[][] dfsCache; private static int dfs(int row, int lastStart) { if (row > n) { return 0; } if (dfsCache[row][lastStart] >= 0) { return dfsCache[row][lastStart]; } var ans = 0; var lastEnd = lastStart + k - 1; // no intersection { int ans0 = leftMax(row, lastStart - 1); ans = Math.max(ans, ans0 + range(row, lastStart, lastEnd)); } { int ans0 = rightMax(row, lastEnd + 1); ans = Math.max(ans, ans0 + range(row, lastStart, lastEnd)); } // intersected for (int thisStart = Math.max(1, lastStart - k + 1); thisStart <= lastEnd && thisStart + k - 1 <= m; thisStart++) { var ans1 = dfs(row + 1, thisStart) + watch(row, lastStart, thisStart); ans = Math.max(ans, ans1); } return dfsCache[row][lastStart] = ans; } static int[][] rightMaxCache; static int[] rightMaxAlready; private static int rightMax(int row, int minStart) { if (minStart + k - 1 > m) { return 0; } if (rightMaxCache[row][minStart] >= 0) { return rightMaxCache[row][minStart]; } var ans0 = rightMaxCache[row][rightMaxAlready[row]]; for (int start = rightMaxAlready[row] - 1; start >= minStart; start--) { if (rightMaxCache[row][start] >= 0) { continue; } var end = start + k - 1; var ans1 = dfs(row + 1, start) + range(row, start, end); rightMaxCache[row][start] = Math.max(rightMaxCache[row][start + 1], ans1); ans0 = Math.max(ans0, ans1); } rightMaxAlready[row] = minStart; assert ans0 == rightMaxCache[row][minStart]; return ans0; } static int[][] leftMaxCache; static int[] leftMaxAlready; private static int leftMax(int row, int maxEnd) { var maxStart = maxEnd - k + 1; if (maxStart <= 0) { return 0; } if (leftMaxCache[row][maxStart] >= 0) { return leftMaxCache[row][maxStart]; } var ans0 = leftMaxCache[row][leftMaxAlready[row]]; for (int start = leftMaxAlready[row] + 1; start <= maxStart; start++) { var end = start + k - 1; if (leftMaxCache[row][start] >= 0) { continue; } var ans1 = dfs(row + 1, start) + range(row, start, end); leftMaxCache[row][start] = Math.max(leftMaxCache[row][start - 1], ans1); ans0 = Math.max(ans0, ans1); } leftMaxAlready[row] = maxStart; assert ans0 == leftMaxCache[row][maxStart]; return leftMaxCache[row][maxStart]; } private static int watch(int row, int start1, int start2) { if (start1 > start2) { return watch(row, start2, start1); } var end2 = start2 + k - 1; if (start1 <= 0) { return range(row, start2, end2); } var end1 = start1 + k - 1; if (end2 < start1 || end1 < start2) { return range(row, start1, end1) + range(row, start2, end2); } return range(row, start1, end1) + range(row, start2, end2) - range(row, start2, Math.min(end1, end2)); } static int[][] rangeCache; private static int range(int row, int start, int end) { if (start <= 0 || start > end) { return 0; } return rangeCache[row][end] - rangeCache[row][start - 1]; } static final boolean DEBUG = false; private static void debug(String fmt, Object... args) { if (DEBUG) { System.out.println(String.format(fmt, args)); } } public static class BufferedScanner { BufferedReader br; StringTokenizer st; public BufferedScanner(Reader reader) { br = new BufferedReader(reader); } public BufferedScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } static long gcd(long a, long b) { if (a < b) { return gcd(b, a); } while (b > 0) { long tmp = b; b = a % b; a = tmp; } return a; } static long inverse(long a, long m) { long[] ans = extgcd(a, m); return ans[0] == 1 ? (ans[1] + m) % m : -1; } private static long[] extgcd(long a, long m) { if (m == 0) { return new long[]{a, 1, 0}; } else { long[] ans = extgcd(m, a % m); long tmp = ans[1]; ans[1] = ans[2]; ans[2] = tmp; ans[2] -= ans[1] * (a / m); return ans; } } private static List<Integer> primes(double upperBound) { var limit = (int) Math.sqrt(upperBound); var isComposite = new boolean[limit + 1]; var primes = new ArrayList<Integer>(); for (int i = 2; i <= limit; i++) { if (isComposite[i]) { continue; } primes.add(i); int j = i + i; while (j <= limit) { isComposite[j] = true; j += i; } } return primes; } }
java
1316
E
E. Team Buildingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAlice; the president of club FCB, wants to build a team for the new volleyball tournament. The team should consist of pp players playing in pp different positions. She also recognizes the importance of audience support, so she wants to select kk people as part of the audience.There are nn people in Byteland. Alice needs to select exactly pp players, one for each position, and exactly kk members of the audience from this pool of nn people. Her ultimate goal is to maximize the total strength of the club.The ii-th of the nn persons has an integer aiai associated with him — the strength he adds to the club if he is selected as a member of the audience.For each person ii and for each position jj, Alice knows si,jsi,j  — the strength added by the ii-th person to the club if he is selected to play in the jj-th position.Each person can be selected at most once as a player or a member of the audience. You have to choose exactly one player for each position.Since Alice is busy, she needs you to help her find the maximum possible strength of the club that can be achieved by an optimal choice of players and the audience.InputThe first line contains 33 integers n,p,kn,p,k (2≤n≤105,1≤p≤7,1≤k,p+k≤n2≤n≤105,1≤p≤7,1≤k,p+k≤n).The second line contains nn integers a1,a2,…,ana1,a2,…,an. (1≤ai≤1091≤ai≤109).The ii-th of the next nn lines contains pp integers si,1,si,2,…,si,psi,1,si,2,…,si,p. (1≤si,j≤1091≤si,j≤109)OutputPrint a single integer resres  — the maximum possible strength of the club.ExamplesInputCopy4 1 2 1 16 10 3 18 19 13 15 OutputCopy44 InputCopy6 2 3 78 93 9 17 13 78 80 97 30 52 26 17 56 68 60 36 84 55 OutputCopy377 InputCopy3 2 1 500 498 564 100002 3 422332 2 232323 1 OutputCopy422899 NoteIn the first sample; we can select person 11 to play in the 11-st position and persons 22 and 33 as audience members. Then the total strength of the club will be equal to a2+a3+s1,1a2+a3+s1,1.
[ "bitmasks", "dp", "greedy", "sortings" ]
import java.util.*; import java.io.*; public class TeamBuilding { // https://codeforces.com/contest/1316/problem/E static int n, p, k; static A[] a; static long[][] s, memo; static int[] map; static long sum=0, INF = (long)(1e15); public static void main(String[] args) throws IOException, FileNotFoundException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //BufferedReader in = new BufferedReader(new FileReader("TeamBuilding")); int t = 1; while (t-- > 0) { StringTokenizer st = new StringTokenizer(in.readLine()); n = Integer.parseInt(st.nextToken()); p = Integer.parseInt(st.nextToken()); k = Integer.parseInt(st.nextToken()); st = new StringTokenizer(in.readLine()); a = new A[n]; map = new int[n]; for (int i=0; i<n; i++) a[i] = new A(Integer.parseInt(st.nextToken()), i); Arrays.parallelSort(a); for (int i=0; i<n; i++ ) { map[a[i].index] = i; if (i<k) sum += a[i].val; } s = new long[n][p]; for (int i=0; i<n; i++) { st = new StringTokenizer(in.readLine()); for (int j=0; j<p; j++) { s[i][j] = Integer.parseInt(st.nextToken()); } } // System.out.println(sum); // System.out.println(Arrays.toString(map)); memo = new long[n][1 << p]; for (int i=0; i<n; i++) { Arrays.fill(memo[i], -1); } long ans = dp(0, 0, 0); // for (int i=0; i<n; i++) { // System.out.println(Arrays.toString(memo[i])); // } System.out.println(ans); } } public static long dp(int index, int mask, int count) { if (index >= n) { if (mask == (1 << p) - 1) { return 0; } return -INF; } if (memo[index][mask] != -1) return memo[index][mask]; // dont take long ans = 0; if (index + 1 - count > k) ans = dp(index+1, mask, count); else ans = dp(index+1, mask, count) + a[index].val; // take for (int i=0; i<p; i++) { if (((mask >> i)&1) == 0) { ans = Math.max(ans, s[a[index].index][i] + dp(index+1, mask + (1 << i), count+1)); } } return memo[index][mask] = ans; } static class A implements Comparable<A> { long val; int index; A (long a, int b) { val = a; index = b; } public int compareTo(A o) { return Long.compare(o.val, val); } } }
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.util.*; public class CF1316_B{ public static void main(String args[]){ Scanner in=new Scanner(System.in); int t=in.nextInt(); while(t-->0){ int n=in.nextInt(); String s=in.next(); String ans=s; String temp=""; int k=1; int count=1; for(int i=1;i<n;i++){ count++; temp=s.substring(i); if((n-count+1)%2==0){ temp+=s.substring(0,i); } else{ StringBuilder sb=new StringBuilder(s.substring(0,i)); temp+=sb.reverse().toString(); } if(temp.compareTo(ans)<0){ ans=temp; k=count; } } System.out.println(ans); System.out.println(k); } } }
java
1311
C
C. Perform the Combotime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou want to perform the combo on your opponent in one popular fighting game. The combo is the string ss consisting of nn lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in ss. I.e. if s=s="abca" then you have to press 'a', then 'b', 'c' and 'a' again.You know that you will spend mm wrong tries to perform the combo and during the ii-th try you will make a mistake right after pipi-th button (1≤pi<n1≤pi<n) (i.e. you will press first pipi buttons right and start performing the combo from the beginning). It is guaranteed that during the m+1m+1-th try you press all buttons right and finally perform the combo.I.e. if s=s="abca", m=2m=2 and p=[1,3]p=[1,3] then the sequence of pressed buttons will be 'a' (here you're making a mistake and start performing the combo from the beginning), 'a', 'b', 'c', (here you're making a mistake and start performing the combo from the beginning), 'a' (note that at this point you will not perform the combo because of the mistake), 'b', 'c', 'a'.Your task is to calculate for each button (letter) the number of times you'll press it.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.Then tt test cases follow.The first line of each test case contains two integers nn and mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤2⋅1051≤m≤2⋅105) — the length of ss and the number of tries correspondingly.The second line of each test case contains the string ss consisting of nn lowercase Latin letters.The third line of each test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n) — the number of characters pressed right during the ii-th try.It is guaranteed that the sum of nn and the sum of mm both does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105, ∑m≤2⋅105∑m≤2⋅105).It is guaranteed that the answer for each letter does not exceed 2⋅1092⋅109.OutputFor each test case, print the answer — 2626 integers: the number of times you press the button 'a', the number of times you press the button 'b', ……, the number of times you press the button 'z'.ExampleInputCopy3 4 2 abca 1 3 10 5 codeforces 2 8 3 2 9 26 10 qwertyuioplkjhgfdsazxcvbnm 20 10 1 2 3 5 10 5 9 4 OutputCopy4 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 9 4 5 3 0 0 0 0 0 0 0 0 9 0 0 3 1 0 0 0 0 0 0 0 2 1 1 2 9 2 2 2 5 2 2 2 1 1 5 4 11 8 2 7 5 1 10 1 5 2 NoteThe first test case is described in the problem statement. Wrong tries are "a"; "abc" and the final try is "abca". The number of times you press 'a' is 44, 'b' is 22 and 'c' is 22.In the second test case, there are five wrong tries: "co", "codeforc", "cod", "co", "codeforce" and the final try is "codeforces". The number of times you press 'c' is 99, 'd' is 44, 'e' is 55, 'f' is 33, 'o' is 99, 'r' is 33 and 's' is 11.
[ "brute force" ]
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 C_Perform_the_Combo { 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) { int n = f.nextInt(); int m = f.nextInt(); String s = f.nextLine(); int arr[] = new int[n]; arr[n-1] = 1; for(int i = 0; i < m; i++) { arr[f.nextInt()-1]++; } for(int i = n-2; i >= 0; i--) { arr[i] += arr[i+1]; } long clickTimes[] = new long[26]; for(int i = 0; i < n; i++) { clickTimes[s.charAt(i)-'a'] += arr[i]; } for(long i: clickTimes) { out.print(i + " "); } out.println(); } 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
1312
E
E. Array Shrinkingtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. You can perform the following operation any number of times: Choose a pair of two neighboring equal elements ai=ai+1ai=ai+1 (if there is at least one such pair). Replace them by one element with value ai+1ai+1. After each such operation, the length of the array will decrease by one (and elements are renumerated accordingly). What is the minimum possible length of the array aa you can get?InputThe first line contains the single integer nn (1≤n≤5001≤n≤500) — the initial length of the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000) — the initial array aa.OutputPrint the only integer — the minimum possible length you can get after performing the operation described above any number of times.ExamplesInputCopy5 4 3 2 2 3 OutputCopy2 InputCopy7 3 3 4 4 4 3 3 OutputCopy2 InputCopy3 1 3 5 OutputCopy3 InputCopy1 1000 OutputCopy1 NoteIn the first test; this is one of the optimal sequences of operations: 44 33 22 22 33 →→ 44 33 33 33 →→ 44 44 33 →→ 55 33.In the second test, this is one of the optimal sequences of operations: 33 33 44 44 44 33 33 →→ 44 44 44 44 33 33 →→ 44 44 44 44 44 →→ 55 44 44 44 →→ 55 55 44 →→ 66 44.In the third and fourth tests, you can't perform the operation at all.
[ "dp", "greedy" ]
/* Dynamic Programming Solution Repace two consecutive equal values with one greater value */ import java.util.*; import java.lang.*; import java.io.*; public class ReplaceConsecutiveEqualElements { // Method to return minimum of two values public static int min(int a, int b) { if(a>b) return b; return a; } // Method to replace consecutive equal elements // with a one greater value // It recieves the array and the size of array // as parameter public static int replaceConsecutiveEqualElements(int arr[], int n) { /* Creating two arrays to build the solution in a bottom up manner dp[i][j] = Number of elements remaining after replacing consecutive equal elememts with one greater value in arr[i..j] element[i][j] = The result value after replacing consecutive equal elememts with one greater value in arr[i..j] */ int[][] dp = new int[n+1][n+1]; int[][] element = new int[n+1][n+1]; int i, j, k, len; // For length = 1 for(i = 1; i <= n; i++) { dp[i][i] = 1; element[i][i] = arr[i]; } // Initialising the dp[i][j] with the number of elements // in the range i..j for (i = 1; i <= n; i++) { for (j = i; j <= n; j++) { dp[i][j] = j - i + 1; } } // len is the length of array considering at a time // Building the solution in a bottom up manner // The loop structure is same as Matrix Chain Multiplication for(len = 2; len <= n; len++) { // For all segments of length len // different possible starting indexes for(i = 1; i + len - 1 <= n; i++) { j = i + len - 1; for (k = i; k < j; k++) { // updating the length of segment in i..j dp[i][j] = min (dp[i][j], (dp[i][k] + dp[k + 1][j])); // if segment i..k and k+1..j both have been converted to // unit length and the value in both segment is same // update dp[i][j] to unity and // element[i][j] to either element[i][k]+1 or element[k+1][j]+1 if ((dp[i][k] == 1) && (dp[k + 1][j]==1) && (element[i][k] == element[k + 1][j])) { dp[i][j] = 1; element[i][j] = element[i][k]+1; } } } } // Return the number of values remaining in the array[1..n] return dp[1][n]; } // Driver Code public static void main(String[] args) { Scanner sc = new Scanner(System.in); // The size of the array int n = sc.nextInt(); // Accepting the array int i; int[] arr = new int[n+1]; for(i = 1; i <= n; i++) { int key = sc.nextInt(); arr[i] = key; } // Calling the function and Printing the result System.out.println("" + replaceConsecutiveEqualElements(arr, n)); } }
java
1294
E
E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3 3 2 1 1 2 3 4 5 6 OutputCopy6 InputCopy4 3 1 2 3 4 5 6 7 8 9 10 11 12 OutputCopy0 InputCopy3 4 1 6 3 4 5 10 7 8 9 2 11 12 OutputCopy2 NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22.
[ "greedy", "implementation", "math" ]
import java.io.*; import java.util.*; public class cf { public static void main(String[] args) throws IOException { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(r.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int[][] stor = new int[n][m]; for (int i = 0; i < n; i++) { st = new StringTokenizer(r.readLine()); for (int j = 0; j < m; j++) { stor[i][j] = Integer.parseInt(st.nextToken())-1; } } //for (int[] i: stor) pw.println(Arrays.toString(i)); int ans = 0; for (int j = 0; j < m; j++) {//j stands for column :) HashMap<Integer, Integer> place = new HashMap<>(n); for (int i = 0; i < n; i++) { if (stor[i][j]%m == j&& stor[i][j] < n*m) {//check if element belongs in column int val = ((i - stor[i][j]/m)%n+n)%n; add(place, val); } } int min = n; for (int i: place.keySet()) { min = Math.min(min, n-place.get(i)+i); } ans += min; //System.out.println(place); //System.out.println(min); } pw.println(ans); pw.close(); } static void add(Map<Integer, Integer> map, int val) { if (!map.containsKey(val)) map.put(val, 1); else map.put(val, map.get(val)+1); } }
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.*; public class codeforce { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t=sc.nextInt(); for(int i=0;i<t;i++) { int n=sc.nextInt(); int t1=n; int sum=0; int r=n/10; n-=r*10; n+=r; while(n>=10) { int r1=n/10; r+=r1; n-=r1*10; n+=r1; } System.out.println(t1+r); } } }
java
1323
B
B. Count Subrectanglestime limit per test1 secondmemory limit per test512 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn and array bb of length mm both consisting of only integers 00 and 11. Consider a matrix cc of size n×mn×m formed by following rule: ci,j=ai⋅bjci,j=ai⋅bj (i.e. aiai multiplied by bjbj). It's easy to see that cc consists of only zeroes and ones too.How many subrectangles of size (area) kk consisting only of ones are there in cc?A subrectangle is an intersection of a consecutive (subsequent) segment of rows and a consecutive (subsequent) segment of columns. I.e. consider four integers x1,x2,y1,y2x1,x2,y1,y2 (1≤x1≤x2≤n1≤x1≤x2≤n, 1≤y1≤y2≤m1≤y1≤y2≤m) a subrectangle c[x1…x2][y1…y2]c[x1…x2][y1…y2] is an intersection of the rows x1,x1+1,x1+2,…,x2x1,x1+1,x1+2,…,x2 and the columns y1,y1+1,y1+2,…,y2y1,y1+1,y1+2,…,y2.The size (area) of a subrectangle is the total number of cells in it.InputThe first line contains three integers nn, mm and kk (1≤n,m≤40000,1≤k≤n⋅m1≤n,m≤40000,1≤k≤n⋅m), length of array aa, length of array bb and required size of subrectangles.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), elements of aa.The third line contains mm integers b1,b2,…,bmb1,b2,…,bm (0≤bi≤10≤bi≤1), elements of bb.OutputOutput single integer — the number of subrectangles of cc with size (area) kk consisting only of ones.ExamplesInputCopy3 3 2 1 0 1 1 1 1 OutputCopy4 InputCopy3 5 4 1 1 1 1 1 1 1 1 OutputCopy14 NoteIn first example matrix cc is: There are 44 subrectangles of size 22 consisting of only ones in it: In second example matrix cc is:
[ "binary search", "greedy", "implementation" ]
import java.io.BufferedReader; import java.io.*; import java.util.*; public class b { static BufferedReader br; static long mod = 1000000000 + 7; static HashSet<Integer> p = new HashSet<>(); static boolean debug =true; // Arrays.sort(time , (a1,a2) -> (a1[0]-a2[0])); 2d array sort lamda public static void main(String[] args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pr = new PrintWriter(System.out); int tc = 1; int[] nk = readArray(3,0,0); int[] row = readArray(nk[0],0,0); int[] col =readArray(nk[1],0,0) ; int n =nk[0]; int k = nk[2]; long ans=0; for(int i=1;i*i<=k;i++){ int mod =k%i; if(mod!=0)continue; int j = k/i; // i*j long x1= rows(i,row); long x2 =rows(j,col); ans+=(x1*x2); //System.out.println(i+" "+j +" "+x1+" "+x2+" i*j "); //j*i if(j==i){ continue; } x1 = rows(j,row); x2 =rows(i,col); //System.out.println(j+" "+i +" "+x1+" "+x2+" j*i "); ans+=(x1*x2); //System.out.println(ans); } System.out.println(ans); } public static long rows(int cons,int[] row){ long ans=0; int sum=0; for(int i=0;i<row.length;i++){ if(row[i]==0){ sum=0; continue; } sum+=row[i]; if(sum>=cons){ ans+=1; } } return ans; } public static <E> void print(String var ,E e){ if(debug==true){ System.out.println(var +" "+e); } } private static long[] sort(long[] e){ ArrayList<Long> x=new ArrayList<>(); for(long c:e){ x.add(c); } Collections.sort(x); long[] y = new long[e.length]; for(int i=0;i<x.size();i++){ y[i]=x.get(i); } return y; } public static void printDp(long[][] dp) { int n = dp.length; for (int i = 0; i < n; i++) { for (int j = 0; j < dp[0].length; j++) { System.out.print(dp[i][j] + " "); } System.out.println(); } } private static long gcd(long a, long b) { if (a == 0) return b; if (b == 0) return a; // base case if (a == b) return a; // a is greater if (a > b) return gcd(a % b, b); return gcd(a, b % a); } public static long min(long a, long b) { return Math.min(a, b); } public static int min(int a, int b) { return Math.min(a, b); } public static void sieve() { int[] pf = new int[100000000 + 1]; //0 prime //1 not prime pf[0] = 1; pf[1] = 1; for (int j = 2; j <= 10000; j++) { if (pf[j] == 0) { p.add(j); for (int k = j * j; k < pf.length; k += j) { pf[k] = 1; } } } } public static int[] readArray(int n, int x, int z) throws Exception { int[] arr = new int[n]; String[] ar = cinA(); for (int i = x; i < n + x; i++) { arr[i] = getI(ar[i - x]); } return arr; } public static long[] readArray(int n, int x) throws Exception { long[] arr = new long[n]; String[] ar = cinA(); for (int i = x; i < n + x; i++) { arr[i] = getL(ar[i - x]); } return arr; } public static void arrinit(String[] a, long[] b) throws Exception { for (int i = 0; i < a.length; i++) { b[i] = Long.parseLong(a[i]); } } public static HashSet<Integer>[] Graph(int n, int edge, int directed) throws Exception { HashSet<Integer>[] tree = new HashSet[n]; for (int j = 0; j < edge; j++) { String[] uv = cinA(); int u = getI(uv[0]); int v = getI(uv[1]); if (directed == 0) { tree[v].add(u); } tree[u].add(v); } return tree; } public static void arrinit(String[] a, int[] b) throws Exception { for (int i = 0; i < a.length; i++) { b[i] = Integer.parseInt(a[i]); } } static double findRoots(int a, int b, int c) { // If a is 0, then equation is not //quadratic, but linear int d = b * b - 4 * a * c; double sqrt_val = Math.sqrt(Math.abs(d)); // System.out.println("Roots are real and different \n"); return Math.max((double) (-b + sqrt_val) / (2 * a), (double) (-b - sqrt_val) / (2 * a)); } public static String cin() throws Exception { return br.readLine(); } public static String[] cinA() throws Exception { return br.readLine().split(" "); } public static String[] cinA(int x) throws Exception { return br.readLine().split(""); } public static String ToString(Long x) { return Long.toBinaryString(x); } public static void cout(String s) { System.out.println(s); } public static Integer cinI() throws Exception { return Integer.parseInt(br.readLine()); } public static int getI(String s) throws Exception { return Integer.parseInt(s); } public static long getL(String s) throws Exception { return Long.parseLong(s); } public static long max(long a, long b) { return Math.max(a, b); } public static int max(int a, int b) { return Math.max(a, b); } public static void coutI(int x) { System.out.println(String.valueOf(x)); } public static void coutI(long x) { System.out.println(String.valueOf(x)); } public static Long cinL() throws Exception { return Long.parseLong(br.readLine()); } public static void arrInit(String[] arr, int[] arr1) throws Exception { for (int i = 0; i < arr.length; i++) { arr1[i] = getI(arr[i]); } } }
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 javax.print.attribute.HashAttributeSet; import java.util.*; import java.lang.*; import java.io.*; public class Solution { static Map<Integer, Set<Integer>> map = new HashMap<>(); static HashSet<Integer> leafList = new HashSet<>(); static int n; 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 = 0; t < test; t++) { solve(); } out.close(); } private static void solve() { n = sc.nextInt(); for (int i = 0; i < n; i++) { map.put(i, new HashSet<>()); } for (int i = 0; i < n - 1; i++) { int x = sc.nextInt() - 1; int y = sc.nextInt() - 1; map.get(x).add(y); map.get(y).add(x); } leafList = new HashSet<>(); for (int i = 0; i < n; i++) { if (map.get(i).size() == 1) { leafList.add(i); } } while (leafList.size() > 1) { int u = leafList.iterator().next(); leafList.remove(u); int v = leafList.iterator().next(); leafList.remove(v); int w = ask(u, v); if (w == u || w == v) { answer(w); return; } removeLeaf(u, -1, w); removeLeaf(v, -1, w); if (map.get(w).size() <= 1) { leafList.add(w); } } answer(leafList.iterator().next()); } private static void removeLeaf(int leaf, int prev, int lca) { if (leafList.contains(leaf)) { leafList.remove(leaf); } for (int adj : map.get(leaf)) { if (adj == prev) { continue; } if (adj == lca) { map.get(adj).remove(leaf); }else if (map.get(adj).size() > 0) { removeLeaf(adj, leaf, lca); } } map.get(leaf).clear(); } private static void answer(int root) { out.println("! " + (root + 1)); out.flush(); } private static int ask(int u, int v) { out.println("? " + (u + 1) + " " + (v + 1)); out.flush(); int w = sc.nextInt() - 1; return w; } public static FastReader sc; public static PrintWriter out; 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
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.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); int t = input.nextInt(); while (t > 0) { int a = input.nextInt(); int b = input.nextInt(); int x = input.nextInt(); int y = input.nextInt(); int x1 = a * (y); int x2 = b * (x); int y1 = a * (b - y - 1); int y2 = b * (a - x - 1); System.out.println(Math.max(x1, Math.max(x2, Math.max(y1, y2)))); t--; } } }
java
1311
B
B. WeirdSorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa of length nn.You are also given a set of distinct positions p1,p2,…,pmp1,p2,…,pm, where 1≤pi<n1≤pi<n. The position pipi means that you can swap elements a[pi]a[pi] and a[pi+1]a[pi+1]. You can apply this operation any number of times for each of the given positions.Your task is to determine if it is possible to sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps.For example, if a=[3,2,1]a=[3,2,1] and p=[1,2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a=[3,1,2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a=[1,3,2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a=[1,2,3]a=[1,2,3], sorted in non-decreasing order.You can see that if a=[4,1,2,3]a=[4,1,2,3] and p=[3,2]p=[3,2] then you cannot sort the array.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.Then tt test cases follow. The first line of each test case contains two integers nn and mm (1≤m<n≤1001≤m<n≤100) — the number of elements in aa and the number of elements in pp. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100). The third line of the test case contains mm integers p1,p2,…,pmp1,p2,…,pm (1≤pi<n1≤pi<n, all pipi are distinct) — the set of positions described in the problem statement.OutputFor each test case, print the answer — "YES" (without quotes) if you can sort the initial array in non-decreasing order (a1≤a2≤⋯≤ana1≤a2≤⋯≤an) using only allowed swaps. Otherwise, print "NO".ExampleInputCopy6 3 2 3 2 1 1 2 4 2 4 1 2 3 3 2 5 1 1 2 3 4 5 1 4 2 2 1 4 3 1 3 4 2 4 3 2 1 1 3 5 2 2 1 2 3 3 1 4 OutputCopyYES NO YES YES NO YES
[ "dfs and similar", "sortings" ]
import java.io.*; import java.util.*; public class ProblemD { 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(); int k = in.readInt(); int a[] = new int[n]; int p[] = new int[n]; HashSet<Integer>set = new HashSet<>(); for(int i = 0;i<n;i++)a[i] = in.readInt(); for(int i = 0;i<k;i++)set.add(in.readInt()); while(true){ boolean ok = false; for(int i =0;i<n;i++){ if(i+1<n && a[i]>a[i+1] && set.contains(i+1)){ swap(a,i,i+1); ok = true; } } if(sorted(a) || !ok){ break; } } if(sorted(a))System.out.println("YES"); else System.out.println("NO"); } } public static void swap(int a[],int i, int j){ int t = a[i]; a[i] = a[j]; a[j] = t; } public static boolean sorted(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 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); for(int i = 0;i<arr.length;i++)arr[i] = list.get(i); } static class Pair{ int x,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
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 java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Stack; public class UnusualCompetitions { public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter pr=new PrintWriter(System.out); solve(br,pr); pr.flush(); pr.close(); } public static void solve(BufferedReader br,PrintWriter pr) throws IOException{ int n=Integer.parseInt(br.readLine()); if(n%2!=0){ pr.println(-1); return; } String s=br.readLine(); int countLeft=0; for(int i=0;i<n;i++){ if(s.charAt(i)=='('){ countLeft++; } } if(countLeft!=n/2){ pr.println(-1); return; } int res=0; int unMatchedRight=0; int index=-1; Stack<Character> stack=new Stack<>(); for(int i=0;i<n;i++){ if(s.charAt(i)=='('){ if(unMatchedRight==0){ stack.push('('); } else{ unMatchedRight--; if(unMatchedRight==0){ res+=i-index+1; index=-1; } } } else if(s.charAt(i)==')'){ if(stack.size()!=0&&stack.peek()=='('){ stack.pop(); } else{ if(index==-1){ index=i; } unMatchedRight++; } } } pr.println(res); } }
java
1294
E
E. Obtain a Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a rectangular matrix of size n×mn×m consisting of integers from 11 to 2⋅1052⋅105.In one move, you can: choose any element of the matrix and change its value to any integer between 11 and n⋅mn⋅m, inclusive; take any column and shift it one cell up cyclically (see the example of such cyclic shift below). A cyclic shift is an operation such that you choose some jj (1≤j≤m1≤j≤m) and set a1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,ja1,j:=a2,j,a2,j:=a3,j,…,an,j:=a1,j simultaneously. Example of cyclic shift of the first column You want to perform the minimum number of moves to make this matrix look like this: In other words, the goal is to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (i.e. ai,j=(i−1)⋅m+jai,j=(i−1)⋅m+j) with the minimum number of moves performed.InputThe first line of the input contains two integers nn and mm (1≤n,m≤2⋅105,n⋅m≤2⋅1051≤n,m≤2⋅105,n⋅m≤2⋅105) — the size of the matrix.The next nn lines contain mm integers each. The number at the line ii and position jj is ai,jai,j (1≤ai,j≤2⋅1051≤ai,j≤2⋅105).OutputPrint one integer — the minimum number of moves required to obtain the matrix, where a1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅ma1,1=1,a1,2=2,…,a1,m=m,a2,1=m+1,a2,2=m+2,…,an,m=n⋅m (ai,j=(i−1)m+jai,j=(i−1)m+j).ExamplesInputCopy3 3 3 2 1 1 2 3 4 5 6 OutputCopy6 InputCopy4 3 1 2 3 4 5 6 7 8 9 10 11 12 OutputCopy0 InputCopy3 4 1 6 3 4 5 10 7 8 9 2 11 12 OutputCopy2 NoteIn the first example; you can set a1,1:=7,a1,2:=8a1,1:=7,a1,2:=8 and a1,3:=9a1,3:=9 then shift the first, the second and the third columns cyclically, so the answer is 66. It can be shown that you cannot achieve a better answer.In the second example, the matrix is already good so the answer is 00.In the third example, it is enough to shift the second column cyclically twice to obtain a good matrix, so the answer is 22.
[ "greedy", "implementation", "math" ]
import java.util.*; public class Hello { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int R = sc.nextInt(); int C = sc.nextInt(); int matrix[][] = new int[R][C]; for (int row = 0; row < R; row++) { for (int col = 0; col < C; col++) { matrix[row][col] = sc.nextInt(); matrix[row][col]--; } } long result = 0; for (int col = 0; col < C; col++) { int count[] = new int[R]; for (int row = 0; row < R; row++) { if (matrix[row][col] % C == col) { int pos = matrix[row][col] / C; if (pos < R) { count[(row - pos + R) % R]++; } } } int cur = R - count[0]; for (int row = 1; row < R; row++) { cur = Math.min(cur, R - count[row] + row); } result += cur; } System.out.println(result); } }
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 JavaApplication14 { public static void main(String[] args) { Scanner in = new Scanner(System.in); long x =in.nextLong(),y=in.nextLong(),count = -1,res=0; for (int i = 1 ; i < 2 ; i++) { if(x == y) { System.out.println("0"); break; } else if (y % x == 0) { count = 0; res = y/x; while (res % 2 ==0) { res /= 2; count++; } while (res % 3 == 0) { res/= 3; count++; } if (res != 1) { count = -1; } } System.out.println(count); } } }
java
1307
E
E. Cow and Treatstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a successful year of milk production; Farmer John is rewarding his cows with their favorite treat: tasty grass!On the field, there is a row of nn units of grass, each with a sweetness sisi. Farmer John has mm cows, each with a favorite sweetness fifi and a hunger value hihi. He would like to pick two disjoint subsets of cows to line up on the left and right side of the grass row. There is no restriction on how many cows must be on either side. The cows will be treated in the following manner: The cows from the left and right side will take turns feeding in an order decided by Farmer John. When a cow feeds, it walks towards the other end without changing direction and eats grass of its favorite sweetness until it eats hihi units. The moment a cow eats hihi units, it will fall asleep there, preventing further cows from passing it from both directions. If it encounters another sleeping cow or reaches the end of the grass row, it will get upset. Farmer John absolutely does not want any cows to get upset. Note that grass does not grow back. Also, to prevent cows from getting upset, not every cow has to feed since FJ can choose a subset of them. Surprisingly, FJ has determined that sleeping cows are the most satisfied. If FJ orders optimally, what is the maximum number of sleeping cows that can result, and how many ways can FJ choose the subset of cows on the left and right side to achieve that maximum number of sleeping cows (modulo 109+7109+7)? The order in which FJ sends the cows does not matter as long as no cows get upset. InputThe first line contains two integers nn and mm (1≤n≤50001≤n≤5000, 1≤m≤50001≤m≤5000)  — the number of units of grass and the number of cows. The second line contains nn integers s1,s2,…,sns1,s2,…,sn (1≤si≤n1≤si≤n)  — the sweetness values of the grass.The ii-th of the following mm lines contains two integers fifi and hihi (1≤fi,hi≤n1≤fi,hi≤n)  — the favorite sweetness and hunger value of the ii-th cow. No two cows have the same hunger and favorite sweetness simultaneously.OutputOutput two integers  — the maximum number of sleeping cows that can result and the number of ways modulo 109+7109+7. ExamplesInputCopy5 2 1 1 1 1 1 1 2 1 3 OutputCopy2 2 InputCopy5 2 1 1 1 1 1 1 2 1 4 OutputCopy1 4 InputCopy3 2 2 3 2 3 1 2 1 OutputCopy2 4 InputCopy5 1 1 1 1 1 1 2 5 OutputCopy0 1 NoteIn the first example; FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 22 is lined up on the left side and cow 11 is lined up on the right side. In the second example, FJ can line up the cows as follows to achieve 11 sleeping cow: Cow 11 is lined up on the left side. Cow 22 is lined up on the left side. Cow 11 is lined up on the right side. Cow 22 is lined up on the right side. In the third example, FJ can line up the cows as follows to achieve 22 sleeping cows: Cow 11 and 22 are lined up on the left side. Cow 11 and 22 are lined up on the right side. Cow 11 is lined up on the left side and cow 22 is lined up on the right side. Cow 11 is lined up on the right side and cow 22 is lined up on the left side. In the fourth example, FJ cannot end up with any sleeping cows, so there will be no cows lined up on either side.
[ "binary search", "combinatorics", "dp", "greedy", "implementation", "math" ]
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.Reader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.StringTokenizer; public class E { public static void main(String[] args) { var scanner = new BufferedScanner(); var writer = new PrintWriter(new BufferedOutputStream(System.out)); var n = scanner.nextInt(); var m = scanner.nextInt(); var s = new int[n + 1]; for (int i = 1; i <= n; i++) { s[i] = scanner.nextInt(); } var f = new int[m + 1]; var h = new int[m + 1]; for (int i = 1; i <= m; i++) { f[i] = scanner.nextInt(); h[i] = scanner.nextInt(); } var ans = solve(n, m, s, f, h); writer.println(ans[0] + " " + ans[1]); scanner.close(); writer.flush(); writer.close(); } static final int MODULO = (int) (1e9 + 7); private static int[] solve(int n, int m, int[] s, int[] f, int[] h) { var sleepLeft = new int[m + 1]; var sleepRight = new int[m + 1]; var byFH = new HashMap<Integer, Integer>() { public Integer get(int f, int h) { return get(hash(f, h)); } void put(int f, int h, int i) { put(hash(f, h), i); } private int hash(int f, int h) { return f * (n + 1) + h; } }; for (int i = 1; i <= m; i++) { byFH.put(f[i], h[i], i); } { var countS = new int[n + 1]; for (int i = 1; i <= n; i++) { countS[s[i]]++; var cow = byFH.get(s[i], countS[s[i]]); if (cow != null) { sleepLeft[cow] = i; } } Arrays.fill(countS, 0); for (int i = n; i >= 1; i--) { countS[s[i]]++; var cow = byFH.get(s[i], countS[s[i]]); if (cow != null) { sleepRight[cow] = i; } } } var bySweet = new HashMap<Integer, List<Integer>>(); for (int i = 1; i <= m; i++) { bySweet.putIfAbsent(f[i], new ArrayList<>()); bySweet.get(f[i]).add(i); } var sweets = bySweet.keySet().stream().mapToInt(i -> i).toArray(); var bySweet2 = new int[n + 1][]; for (int sweet : sweets) { bySweet2[sweet] = bySweet.get(sweet).stream().mapToInt(i -> i).toArray(); } var maxCows = Integer.MIN_VALUE; var maxWays = Long.MIN_VALUE; // first==0表示左边不选;first一定要用在左边,这样避免计数重复 for (int first = 0; first <= m; first++) { var leftStart = 1; var leftEnd = sleepLeft[first]; var rightStart = leftEnd + 1; var rightEnd = n; if (first != 0 && (sleepLeft[first] < leftStart || sleepLeft[first] > leftEnd)) { continue; } var cows = 0; var ways = 1L; for (int sweet : sweets) { // for (var entry : bySweet.entrySet()) { // var sweet = entry.getKey(); var left = 0L; var right = 0L; var both = 0L; for (var i : bySweet2[sweet]) { // for (var i : entry.getValue()) { var t = 0; if (sleepLeft[i] >= leftStart && sleepLeft[i] <= leftEnd) { left++; t++; } if (i == first) { // first一定在左边 continue; } if (sleepRight[i] >= rightStart && sleepRight[i] <= rightEnd) { right++; t++; } if (t == 2) { both++; left--; right--; } } if (sweet == f[first]) { left = 1; // left被first占据了 } if (left + right + both == 0) { continue; } long thisWays; if (sweet == f[first]) { thisWays = right + both; } else { // 尝试任意放两个 thisWays = left * (right + both) + both * (right + both - 1); } if (thisWays > 0) { cows += 2; ways = (ways * thisWays) % MODULO; continue; } cows++; // 放一个的方案 thisWays = left + right + both * 2; ways = (ways * thisWays) % MODULO; } if (cows > maxCows) { maxCows = cows; maxWays = ways; } else if (cows == maxCows && cows > 0) { maxWays = (maxWays + ways) % MODULO; } } return new int[]{maxCows, (int) maxWays}; } public static class BufferedScanner { BufferedReader br; StringTokenizer st; public BufferedScanner(Reader reader) { br = new BufferedReader(reader); } public BufferedScanner() { this(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } void close() { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } static long gcd(long a, long b) { if (a < b) { return gcd(b, a); } while (b > 0) { long tmp = b; b = a % b; a = tmp; } return a; } static long inverse(long a, long m) { long[] ans = extgcd(a, m); return ans[0] == 1 ? (ans[1] + m) % m : -1; } private static long[] extgcd(long a, long m) { if (m == 0) { return new long[]{a, 1, 0}; } else { long[] ans = extgcd(m, a % m); long tmp = ans[1]; ans[1] = ans[2]; ans[2] = tmp; ans[2] -= ans[1] * (a / m); return ans; } } private static List<Integer> primes(double upperBound) { var limit = (int) Math.sqrt(upperBound); var isComposite = new boolean[limit + 1]; var primes = new ArrayList<Integer>(); for (int i = 2; i <= limit; i++) { if (isComposite[i]) { continue; } primes.add(i); int j = i + i; while (j <= limit) { isComposite[j] = true; j += i; } } return primes; } }
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 n=sc.nextInt(); double c=0.0000000; for(float i=n;i>0;i--) { c+=(1/i); } System.out.println(c); } }
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); out.debug("g", g); out.debug("tree", tree); 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.parent(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.parent(u); } int v = q.b; while (v != ancestor) { if (w[v] == 0) { w[v] = q.c; } valid |= w[v] == q.c; v = tree.parent(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 final List<TreeNode> nodes; public Tree(int root) { this.root = root; this.nodes = new ArrayList<>(n); for (var i = 0; i < n; i++) { nodes.add(null); } build(root, -1, 0); } private void build(int id, int parent, int depth) { var children = neighbors(id).stream().filter(e -> e.v != parent).collect(Collectors.toList()); children.forEach(e -> build(e.v, id, depth + 1)); var subTreeSize = children.stream().mapToInt(e -> nodes.get(e.v).subTreeSize).sum() + 1; var node = new TreeNode(id, parent, depth, subTreeSize, children.isEmpty()); nodes.set(id, node); } public TreeNode treeNode(int id) { return nodes.get(id); } public int size() { return n; } public int parent(int id) { return treeNode(id).parent; } public List<Edge<T>> children(int id) { int p = parent(id); return neighbors(id).stream().filter(e -> e.v != p).collect(Collectors.toList()); } public int depth(int id) { return treeNode(id).depth; } public int subTreeSize(int id) { return treeNode(id).subTreeSize; } @Override public String toString() { String nodesString = IntStream.range(0, n) .mapToObj(i -> " " + i + ": " + nodes.get(i)) .collect(Collectors.joining(",\n")); return "Tree {\n" + " root: " + root + ",\n" + " nodes: {\n" + nodesString + "\n" + " }\n" + "}"; } } public static class TreeNode { public final int id; public final int parent; public final int depth; public final int subTreeSize; public final boolean leaf; public TreeNode(int id, int parent, int depth, int subTreeSize, boolean leaf) { this.id = id; this.parent = parent; this.depth = depth; this.subTreeSize = subTreeSize; this.leaf = leaf; } @Override public String toString() { return "TreeNode(" + "id=" + this.id + ", " + "parent=" + this.parent + ", " + "depth=" + this.depth + ", " + "subTreeSize=" + this.subTreeSize + ", " + "leaf=" + this.leaf + ")"; } } 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; var n = tree.size(); 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.subTreeSize(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
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.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int n = Integer.parseInt(in.readLine()), num = 0, dem = n - 2; for (int i = 2; i < n; i++) for (int x : inBase(n, i)) num += x; while (true) { int gcd = gcd(num, dem); if (gcd == 1) break; num /= gcd; dem /= gcd; } out.println(num + "/" + dem); out.flush(); in.close(); out.close(); } private static List<Integer> inBase(int n, int b) { List<Integer> list = new ArrayList<>(); while (n > 0) { list.add(n % b); n /= b; } return list; } private static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } }
java
1325
C
C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusive. All the written labels are distinct. The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3 1 2 1 3 OutputCopy0 1 InputCopy6 1 2 1 3 2 4 2 5 5 6 OutputCopy0 3 2 4 1NoteThe tree from the second sample:
[ "constructive algorithms", "dfs and similar", "greedy", "trees" ]
import java.util.*; import java.lang.*; import java.io.*; public class Solution { static long[] fac; public static void main(String[] args) throws IOException { Reader.init(System.in); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); /* // Do not delete this // Uncomment this before using nCrModPFermat fac = new long[200000 + 1]; fac[0] = 1; for (int i = 1; i <= 200000; i++) fac[i] = (fac[i - 1] * i % 1000000007); */ // int te = Reader.nextInt(); int te = 1; while(te-->0) { int n = Reader.nextInt(); ArrayList<ArrayList<int[]>> g = new ArrayList<>(); for(int i = 0;i<=n;i++) g.add(new ArrayList<>()); int[] ans = new int[n]; for(int i = 0;i<n-1;i++){ int u = Reader.nextInt(); int v = Reader.nextInt(); g.get(u).add(new int[]{v,i}); g.get(v).add(new int[]{u,i}); } if(n==2){ output.write("0\n"); continue; } boolean[] visited = new boolean[n+1]; boolean started = false; Queue<Integer> q = new LinkedList<>(); q.add(1); int val = n-2; boolean[] numVisited = new boolean[n-1]; boolean zero = false, two = false; while(q.size()>0){ int curr = q.remove(); if(visited[curr]) continue; visited[curr] = true; if(started){ if(g.get(curr).size()>=3){ for(int[] edge : g.get(curr)){ if(!visited[edge[0]]){ if(!zero){ ans[edge[1]] = 0; numVisited[0] = true; zero = true; } else if(!two){ ans[edge[1]] = 2; numVisited[2] = true; two = true; } else{ while(numVisited[val]) val--; ans[edge[1]] = val; numVisited[val] = true; val--; } q.add(edge[0]); } } } else{ for(int[] edge : g.get(curr)){ if(!visited[edge[0]]){ while(numVisited[val]) val--; ans[edge[1]] = val; numVisited[val] = true; val--; q.add(edge[0]); } } } } else{ numVisited[1] = true; ans[g.get(curr).get(0)[1]] = 1; q.add(g.get(curr).get(0)[0]); if(g.get(curr).size()>=3){ for(int[] edge : g.get(curr)){ if(!started){ started = true; continue; } if(!visited[edge[0]]){ if(!zero){ ans[edge[1]] = 0; numVisited[0] = true; zero = true; } else if(!two){ ans[edge[1]] = 2; numVisited[2] = true; two = true; } else{ while(numVisited[val]) val--; ans[edge[1]] = val; numVisited[val] = true; val--; } q.add(edge[0]); } } } else{ for(int[] edge : g.get(curr)){ if(!visited[edge[0]]){ if(!started){ started = true; continue; } while(numVisited[val]) val--; ans[edge[1]] = val; numVisited[val] = true; val--; q.add(edge[0]); } } } } } for(int i = 0;i<n-1;i++){ output.write(ans[i]+"\n"); } } output.close(); } public static boolean isP(int n){ StringBuilder s1 = new StringBuilder(n+""); StringBuilder s2 = new StringBuilder(n+""); s2.reverse(); for(int i = 0;i<s1.length();i++){ if(s1.charAt(i)!=s2.charAt(i)) return false; } return true; } public static long[] factorial(int n){ long[] factorials = new long[n+1]; factorials[0] = 1; factorials[1] = 1; for(int i = 2;i<=n;i++){ factorials[i] = (factorials[i-1]*i); } return factorials; } public static long numOfBits(long n){ long ans = 0; while(n>0){ n = n & (n-1); ans++; } return ans; } public static long ceilOfFraction(long x, long y){ // ceil using integer division: ceil(x/y) = (x+y-1)/y // using double may go out of range. return (x+y-1)/y; } public static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } // Returns n^(-1) mod p public static long modInverse(long n, long p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. public static long nCrModPFermat(int n, int r, int p) { if (n<r) return 0; if (r == 0) return 1; // Fill factorial array so that we // can find all factorial of r, n // and n-r return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; } public static long ncr(long n, long r) { long p = 1, k = 1; if (n - r < r) { r = n - r; } if (r != 0) { while (r > 0) { p *= n; k *= r; long m = gcd(p, k); p /= m; k /= m; n--; r--; } } else { p = 1; } return p; } public static boolean isPrime(long n){ if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; (long) i * i <= n; i = i + 6){ if (n % i == 0 || n % (i + 2) == 0) { return false; } } return true; } public static int powOf2JustSmallerThanN(int n) { n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; return n ^ (n >> 1); } public static long merge(int[] arr, int[] aux, int low, int mid, int high) { int k = low, i = low, j = mid + 1; long inversionCount = 0; // while there are elements in the left and right runs while (i <= mid && j <= high) { if (arr[i] <= arr[j]) { aux[k++] = arr[i++]; } else { aux[k++] = arr[j++]; inversionCount += (mid - i + 1); // NOTE } } // copy remaining elements while (i <= mid) { aux[k++] = arr[i++]; } /* no need to copy the second half (since the remaining items are already in their correct position in the temporary array) */ // copy back to the original array to reflect sorted order for (i = low; i <= high; i++) { arr[i] = aux[i]; } return inversionCount; } // Sort array `arr[low…high]` using auxiliary array `aux` public static long mergesort(int[] arr, int[] aux, int low, int high) { if (high <= low) { // if run size <= 1 return 0; } int mid = (low + ((high - low) >> 1)); long inversionCount = 0; // recursively split runs into two halves until run size <= 1, // then merges them and return up the call chain // split/merge left half inversionCount += mergesort(arr, aux, low, mid); // split/merge right half inversionCount += mergesort(arr, aux, mid + 1, high); // merge the two half runs inversionCount += merge(arr, aux, low, mid, high); return inversionCount; } public static void reverseArray(int[] arr,int start, int end) { int temp; while (start < end) { temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } } public static long gcd(long a, long b){ if(a==0){ return b; } return gcd(b%a,a); } public static long lcm(long a, long b){ if(a>b) return a/gcd(b,a) * b; return b/gcd(a,b) * a; } public static long largeExponentMod(long x,long y,long mod){ // computing (x^y) % mod x%=mod; long ans = 1; while(y>0){ if((y&1)==1){ ans = (ans*x)%mod; } x = (x*x)%mod; y = y >> 1; } return ans; } public static boolean[] numOfPrimesInRange(long L, long R){ boolean[] isPrime = new boolean[(int) (R-L+1)]; Arrays.fill(isPrime,true); long lim = (long) Math.sqrt(R); for (long i = 2; i <= lim; i++){ for (long j = Math.max(i * i, (L + i - 1) / i * i); j <= R; j += i){ isPrime[(int) (j - L)] = false; } } if (L == 1) isPrime[0] = false; return isPrime; } public static ArrayList<Long> primeFactors(long n){ ArrayList<Long> factorization = new ArrayList<>(); if(n%2==0){ factorization.add(2L); } while(n%2==0){ n/=2; } if(n%3==0){ factorization.add(3L); } while(n%3==0){ n/=3; } if(n%5==0){ factorization.add(5L); } while(n%5==0){ // factorization.add(5L); n/=5; } int[] increments = {4, 2, 4, 2, 4, 6, 2, 6}; int i = 0; for (long d = 7; d * d <= n; d += increments[i++]) { if(n%d==0){ factorization.add(d); } while (n % d == 0) { // factorization.add(d); n /= d; } if (i == 8) i = 0; } if (n > 1) factorization.add(n); return factorization; } } class DSU { int[] size, parent; int n; public DSU(int n){ this.n = n; size = new int[n]; parent = new int[n]; for(int i = 0;i<n;i++){ parent[i] = i; size[i] = 1; } } public int find(int u){ if(parent[u]==u){ return u; } return parent[u] = find(parent[u]); } public void merge(int u, int v){ u = find(u); v = find(v); if(u!=v){ if(size[u]>size[v]){ parent[v] = u; size[u] += size[v]; } else{ parent[u] = v; size[v] += size[u]; } } } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static String nextLine() throws IOException { return reader.readLine(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static long nextLong() throws IOException{ return Long.parseLong(next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } } class SegTree{ int n; // array size // Max size of tree public int[] tree; public SegTree(int n){ this.n = n; tree = new int[4*n]; } // function to build the tree void update(int pos, int val, int s, int e, int treeIdx){ if(pos < s || pos > e){ return; } if(s == e){ tree[treeIdx] = val; return; } int mid = s + (e - s) / 2; update(pos, val, s, mid, 2 * treeIdx); update(pos, val, mid + 1, e, 2 * treeIdx + 1); tree[treeIdx] = tree[2 * treeIdx] + tree[2 * treeIdx + 1]; } void update(int pos, int val){ update(pos, val, 1, n, 1); } int query(int qs, int qe, int s, int e, int treeIdx){ if(qs <= s && qe >= e){ return tree[treeIdx]; } if(qs > e || qe < s){ return 0; } int mid = s + (e - s) / 2; int subQuery1 = query(qs, qe, s, mid, 2 * treeIdx); int subQuery2 = query(qs, qe, mid + 1, e, 2 * treeIdx + 1); int res = subQuery1 + subQuery2; return res; } int query(int l, int r){ return query(l, r, 1, n, 1); } }
java
1312
C
C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can: either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one 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 kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5 4 100 0 0 0 0 1 2 1 3 4 1 4 1 3 2 0 1 3 3 9 0 59049 810 OutputCopyYES YES NO NO YES NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2.
[ "bitmasks", "greedy", "implementation", "math", "number theory", "ternary search" ]
import java.io.*; import java.util.ArrayList; public class CER83C { public static void solve() throws IOException { int n = sc.nextInt(); int k = sc.nextInt(); long arr[] = new long[n]; for(int i=0;i<n;i++){ arr[i] = sc.nextLong(); } ArrayList<Long>ls = new ArrayList<>(); boolean flag = true; for(long x:arr){ long num =0; long p = x; while(p>0){ long rem = p%k; if(rem>1){ flag= false; break ; }else if(rem==1){ if(!ls.contains(num)){ ls.add(num); }else{ flag = false; break; } } p=p/k; num++; } } if(!flag){ System.out.println("NO"); }else{ System.out.println("YES"); } } //============================================================================= //--------------------------The End--------------------------------- //============================================================================= private static long INF = 2000000000000000000L, M = 1000000007, MM = 998244353; private static int N = 0; private static void google(int tt) { System.out.print("Case #" + (tt) + ": "); } static FastScanner sc; static FastWriter out; public static void main(String[] args) throws IOException { boolean oj = true; if (oj) { sc = new FastScanner(); out = new FastWriter(System.out); } else { sc = new FastScanner("input.txt"); out = new FastWriter("output.txt"); } long s = System.currentTimeMillis(); int t = 1; t = sc.nextInt(); int TTT = 1; outer: while (t-- > 0) { // google(TTT++); solve(); } out.flush(); // tr(System.currentTimeMillis()-s+"ms"); } static class FastScanner { //I don't understand how this works lmao 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[] readArray(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] readArrayLong(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public int[][] readArrayMatrix(int N, int M, int Index) { if (Index == 0) { int[][] res = new int[N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) res[i][j] = (int) nextLong(); } return res; } int[][] res = new int[N][M]; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) res[i][j] = (int) nextLong(); } return res; } public long[][] readArrayMatrixLong(int N, int M, int Index) { if (Index == 0) { long[][] res = new long[N][M]; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) res[i][j] = nextLong(); } return res; } long[][] res = new long[N][M]; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) res[i][j] = 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[] readArrayDouble(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; } } } 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(); } } }
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" ]
import java.util.*; import java.io.*; import java.math.*; public class Main{ public static void main(String[]args){ long s = System.currentTimeMillis(); new Solver().run(); System.err.println(System.currentTimeMillis()-s+"ms"); } } class Solver{ final long mod = (long)1e9+7l; final boolean DEBUG = true, MULTIPLE_TC = false; FastReader sc; PrintWriter out; int N, pow2[]; ArrayList<Integer> arr; void init(){ N = ni(); arr = new ArrayList<>(); pow2 = new int[32]; pow2[0] = 1; for(int i = 1; i <= 31; i++){ pow2[i] = 2 * pow2[i - 1]; } for(int i = 1; i <= N; i++){ arr.add(ni()); } } ArrayList<Integer> pickNumbersWithThisBitOn(int bitPos, ArrayList<Integer> li){ ArrayList<Integer> ret= new ArrayList<>(); for(int x : li){ if((pow2[bitPos] & x) != 0){ ret.add(x); } } return ret; } ArrayList<Integer> pickNumbersWithThisBitOff(int bitPos, ArrayList<Integer> li){ ArrayList<Integer> ret = new ArrayList<>(); for(int x : li){ if((pow2[bitPos] & x) == 0){ ret.add(x); } } return ret; } boolean allBitsAtThisPosAreSame(int bitPos, ArrayList<Integer> li){ int cntOff = 0, cntOn = 0; for(int x : li){ if((x & pow2[bitPos]) != 0){ cntOn += 1; }else{ cntOff += 1; } } return cntOff == li.size() || cntOn == li.size(); } int f(int bit, boolean on, ArrayList<Integer> li){ if(bit < 0){ return 0; } ArrayList<Integer> consider = on ? pickNumbersWithThisBitOn(bit + 1, li) : pickNumbersWithThisBitOff(bit + 1, li); int res = 0; if(allBitsAtThisPosAreSame(bit, consider)){ res = f(bit - 1, (consider.get(0) & pow2[bit]) != 0, consider); }else{ res = pow2[bit] + Math.min(f(bit - 1, false, consider), f(bit - 1, true, consider)); } return res; } void process(int testNumber){ init(); int res = f(30, false, arr); pn(res); } void run(){ sc = new FastReader(); out = new PrintWriter(System.out); int t = MULTIPLE_TC ? ni() : 1; for(int test = 1; test <= t; test++){ process(test); } out.flush(); } void trace(Object... o){ if(!DEBUG) return; System.err.println(Arrays.deepToString(o)); }; void pn(Object o){ out.println(o); } void p(Object o){ out.print(o); } int ni(){ return Integer.parseInt(sc.next()); } long nl(){ return Long.parseLong(sc.next()); } double nd(){ return Double.parseDouble(sc.next()); } String nln(){ return sc.nextLine(); } long gcd(long a, long b){ return (b==0)?a:gcd(b,a%b);} int gcd(int a, int b){ return (b==0)?a:gcd(b,a%b); } 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(); } String nextLine(){ String str = ""; try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } } class pair implements Comparable<pair> { int first, second; public pair(int first, int second){ this.first = first; this.second = second; } @Override public int compareTo(pair ob){ if(this.first != ob.first) return this.first - ob.first; return this.second - ob.second; } @Override public String toString(){ return this.first + " " + this.second; } static public pair from(int f, int s){ return new pair(f, s); } }
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.util.*; import java.io.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; @SuppressWarnings("unchecked") public class Main { public static PrintWriter pw = new PrintWriter(System.out); static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static int[][] dirs = {{0,1},{1,0},{0,-1},{-1,0}}; public static class Tree { Node root; } public static class Node { int v; ArrayList<Node> children; Node(int v, ArrayList<Node> children) { this.v = v; this.children = children; } } public static void dfs(int v , Set<Integer> ss) { ss.add(v); ans++; for(int x : graph[v]) { if(!ss.contains(x)) { dfs(x,ss); } } ss.remove(v); } public static void sieveOfEratosthenes(int n) { // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. boolean prime[] = new boolean[n+1]; for(int i=0;i<=n;i++) prime[i] = true; for(int p = 2; p*p <=n; p++) { // If prime[p] is not changed, then it is a prime if(prime[p] == true) { // Update all multiples of p for(int i = p*p; i <= n; i += p) prime[i] = false; } } // Print all prime numbers for(int i = 2; i <= n; i++) { if(prime[i] == true) System.out.print(i + " "); } } // dsu public static int find(int x) { if (parent[x] != x) { parent[x] = find(parent[x]); } return parent[x]; } public static void union(int x, int y) { // Find representatives of two sets int xRoot = find(x), yRoot = find(y); // Elements are in the same set, no need // to unite anything. if (xRoot == yRoot) return; // If x's rank is less than y's rank if (rank[xRoot] < rank[yRoot]) {// Then move x under y so that depth // of tree remains less parent[xRoot] = yRoot; rank[yRoot] +=rank[xRoot]; rank[xRoot]=1; } // Else if y's rank is less than x's rank else if (rank[yRoot] < rank[xRoot]) { // Then move y under x so that depth of // tree remains less parent[yRoot] = xRoot; rank[xRoot] +=rank[yRoot]; rank[yRoot]=1; } else // if ranks are the same { // Then move y under x (doesn't matter // which one goes where) parent[yRoot] = xRoot; // And increment the result tree's // rank by 1 rank[xRoot] = rank[xRoot] + rank[yRoot]; rank[yRoot]=1; } } public static void makegraph(int n , int m) { for(int a=0;a<n;a++) { graph[a] = new ArrayList<>(); } for(int a=0;a<m;a++) { int v1 = scn.nextInt()-1; int v2 = scn.nextInt()-1; graph[v1].add(v2); graph[v2].add(v1); } } public static int[] arrInt() { int n = scn.nextInt(); int [] arr = new int[n]; for(int a=0;a<n;a++) {arr[a] = scn.nextInt();} return arr; } public static long[] arrLong() { int n = scn.nextInt(); long [] arr = new long[n]; for(int a=0;a<n;a++) {arr[a] = scn.nextLong();} return arr; } public static void display(int [] arr) { for(int i : arr) {pw.print(i+" ");} pw.println(); } public static void display(long [] arr) { for(long i : arr) {pw.print(i+" ");} pw.println(); } // ==================== MATHEMATICAL FUNCTIONS =========================== private static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } private static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } private static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } private static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } private static int mod_pow(long a, long b, long mod) { if (b == 0) return 1; int temp = mod_pow(a, b >> 1, mod); temp %= mod; temp = (int) ((1L * temp * temp) % mod); if ((b & 1) == 1) temp = (int) ((1L * temp * a) % mod); return temp; } private static long multiply(long a, long b,long mod) { return (((a % mod) * (b % mod)) % mod); } private static long divide(long a, long b,long mod) { return multiply(a, mod_pow(b, mod - 2, mod),mod); } private static boolean isPrime(long n) { for (long i = 2; i * i <= n; i++) if (n % i == 0) return false; return true; } public static long fact(long n) { return (n == 1 || n == 0) ? 1 : n * fact(n - 1); } public static long ncr(long n, long k) { long res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1] for (long i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } private static List<Integer> factors(int n) { List<Integer> list = new ArrayList<>(); for (int i = 1; 1L * i * i <= n; i++) if (n % i == 0) { list.add(i); if (i != n / i) list.add(n / i); } return list; } private static List<Long> factors(long n) { List<Long> list = new ArrayList<>(); for (long i = 1; i * i <= n; i++) if (n % i == 0) { list.add(i); if (i != n / i) list.add(n / i); } return list; } //public static ArrayList<ArrayList<Integer>> fans = new ArrayList<>(); public static int [] parent = null; public static int [] rank = null; public static ArrayList<Integer>[] graph = null; public static int ans = 0; public static FastReader scn = new FastReader(); public static long c = 1000000007; public static long mod = 1000000007; public static void main(String[] args) { int t = 1; z:for(int w=1;w<=t;w++) { long n = scn.nextLong(); long ans=0; for(long a=1;a*a<=n;a++) { if(n%a==0 && lcm(a,n/a)==n) { ans = a; } } pw.println(ans+" "+n/ans); } pw.close(); } }
java
1291
A
A. Even But Not Eventime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's define a number ebne (even but not even) if and only if its sum of digits is divisible by 22 but the number itself is not divisible by 22. For example, 1313, 12271227, 185217185217 are ebne numbers, while 1212, 22, 177013177013, 265918265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clarification.You are given a non-negative integer ss, consisting of nn digits. You can delete some digits (they are not necessary consecutive/successive) to make the given number ebne. You cannot change the order of the digits, that is, after deleting the digits the remaining digits collapse. The resulting number shouldn't contain leading zeros. You can delete any number of digits between 00 (do not delete any digits at all) and n−1n−1.For example, if you are given s=s=222373204424185217171912 then one of possible ways to make it ebne is: 222373204424185217171912 →→ 2237344218521717191. The sum of digits of 2237344218521717191 is equal to 7070 and is divisible by 22, but number itself is not divisible by 22: it means that the resulting number is ebne.Find any resulting number that is ebne. If it's impossible to create an ebne number from the given number report about it.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — 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≤30001≤n≤3000)  — the number of digits in the original number.The second line of each test case contains a non-negative integer number ss, consisting of nn digits.It is guaranteed that ss does not contain leading zeros and the sum of nn over all test cases does not exceed 30003000.OutputFor each test case given in the input print the answer in the following format: If it is impossible to create an ebne number, print "-1" (without quotes); Otherwise, print the resulting number after deleting some, possibly zero, but not all digits. This number should be ebne. If there are multiple answers, you can print any of them. Note that answers with leading zeros or empty strings are not accepted. It's not necessary to minimize or maximize the number of deleted digits.ExampleInputCopy4 4 1227 1 0 6 177013 24 222373204424185217171912 OutputCopy1227 -1 17703 2237344218521717191 NoteIn the first test case of the example; 12271227 is already an ebne number (as 1+2+2+7=121+2+2+7=12, 1212 is divisible by 22, while in the same time, 12271227 is not divisible by 22) so we don't need to delete any digits. Answers such as 127127 and 1717 will also be accepted.In the second test case of the example, it is clearly impossible to create an ebne number from the given number.In the third test case of the example, there are many ebne numbers we can obtain by deleting, for example, 11 digit such as 1770317703, 7701377013 or 1701317013. Answers such as 17011701 or 770770 will not be accepted as they are not ebne numbers. Answer 013013 will not be accepted as it contains leading zeroes.Explanation: 1+7+7+0+3=181+7+7+0+3=18. As 1818 is divisible by 22 while 1770317703 is not divisible by 22, we can see that 1770317703 is an ebne number. Same with 7701377013 and 1701317013; 1+7+0+1=91+7+0+1=9. Because 99 is not divisible by 22, 17011701 is not an ebne number; 7+7+0=147+7+0=14. This time, 1414 is divisible by 22 but 770770 is also divisible by 22, therefore, 770770 is not an ebne number.In the last test case of the example, one of many other possible answers is given. Another possible answer is: 222373204424185217171912 →→ 22237320442418521717191 (delete the last digit).
[ "greedy", "math", "strings" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class A { public static void main(String[] args) { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t = fs.nextInt(); while (t-- > 0) { int n=fs.nextInt(); char ch[]=fs.next().toCharArray(); out.println(check(ch)); } out.close(); } public static String check(char ch[]){ int n=ch.length; int ps[]=new int[n]; ps[0]=ch[0]-'0'; for(int i=1;i<n;i++){ ps[i]=(ch[i]-'0')+ps[i-1]; } int i=0; for(i=n-1;i>=0;i--){ if(ps[i]%2==0 && (ch[i]-'0')%2!=0) break; } if(i>=0){ String res=""; for(int j=0;j<=i;j++){ res+=ch[j]; } return res; } return "-1"; } /* HELPER FUNCTION's */ static final Random random = new Random(); static final int mod = 1_000_000_007; static void ruffleSort(int[] a) { int n = a.length;//shuffle, then sort for (int i = 0; i < n; i++) { int oi = random.nextInt(n), temp = a[oi]; a[oi] = a[i]; a[i] = temp; } Arrays.sort(a); } static long add(long a, long b) { return (a + b) % mod; } static long sub(long a, long b) { return ((a - b) % mod + mod) % mod; } static long mul(long a, long b) { return (a * b) % mod; } /* fast exponentiation */ static long exp(long base, long exp) { if (exp == 0) return 1; long half = exp(base, exp / 2); if (exp % 2 == 0) return mul(half, half); return mul(half, mul(half, base)); } /* end of fast exponentiation */ static long[] factorials = new long[2_000_001]; static long[] invFactorials = new long[2_000_001]; static void precompFacts() { factorials[0] = invFactorials[0] = 1; for (int i = 1; i < factorials.length; i++) factorials[i] = mul(factorials[i - 1], i); invFactorials[factorials.length - 1] = exp(factorials[factorials.length - 1], mod - 2); for (int i = invFactorials.length - 2; i >= 0; i--) invFactorials[i] = mul(invFactorials[i + 1], i + 1); } static long nCk(int n, int k) { return mul(factorials[n], mul(invFactorials[k], invFactorials[n - k])); } /* sort ascending and descending both */ static void sort(int[] a,int x) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); if(x==0) { Collections.sort(l); } if(x==1){ Collections.sort(l,Collections.reverseOrder()); } for (int i = 0; i < a.length; i++) a[i] = l.get(i); } /* sort String acc. to character */ static String sortString(String s){ char ch[]=s.toCharArray(); Arrays.sort(ch); String s1=String.valueOf(ch); return s1; } // lcm(a,b) * gcd(a,b) = a * b public static long _lcm(long a, long b) { return (a / _gcd(a, b)) * b; } // euclidean algorithm time O(max (loga ,logb)) public static long _gcd(long a, long b) { while (a > 0) { long x = a; a = b % a; b = x; } return b; } /* Pair Class implementation */ static class Pair<K, V> { K ff; V ss; public Pair(K ff, V ss) { this.ff = ff; this.ss = ss; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || this.getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; return ff.equals(pair.ff) && ss.equals(pair.ss); } @Override public int hashCode() { return Objects.hash(ff, ss); } @Override public String toString() { return ff.toString() + " " + ss.toString(); } } /* pair class ends here */ /* fast input output class */ 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[] readArrayL(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } }
java
1312
B
B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3 1 7 4 1 1 3 5 6 3 2 1 5 6 4 OutputCopy7 1 5 1 3 2 4 6 1 3 5
[ "constructive algorithms", "sortings" ]
import java.util.*; import java.io.*; public class A { static class Pair { int x; int y; public Pair(int x, int 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 void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); StringBuilder str = new StringBuilder(); int t = sc.nextInt(); for (int xx = 1; xx <= t; xx++) { int n = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); Arrays.sort(arr); for(int i=n-1;i>=0;i--) str.append(arr[i]+" "); str.append("\n"); } System.out.println(str); sc.close(); } }
java
1141
B
B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5 1 0 1 0 1 OutputCopy2 InputCopy6 0 1 0 1 1 0 OutputCopy2 InputCopy7 1 0 1 1 1 0 1 OutputCopy3 InputCopy3 0 0 0 OutputCopy0 NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all.
[ "implementation" ]
import java.io.*; import java.util.*; public class maxrest { public static void main(String[] args)throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int count = Integer.parseInt(br.readLine()); int[]nums=new int[count*2]; StringTokenizer st = new StringTokenizer(br.readLine()); for(int i=0;i<count;i++) { nums[i]=Integer.parseInt(st.nextToken()); nums[i+count]=nums[i]; } int c=0; int g=0; for(int i=0;i<nums.length;i++) { if(nums[i]==1) { c++; if(c>g) { g=c; } } if(nums[i]==0) { c=0; } } System.out.println(g); } }
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 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; /* * * 123456789 *(()(())) * * */ 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 = 1; while (t-- > 0) { int n = fastReader.nextInt(); char c[] = fastReader.nextLine().toCharArray(); int cur = 0; int ans = 0; boolean valid = true; for (int i = 0; i < n; i++) { // out.println("i: " + i); if (c[i] == '(') { cur++; } else { cur--; } if (cur < 0) { int abs = cur; int index = i + 1; while (index < n && abs != 0) { if (c[index] == '(') { abs++; } else { abs--; } index++; } if (abs != 0) { valid = false; } // out.println(abs); // out.println(index); ans += (index - i); cur = 0; i = index - 1; } } if (!valid || cur != 0) { out.println(-1); } else { out.println(ans); } } 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
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.io.*; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.*; public class ProblemA { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder sb = new StringBuilder(); int test = Integer.parseInt(br.readLine()); while(test-->0){ int n = Integer.parseInt(br.readLine()); String line[] = br.readLine().split(" "); HashSet<Integer>set = new HashSet<>(); for(int i = 0;i<n;i++)set.add(Integer.parseInt(line[i])%2); sb.append(set.size()==1?"YES":"NO"); sb.append("\n"); } System.out.println(sb); } public static int search(int target,int arr[]){ int l = 0; int r = arr.length-1; int index = -1; while(l<=r){ int mid = (l+r)/2; if(arr[mid]<=target){ index = mid; 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); for(int i = 0;i<list.size();i++)arr[i] = list.get(i); } } class Pair{ int x,y; public Pair(int x,int y){ this.x = x; this.y = y; } }
java
1303
D
D. Fill The Bagtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou have a bag of size nn. Also you have mm boxes. The size of ii-th box is aiai, where each aiai is an integer non-negative power of two.You can divide boxes into two parts of equal size. Your goal is to fill the bag completely.For example, if n=10n=10 and a=[1,1,32]a=[1,1,32] then you have to divide the box of size 3232 into two parts of size 1616, and then divide the box of size 1616. So you can fill the bag with boxes of size 11, 11 and 88.Calculate the minimum number of divisions required to fill the bag of size nn.InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases.The first line of each test case contains two integers nn and mm (1≤n≤1018,1≤m≤1051≤n≤1018,1≤m≤105) — the size of bag and the number of boxes, respectively.The second line of each test case contains mm integers a1,a2,…,ama1,a2,…,am (1≤ai≤1091≤ai≤109) — the sizes of boxes. It is guaranteed that each aiai is a power of two.It is also guaranteed that sum of all mm over all test cases does not exceed 105105.OutputFor each test case print one integer — the minimum number of divisions required to fill the bag of size nn (or −1−1, if it is impossible).ExampleInputCopy3 10 3 1 32 1 23 4 16 1 4 1 20 5 2 1 16 1 8 OutputCopy2 -1 0
[ "bitmasks", "greedy" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import java.util.Random; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; // CFPS -> CodeForcesProblemSet public final class CFPS { static FastReader fr = new FastReader(); static PrintWriter out = new PrintWriter(System.out); static final int gigamod = 1000000007; static final int mod = 998244353; static int t = 1; static double epsilon = 0.00000001; static boolean[] isPrime; static int[] smallestFactorOf; @SuppressWarnings("unused") public static void main(String[] args) { t = fr.nextInt(); OUTER: for (int tc = 0; tc < t; tc++) { long n = fr.nextLong(); int m = fr.nextInt(); long[] arr = fr.nextLongArray(m); // Observations: // 1. The task is to determine the minimum number of splits required // to fill up the bag completely. // 2. Possibility 1: DP problem // Possibility 2: Greedy + Bitmask problem // 3. We can combine boxes for free. // 4. If some bit is ON in 'n', and is also present among the boxes, // it is optimal to use it up then and there. CountMap<Long> powers = new CountMap<>(); for (long l : arr) powers.putCM(l); for (int lvl = 0; lvl < 60; lvl++) { long shiftt = (1L << lvl); if ((n & shiftt) > 0 && powers.containsKey(shiftt)) { n ^= shiftt; powers.removeCM(shiftt); } } // 5. Starting from the smallest SET bit, we will try to determine, if // some smaller bits can constitute to form it. What else will the // smaller bits be used for anyway? // -- // If however, smaller bits don't fare, we will break the smallest value // larger than the current bit level and continue for larger ON bits. long numDivs = 0; for (int lvl = 0; lvl < 60; lvl++) { long shiftt = (1L << lvl); if ((n & shiftt) > 0) { // here, we have to find a combination of smaller available bits // to (possibly) make up this bit // if this bit cannot be made from smaller bits, we will break the // smallest bit larger than it and use it CountMap<Long> used = new CountMap<>(); long reqd = shiftt; for (long chk = reqd; chk > 0; chk /= 2) { // we will take up 'chk' until reqd remains non-negative int available = powers.getCM(chk); int take = (int) Math.min(available, reqd / chk); reqd -= take * chk; used.put(chk, take); } if (reqd == 0) { // some bits can be combined to form 'lvl' bit n ^= shiftt; while (!used.isEmpty()) { Entry<Long, Integer> e = used.pollFirstEntry(); int power = e.getValue(); int alreadyPower = powers.getCM(e.getKey()); powers.put(e.getKey(), alreadyPower - power); } } else { // we need to break some bit down reqd = shiftt; long got = -1; int numSteps = -1; for (long chk = reqd; chk < 1e9 + 1e9; chk *= 2) { if (powers.containsKey(chk)) { numSteps = logk((int) (chk / reqd), 2); got = chk; break; } } if (got == -1) { out.println(-1); continue OUTER; } // 'got' will be broken down to get reqd powers.removeCM(got); n ^= shiftt; // we also need to add to powers, the descendants of // got for (long desc = got / 2; desc >= reqd; desc /= 2) { powers.putCM(desc); numDivs++; } } } } if (n == 0) out.println(numDivs); else out.println(-1); } out.close(); } static class Tuple { int type, val, to; Tuple(int ll, int rr, int zz) { type = ll; val = rr; to = zz; } } static int treeDiameter(UGraph ug) { int n = ug.V(); int farthest = -1; int[] distTo = new int[n]; diamDFS(0, -1, 0, ug, distTo); int maxDist = -1; for (int i = 0; i < n; i++) if (maxDist < distTo[i]) { maxDist = distTo[i]; farthest = i; } distTo = new int[n]; diamDFS(farthest, -1, 0, ug, distTo); return Arrays.stream(distTo).max().getAsInt(); } static void diamDFS(int current, int from, int dist, UGraph ug, int[] distTo) { distTo[current] = dist; for (int adj : ug.adj(current)) if (adj != from) diamDFS(adj, current, dist + 1, ug, distTo); } static class LCA { int[] height, first, segtree; ArrayList<Integer> euler; boolean[] visited; int n; LCA(UGraph ug, int root) { n = ug.V(); height = new int[n]; first = new int[n]; euler = new ArrayList<>(); visited = new boolean[n]; dfs(ug, root, 0); int m = euler.size(); segtree = new int[m * 4]; build(1, 0, m - 1); } void dfs(UGraph ug, int node, int h) { visited[node] = true; height[node] = h; first[node] = euler.size(); euler.add(node); for (int adj : ug.adj(node)) { if (!visited[adj]) { dfs(ug, adj, h + 1); euler.add(node); } } } void build(int node, int b, int e) { if (b == e) { segtree[node] = euler.get(b); } else { int mid = (b + e) / 2; build(node << 1, b, mid); build(node << 1 | 1, mid + 1, e); int l = segtree[node << 1], r = segtree[node << 1 | 1]; segtree[node] = (height[l] < height[r]) ? l : r; } } int query(int node, int b, int e, int L, int R) { if (b > R || e < L) return -1; if (b >= L && e <= R) return segtree[node]; int mid = (b + e) >> 1; int left = query(node << 1, b, mid, L, R); int right = query(node << 1 | 1, mid + 1, e, L, R); if (left == -1) return right; if (right == -1) return left; return height[left] < height[right] ? left : right; } int lca(int u, int v) { int left = first[u], right = first[v]; if (left > right) { int temp = left; left = right; right = temp; } return query(1, 0, euler.size() - 1, left, right); } } static class FenwickTree { long[] array; // 1-indexed array, In this array We save cumulative information to perform efficient range queries and updates public FenwickTree(int size) { array = new long[size + 1]; } public long rsq(int ind) { assert ind > 0; long sum = 0; while (ind > 0) { sum += array[ind]; //Extracting the portion up to the first significant one of the binary representation of 'ind' and decrementing ind by that number ind -= ind & (-ind); } return sum; } public long rsq(int a, int b) { assert b >= a && a > 0 && b > 0; return rsq(b) - rsq(a - 1); } public void update(int ind, long value) { assert ind > 0; while (ind < array.length) { array[ind] += value; //Extracting the portion up to the first significant one of the binary representation of 'ind' and incrementing ind by that number ind += ind & (-ind); } } public int size() { return array.length - 1; } } static boolean[] prefMatchesSuff(char[] s) { int n = s.length; boolean[] res = new boolean[n + 1]; int[] pi = prefixFunction(s); res[0] = true; for (int p = n; p != 0; p = pi[p]) res[p] = true; return res; } static int[] prefixFunction(char[] s) { int k = s.length; int[] pfunc = new int[k + 1]; pfunc[0] = pfunc[1] = 0; for (int i = 2; i <= k; i++) { pfunc[i] = 0; for (int p = pfunc[i - 1]; p != 0; p = pfunc[p]) if (s[p] == s[i - 1]) { pfunc[i] = p + 1; break; } if (pfunc[i] == 0 && s[i - 1] == s[0]) pfunc[i] = 1; } return pfunc; } static class Edge implements Comparable<Edge> { int from, to; long weight; int id; // int hash; Edge(int fro, int t, long weigh, int i) { from = fro; to = t; weight = weigh; id = i; // hash = Objects.hash(from, to, weight); } /*public int hashCode() { return hash; }*/ public int compareTo(Edge that) { return Long.compare(this.id, that.id); } } public static long[][] sparseTable(long[] a) { int n = a.length; int b = 32-Integer.numberOfLeadingZeros(n); long[][] ret = new long[b][]; for(int i = 0, l = 1;i < b;i++, l*=2) { if(i == 0) { ret[i] = a; }else { ret[i] = new long[n-l+1]; for(int j = 0;j < n-l+1;j++) { ret[i][j] = Math.min(ret[i-1][j], ret[i-1][j+l/2]); } } } return ret; } public static long sparseRMQ(long[][] table, int l, int r) { // [a,b) assert l <= r; if(l >= r)return Integer.MAX_VALUE; // 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3 int t = 31-Integer.numberOfLeadingZeros(r-l); return Math.min(table[t][l], table[t][r-(1<<t)]); } static class Point implements Comparable<Point> { long x; long y; long z; long id; // private int hashCode; Point() { x = z = y = 0; // this.hashCode = Objects.hash(x, y, cost); } Point(Point p) { this.x = p.x; this.y = p.y; this.z = p.z; this.id = p.id; // this.hashCode = Objects.hash(x, y, cost); } Point(long x, long y, long z, long id) { this.x = x; this.y = y; this.z = z; this.id = id; // this.hashCode = Objects.hash(x, y, id); } Point(long a, long b) { this.x = a; this.y = b; this.z = 0; // this.hashCode = Objects.hash(a, b); } Point(long x, long y, long id) { this.x = x; this.y = y; this.id = id; } @Override public int compareTo(Point o) { if (this.x < o.x) return -1; if (this.x > o.x) return 1; if (this.y < o.y) return -1; if (this.y > o.y) return 1; if (this.z < o.z) return -1; if (this.z > o.z) return 1; return 0; } @Override public boolean equals(Object that) { return this.compareTo((Point) that) == 0; } /*@Override public int hashCode() { return this.hashCode; }*/ } static class BinaryLift { // FUNCTIONS: k-th ancestor and LCA in log(n) int[] parentOf; int maxJmpPow; int[][] binAncestorOf; int n; int[] lvlOf; // How this works? // a. For every node, we store the b-ancestor for b in {1, 2, 4, 8, .. log(n)}. // b. When we need k-ancestor, we represent 'k' in binary and for each set bit, we // lift level in the tree. public BinaryLift(UGraph tree) { n = tree.V(); maxJmpPow = logk(n, 2) + 1; parentOf = new int[n]; binAncestorOf = new int[n][maxJmpPow]; lvlOf = new int[n]; for (int i = 0; i < n; i++) Arrays.fill(binAncestorOf[i], -1); parentConstruct(0, -1, tree, 0); binConstruct(); } // TODO: Implement lvlOf[] initialization public BinaryLift(int[] parentOf) { this.parentOf = parentOf; n = parentOf.length; maxJmpPow = logk(n, 2) + 1; binAncestorOf = new int[n][maxJmpPow]; lvlOf = new int[n]; for (int i = 0; i < n; i++) Arrays.fill(binAncestorOf[i], -1); UGraph tree = new UGraph(n); for (int i = 1; i < n; i++) tree.addEdge(i, parentOf[i]); binConstruct(); parentConstruct(0, -1, tree, 0); } private void parentConstruct(int current, int from, UGraph tree, int depth) { parentOf[current] = from; lvlOf[current] = depth; for (int adj : tree.adj(current)) if (adj != from) parentConstruct(adj, current, tree, depth + 1); } private void binConstruct() { for (int node = 0; node < n; node++) for (int lvl = 0; lvl < maxJmpPow; lvl++) binConstruct(node, lvl); } private int binConstruct(int node, int lvl) { if (node < 0) return -1; if (lvl == 0) return binAncestorOf[node][lvl] = parentOf[node]; if (node == 0) return binAncestorOf[node][lvl] = -1; if (binAncestorOf[node][lvl] != -1) return binAncestorOf[node][lvl]; return binAncestorOf[node][lvl] = binConstruct(binConstruct(node, lvl - 1), lvl - 1); } // return ancestor which is 'k' levels above this one public int ancestor(int node, int k) { if (node < 0) return -1; if (node == 0) if (k == 0) return node; else return -1; if (k > (1 << maxJmpPow) - 1) return -1; if (k == 0) return node; int ancestor = node; int highestBit = Integer.highestOneBit(k); while (k > 0 && ancestor != -1) { ancestor = binAncestorOf[ancestor][logk(highestBit, 2)]; k -= highestBit; highestBit = Integer.highestOneBit(k); } return ancestor; } public int lca(int u, int v) { if (u == v) return u; // The invariant will be that 'u' is below 'v' initially. if (lvlOf[u] < lvlOf[v]) { int temp = u; u = v; v = temp; } // Equalizing the levels. u = ancestor(u, lvlOf[u] - lvlOf[v]); if (u == v) return u; // We will now raise level by largest fitting power of two until possible. for (int power = maxJmpPow - 1; power > -1; power--) if (binAncestorOf[u][power] != binAncestorOf[v][power]) { u = binAncestorOf[u][power]; v = binAncestorOf[v][power]; } return ancestor(u, 1); } } static class DFSTree { // NOTE: The thing is made keeping in mind that the whole // input graph is connected. UGraph tree; UGraph backUG; int hasBridge; int n; DFSTree(UGraph ug) { this.n = ug.V(); tree = new UGraph(n); hasBridge = -1; backUG = new UGraph(n); treeCalc(0, -1, new boolean[n], ug); } private void treeCalc(int current, int from, boolean[] marked, UGraph ug) { if (marked[current]) { // This is a backEdge. backUG.addEdge(from, current); return; } if (from != -1) tree.addEdge(from, current); marked[current] = true; for (int adj : ug.adj(current)) if (adj != from) treeCalc(adj, current, marked, ug); } public boolean hasBridge() { if (hasBridge != -1) return (hasBridge == 1); // We have to determine the bridge. bridgeFinder(); return (hasBridge == 1); } int[] levelOf; int[] dp; private void bridgeFinder() { // Finding the level of each node. levelOf = new int[n]; // Applying DP solution. // dp[i] -> Highest level reachable from subtree of 'i' using // some backEdge. dp = new int[n]; Arrays.fill(dp, Integer.MAX_VALUE / 100); dpDFS(0, -1, 0); // Now, we will check each edge and determine whether its a // bridge. for (int i = 0; i < n; i++) for (int adj : tree.adj(i)) { // (i -> adj) is the edge. if (dp[adj] > levelOf[i]) hasBridge = 1; } if (hasBridge != 1) hasBridge = 0; } private int dpDFS(int current, int from, int lvl) { levelOf[current] = lvl; dp[current] = levelOf[current]; for (int back : backUG.adj(current)) dp[current] = Math.min(dp[current], levelOf[back]); for (int adj : tree.adj(current)) if (adj != from) dp[current] = Math.min(dp[current], dpDFS(adj, current, lvl + 1)); return dp[current]; } } static class UnionFind { // Uses weighted quick-union with path compression. private int[] parent; // parent[i] = parent of i private int[] size; // size[i] = number of sites in tree rooted at i // Note: not necessarily correct if i is not a root node private int count; // number of components public UnionFind(int n) { count = n; parent = new int[n]; size = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; size[i] = 1; } } // Number of connected components. public int count() { return count; } // Find the root of p. public int find(int p) { while (p != parent[p]) p = parent[p]; return p; } public boolean connected(int p, int q) { return find(p) == find(q); } public int numConnectedTo(int node) { return size[find(node)]; } // Weighted union. public void union(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return; // make smaller root point to larger one if (size[rootP] < size[rootQ]) { parent[rootP] = rootQ; size[rootQ] += size[rootP]; } else { parent[rootQ] = rootP; size[rootP] += size[rootQ]; } count--; } public static int[] connectedComponents(UnionFind uf) { // We can do this in nlogn. int n = uf.size.length; int[] compoColors = new int[n]; for (int i = 0; i < n; i++) compoColors[i] = uf.find(i); HashMap<Integer, Integer> oldToNew = new HashMap<>(); int newCtr = 0; for (int i = 0; i < n; i++) { int thisOldColor = compoColors[i]; Integer thisNewColor = oldToNew.get(thisOldColor); if (thisNewColor == null) thisNewColor = newCtr++; oldToNew.put(thisOldColor, thisNewColor); compoColors[i] = thisNewColor; } return compoColors; } } static class UGraph { // Adjacency list. private HashSet<Integer>[] adj; private static final String NEWLINE = "\n"; private int E; @SuppressWarnings("unchecked") public UGraph(int V) { adj = (HashSet<Integer>[]) new HashSet[V]; E = 0; for (int i = 0; i < V; i++) adj[i] = new HashSet<Integer>(); } public void addEdge(int from, int to) { if (adj[from].contains(to)) return; E++; adj[from].add(to); adj[to].add(from); } public HashSet<Integer> adj(int from) { return adj[from]; } public int degree(int v) { return adj[v].size(); } public int V() { return adj.length; } public int E() { return E; } public String toString() { StringBuilder s = new StringBuilder(); s.append(V() + " vertices, " + E() + " edges " + NEWLINE); for (int v = 0; v < V(); v++) { s.append(v + ": "); for (int w : adj[v]) { s.append(w + " "); } s.append(NEWLINE); } return s.toString(); } public static void dfsMark(int current, boolean[] marked, UGraph g) { if (marked[current]) return; marked[current] = true; Iterable<Integer> adj = g.adj(current); for (int adjc : adj) dfsMark(adjc, marked, g); } public static void dfsMark(int current, int from, long[] distTo, boolean[] marked, UGraph g, ArrayList<Integer> endPoints) { if (marked[current]) return; marked[current] = true; if (from != -1) distTo[current] = distTo[from] + 1; HashSet<Integer> adj = g.adj(current); int alreadyMarkedCtr = 0; for (int adjc : adj) { if (marked[adjc]) alreadyMarkedCtr++; dfsMark(adjc, current, distTo, marked, g, endPoints); } if (alreadyMarkedCtr == adj.size()) endPoints.add(current); } public static void bfsOrder(int current, UGraph g) { } public static void dfsMark(int current, int[] colorIds, int color, UGraph g) { if (colorIds[current] != -1) return; colorIds[current] = color; Iterable<Integer> adj = g.adj(current); for (int adjc : adj) dfsMark(adjc, colorIds, color, g); } public static int[] connectedComponents(UGraph g) { int n = g.V(); int[] componentId = new int[n]; Arrays.fill(componentId, -1); int colorCtr = 0; for (int i = 0; i < n; i++) { if (componentId[i] != -1) continue; dfsMark(i, componentId, colorCtr, g); colorCtr++; } return componentId; } public static boolean hasCycle(UGraph ug) { int n = ug.V(); boolean[] marked = new boolean[n]; boolean[] hasCycleFirst = new boolean[1]; for (int i = 0; i < n; i++) { if (marked[i]) continue; hcDfsMark(i, ug, marked, hasCycleFirst, -1); } return hasCycleFirst[0]; } // Helper for hasCycle. private static void hcDfsMark(int current, UGraph ug, boolean[] marked, boolean[] hasCycleFirst, int parent) { if (marked[current]) return; if (hasCycleFirst[0]) return; marked[current] = true; HashSet<Integer> adjc = ug.adj(current); for (int adj : adjc) { if (marked[adj] && adj != parent && parent != -1) { hasCycleFirst[0] = true; return; } hcDfsMark(adj, ug, marked, hasCycleFirst, current); } } } static class Digraph { // Adjacency list. private HashSet<Integer>[] adj; private static final String NEWLINE = "\n"; private int E; @SuppressWarnings("unchecked") public Digraph(int V) { adj = (HashSet<Integer>[]) new HashSet[V]; E = 0; for (int i = 0; i < V; i++) adj[i] = new HashSet<Integer>(); } public void addEdge(int from, int to) { if (adj[from].contains(to)) return; E++; adj[from].add(to); } public HashSet<Integer> adj(int from) { return adj[from]; } public int V() { return adj.length; } public int E() { return E; } public Digraph reversed() { Digraph dg = new Digraph(V()); for (int i = 0; i < V(); i++) for (int adjVert : adj(i)) dg.addEdge(adjVert, i); return dg; } public String toString() { StringBuilder s = new StringBuilder(); s.append(V() + " vertices, " + E() + " edges " + NEWLINE); for (int v = 0; v < V(); v++) { s.append(v + ": "); for (int w : adj[v]) { s.append(w + " "); } s.append(NEWLINE); } return s.toString(); } public static int[] KosarajuSharirSCC(Digraph dg) { int[] id = new int[dg.V()]; Digraph reversed = dg.reversed(); // Gotta perform topological sort on this one to get the stack. Stack<Integer> revStack = Digraph.topologicalSort(reversed); // Initializing id and idCtr. id = new int[dg.V()]; int idCtr = -1; // Creating a 'marked' array. boolean[] marked = new boolean[dg.V()]; while (!revStack.isEmpty()) { int vertex = revStack.pop(); if (!marked[vertex]) sccDFS(dg, vertex, marked, ++idCtr, id); } return id; } private static void sccDFS(Digraph dg, int source, boolean[] marked, int idCtr, int[] id) { marked[source] = true; id[source] = idCtr; for (Integer adjVertex : dg.adj(source)) if (!marked[adjVertex]) sccDFS(dg, adjVertex, marked, idCtr, id); } public static Stack<Integer> topologicalSort(Digraph dg) { // dg has to be a directed acyclic graph. // We'll have to run dfs on the digraph and push the deepest nodes on stack first. // We'll need a Stack<Integer> and a int[] marked. Stack<Integer> topologicalStack = new Stack<Integer>(); boolean[] marked = new boolean[dg.V()]; // Calling dfs for (int i = 0; i < dg.V(); i++) if (!marked[i]) runDfs(dg, topologicalStack, marked, i); return topologicalStack; } static void runDfs(Digraph dg, Stack<Integer> topologicalStack, boolean[] marked, int source) { marked[source] = true; for (Integer adjVertex : dg.adj(source)) if (!marked[adjVertex]) runDfs(dg, topologicalStack, marked, adjVertex); topologicalStack.add(source); } } static class FastReader { private BufferedReader bfr; private StringTokenizer st; public FastReader() { bfr = new BufferedReader(new InputStreamReader(System.in)); } String next() { if (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(bfr.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()); } char nextChar() { return next().toCharArray()[0]; } String nextString() { return next(); } int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } double[] nextDoubleArray(int n) { double[] arr = new double[n]; for (int i = 0; i < arr.length; i++) arr[i] = nextDouble(); return arr; } long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } int[][] nextIntGrid(int n, int m) { int[][] grid = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) grid[i][j] = fr.nextInt(); } return grid; } } static class SegmentTree { private Node[] heap; private long[] array; private int size; public SegmentTree(long[] array) { this.array = Arrays.copyOf(array, array.length); //The max size of this array is about 2 * 2 ^ log2(n) + 1 size = (int) (2 * Math.pow(2.0, Math.floor((Math.log((double) array.length) / Math.log(2.0)) + 1))); heap = new Node[size]; build(1, 0, array.length); } public int size() { return array.length; } //Initialize the Nodes of the Segment tree private void build(int v, int from, int size) { heap[v] = new Node(); heap[v].from = from; heap[v].to = from + size - 1; if (size == 1) { heap[v].sum = array[from]; heap[v].min = array[from]; heap[v].max = array[from]; } else { //Build childs build(2 * v, from, size / 2); build(2 * v + 1, from + size / 2, size - size / 2); heap[v].sum = heap[2 * v].sum + heap[2 * v + 1].sum; //min = min of the children heap[v].min = Math.min(heap[2 * v].min, heap[2 * v + 1].min); heap[v].max = Math.max(heap[2 * v].max, heap[2 * v + 1].max); } } public long rsq(int from, int to) { return rsq(1, from, to); } private long rsq(int v, int from, int to) { Node n = heap[v]; //If you did a range update that contained this node, you can infer the Sum without going down the tree if (n.pendingVal != null && contains(n.from, n.to, from, to)) { return (to - from + 1) * n.pendingVal; } if (contains(from, to, n.from, n.to)) { return heap[v].sum; } if (intersects(from, to, n.from, n.to)) { propagate(v); long leftSum = rsq(2 * v, from, to); long rightSum = rsq(2 * v + 1, from, to); return leftSum + rightSum; } return 0; } public long rMinQ(int from, int to) { return rMinQ(1, from, to); } private long rMinQ(int v, int from, int to) { Node n = heap[v]; //If you did a range update that contained this node, you can infer the Min value without going down the tree if (n.pendingVal != null && contains(n.from, n.to, from, to)) { return n.pendingVal; } if (contains(from, to, n.from, n.to)) { return heap[v].min; } if (intersects(from, to, n.from, n.to)) { propagate(v); long leftMin = rMinQ(2 * v, from, to); long rightMin = rMinQ(2 * v + 1, from, to); return Math.min(leftMin, rightMin); } return Integer.MAX_VALUE; } public long rMaxQ(int from, int to) { return rMaxQ(1, from, to); } private long rMaxQ(int v, int from, int to) { Node n = heap[v]; //If you did a range update that contained this node, you can infer the Min value without going down the tree if (n.pendingVal != null && contains(n.from, n.to, from, to)) { return n.pendingVal; } if (contains(from, to, n.from, n.to)) { return heap[v].max; } if (intersects(from, to, n.from, n.to)) { propagate(v); long leftMax = rMaxQ(2 * v, from, to); long rightMax = rMaxQ(2 * v + 1, from, to); return Math.max(leftMax, rightMax); } return Integer.MIN_VALUE; } public void update(int from, int to, long value) { update(1, from, to, value); } private void update(int v, int from, int to, long value) { //The Node of the heap tree represents a range of the array with bounds: [n.from, n.to] Node n = heap[v]; if (contains(from, to, n.from, n.to)) { change(n, value); } if (n.size() == 1) return; if (intersects(from, to, n.from, n.to)) { propagate(v); update(2 * v, from, to, value); update(2 * v + 1, from, to, value); n.sum = heap[2 * v].sum + heap[2 * v + 1].sum; n.min = Math.min(heap[2 * v].min, heap[2 * v + 1].min); n.max = Math.max(heap[2 * v].max, heap[2 * v + 1].max); } } //Propagate temporal values to children private void propagate(int v) { Node n = heap[v]; if (n.pendingVal != null) { change(heap[2 * v], n.pendingVal); change(heap[2 * v + 1], n.pendingVal); n.pendingVal = null; //unset the pending propagation value } } //Save the temporal values that will be propagated lazily private void change(Node n, long value) { n.pendingVal = value; n.sum = n.size() * value; n.min = value; n.max = value; array[n.from] = value; } //Test if the range1 contains range2 private boolean contains(int from1, int to1, int from2, int to2) { return from2 >= from1 && to2 <= to1; } //check inclusive intersection, test if range1[from1, to1] intersects range2[from2, to2] private boolean intersects(int from1, int to1, int from2, int to2) { return from1 <= from2 && to1 >= from2 // (.[..)..] or (.[...]..) || from1 >= from2 && from1 <= to2; // [.(..]..) or [..(..).. } //The Node class represents a partition range of the array. static class Node { long sum; long min; long max; //Here we store the value that will be propagated lazily Long pendingVal = null; int from; int to; int size() { return to - from + 1; } } } @SuppressWarnings("serial") static class CountMap<T> extends TreeMap<T, Integer>{ CountMap() { } CountMap(T[] arr) { this.putCM(arr); } public Integer putCM(T key) { return super.put(key, super.getOrDefault(key, 0) + 1); } public Integer removeCM(T key) { int count = super.getOrDefault(key, -1); if (count == -1) return -1; if (count == 1) return super.remove(key); else return super.put(key, count - 1); } public Integer getCM(T key) { return super.getOrDefault(key, 0); } public void putCM(T[] arr) { for (T l : arr) this.putCM(l); } } static long dioGCD(long a, long b, long[] x0, long[] y0) { if (b == 0) { x0[0] = 1; y0[0] = 0; return a; } long[] x1 = new long[1], y1 = new long[1]; long d = dioGCD(b, a % b, x1, y1); x0[0] = y1[0]; y0[0] = x1[0] - y1[0] * (a / b); return d; } static boolean diophantine(long a, long b, long c, long[] x0, long[] y0, long[] g) { g[0] = dioGCD(Math.abs(a), Math.abs(b), x0, y0); if (c % g[0] > 0) { return false; } x0[0] *= c / g[0]; y0[0] *= c / g[0]; if (a < 0) x0[0] = -x0[0]; if (b < 0) y0[0] = -y0[0]; return true; } static long[][] prod(long[][] mat1, long[][] mat2) { int n = mat1.length; long[][] prod = new long[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) // determining prod[i][j] // it will be the dot product of mat1[i][] and mat2[][i] for (int k = 0; k < n; k++) prod[i][j] += mat1[i][k] * mat2[k][j]; return prod; } static long[][] matExpo(long[][] mat, long power) { int n = mat.length; long[][] ans = new long[n][n]; if (power == 0) return null; if (power == 1) return mat; long[][] half = matExpo(mat, power / 2); ans = prod(half, half); if (power % 2 == 1) { ans = prod(ans, mat); } return ans; } static int KMPNumOcc(char[] text, char[] pat) { int n = text.length; int m = pat.length; char[] patPlusText = new char[n + m + 1]; for (int i = 0; i < m; i++) patPlusText[i] = pat[i]; patPlusText[m] = '^'; // Seperator for (int i = 0; i < n; i++) patPlusText[m + i] = text[i]; int[] fullPi = piCalcKMP(patPlusText); int answer = 0; for (int i = 0; i < n + m + 1; i++) if (fullPi[i] == m) answer++; return answer; } static int[] piCalcKMP(char[] s) { int n = s.length; int[] pi = new int[n]; for (int i = 1; i < n; i++) { int j = pi[i - 1]; while (j > 0 && s[i] != s[j]) j = pi[j - 1]; if (s[i] == s[j]) j++; pi[i] = j; } return pi; } static long hash(long key) { long h = Long.hashCode(key); h ^= (h >>> 20) ^ (h >>> 12) ^ (h >>> 7) ^ (h >>> 4); return h & (gigamod-1); } static int mapTo1D(int row, int col, int n, int m) { // Maps elements in a 2D matrix serially to elements in // a 1D array. return row * m + col; } static int[] mapTo2D(int idx, int n, int m) { // Inverse of what the one above does. int[] rnc = new int[2]; rnc[0] = idx / m; rnc[1] = idx % m; return rnc; } static boolean[] primeGenerator(int upto) { // Sieve of Eratosthenes: isPrime = new boolean[upto + 1]; smallestFactorOf = new int[upto + 1]; Arrays.fill(smallestFactorOf, 1); Arrays.fill(isPrime, true); isPrime[1] = isPrime[0] = false; for (long i = 2; i < upto + 1; i++) if (isPrime[(int) i]) { smallestFactorOf[(int) i] = (int) i; // Mark all the multiples greater than or equal // to the square of i to be false. for (long j = i; j * i < upto + 1; j++) { if (isPrime[(int) j * (int) i]) { isPrime[(int) j * (int) i] = false; smallestFactorOf[(int) j * (int) i] = (int) i; } } } return isPrime; } static HashMap<Integer, Integer> smolNumPrimeFactorization(int num) { if (smallestFactorOf == null) primeGenerator(num + 1); HashMap<Integer, Integer> fnps = new HashMap<>(); while (num != 1) { fnps.put(smallestFactorOf[num], fnps.getOrDefault(smallestFactorOf[num], 0) + 1); num /= smallestFactorOf[num]; } return fnps; } static HashMap<Long, Integer> primeFactorization(long num) { // Returns map of factor and its power in the number. HashMap<Long, Integer> map = new HashMap<>(); while (num % 2 == 0) { num /= 2; Integer pwrCnt = map.get(2L); map.put(2L, pwrCnt != null ? pwrCnt + 1 : 1); } for (long i = 3; i * i <= num; i += 2) { while (num % i == 0) { num /= i; Integer pwrCnt = map.get(i); map.put(i, pwrCnt != null ? pwrCnt + 1 : 1); } } // If the number is prime, we have to add it to the // map. if (num != 1) map.put(num, 1); return map; } static HashSet<Long> divisors(long num) { HashSet<Long> divisors = new HashSet<Long>(); divisors.add(1L); divisors.add(num); for (long i = 2; i * i <= num; i++) { if (num % i == 0) { divisors.add(num/i); divisors.add(i); } } return divisors; } static void coprimeGenerator(int m, int n, ArrayList<Point> coprimes, int limit, int numCoprimes) { if (m > limit) return; if (m <= limit && n <= limit) coprimes.add(new Point(m, n)); if (coprimes.size() > numCoprimes) return; coprimeGenerator(2 * m - n, m, coprimes, limit, numCoprimes); coprimeGenerator(2 * m + n, m, coprimes, limit, numCoprimes); coprimeGenerator(m + 2 * n, n, coprimes, limit, numCoprimes); } static int bsearch(int[] arr, int val, int lo, int hi) { // Returns the index of the first element // larger than or equal to val. int idx = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (arr[mid] >= val) { idx = mid; hi = mid - 1; } else lo = mid + 1; } return idx; } static int bsearch(long[] arr, long val, int lo, int hi) { // Returns the index of the first element // larger than or equal to val. int idx = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (arr[mid] >= val) { idx = mid; hi = mid - 1; } else lo = mid + 1; } return idx; } static int bsearch(long[] arr, long val, int lo, int hi, boolean sMode) { // Returns the index of the last element // smaller than or equal to val. int idx = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (arr[mid] > val) { hi = mid - 1; } else { idx = mid; lo = mid + 1; } } return idx; } static int bsearch(int[] arr, long val, int lo, int hi, boolean sMode) { int idx = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (arr[mid] > val) { hi = mid - 1; } else { idx = mid; lo = mid + 1; } } return idx; } static long nCr(long n, long r, long[] fac) { long p = mod; if (r == 0) return 1; return (fac[(int)n] * modInverse(fac[(int)r], p) % p * modInverse(fac[(int)n - (int)r], p) % p) % p; } static long modInverse(long n, long p) { return power(n, p - 2, p); } static long modDiv(long a, long b){return mod(a * power(b, gigamod - 2, gigamod));} static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1)==1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static int logk(long n, long k) { return (int)(Math.log(n) / Math.log(k)); } 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 gcd(long[] arr) { int n = arr.length; long gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static int gcd(int[] arr) { int n = arr.length; int gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static long lcm(long[] arr) { long lcm = arr[0]; int n = arr.length; for (int i = 1; i < n; i++) { lcm = (lcm * arr[i]) / gcd(lcm, arr[i]); } return lcm; } static long lcm(long a, long b) { return (a * b)/gcd(a, b); } static boolean less(int a, int b) { return a < b ? true : false; } static boolean isSorted(int[] a) { for (int i = 1; i < a.length; i++) { if (less(a[i], a[i - 1])) return false; } return true; } static boolean isSorted(long[] a) { for (int i = 1; i < a.length; i++) { if (a[i] < a[i - 1]) return false; } return true; } static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(long[] a, int i, int j) { long temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(double[] a, int i, int j) { double temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(char[] a, int i, int j) { char temp = a[i]; a[i] = a[j]; a[j] = temp; } static void sort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void reverseSort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverse(char[] arr) { int n = arr.length; for (int i = 0; i < n / 2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void shuffleArray(long[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { long tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(int[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(double[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { double tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(char[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { char tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static boolean isPrime(long n) {if (n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(long i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;} static String toString(int[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();} static String toString(boolean[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();} static String toString(long[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();} static String toString(char[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+"");return sb.toString();} static String toString(int[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();} static String toString(long[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++) {sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();} static String toString(double[][] dp){StringBuilder sb=new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();} static String toString(char[][] dp){StringBuilder sb = new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+"");}sb.append('\n');}return sb.toString();} static long mod(long a, long m){return(a%m+1000000L*m)%m;} static long mod(long num){return(num%gigamod+gigamod)%gigamod;} } // NOTES: // ASCII VALUE OF 'A': 65 // ASCII VALUE OF 'a': 97 // Range of long: 9 * 10^18 // ASCII VALUE OF '0': 48 // Primes upto 'n' can be given by (n / (logn)).
java