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
1284
C
C. New Year and Permutationtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputRecall that the permutation is an array consisting of nn distinct integers from 11 to nn in arbitrary order. For example, [2,3,1,5,4][2,3,1,5,4] is a permutation, but [1,2,2][1,2,2] is not a permutation (22 appears twice in the array) and [1,3,4][1,3,4] is also not a permutation (n=3n=3 but there is 44 in the array).A sequence aa is a subsegment of a sequence bb if aa can be obtained from bb by deletion of several (possibly, zero or all) elements from the beginning and several (possibly, zero or all) elements from the end. We will denote the subsegments as [l,r][l,r], where l,rl,r are two integers with 1≤l≤r≤n1≤l≤r≤n. This indicates the subsegment where l−1l−1 elements from the beginning and n−rn−r elements from the end are deleted from the sequence.For a permutation p1,p2,…,pnp1,p2,…,pn, we define a framed segment as a subsegment [l,r][l,r] where max{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−lmax{pl,pl+1,…,pr}−min{pl,pl+1,…,pr}=r−l. For example, for the permutation (6,7,1,8,5,3,2,4)(6,7,1,8,5,3,2,4) some of its framed segments are: [1,2],[5,8],[6,7],[3,3],[8,8][1,2],[5,8],[6,7],[3,3],[8,8]. In particular, a subsegment [i,i][i,i] is always a framed segments for any ii between 11 and nn, inclusive.We define the happiness of a permutation pp as the number of pairs (l,r)(l,r) such that 1≤l≤r≤n1≤l≤r≤n, and [l,r][l,r] is a framed segment. For example, the permutation [3,1,2][3,1,2] has happiness 55: all segments except [1,2][1,2] are framed segments.Given integers nn and mm, Jongwon wants to compute the sum of happiness for all permutations of length nn, modulo the prime number mm. Note that there exist n!n! (factorial of nn) different permutations of length nn.InputThe only line contains two integers nn and mm (1≤n≤2500001≤n≤250000, 108≤m≤109108≤m≤109, mm is prime).OutputPrint rr (0≤r<m0≤r<m), the sum of happiness for all permutations of length nn, modulo a prime number mm.ExamplesInputCopy1 993244853 OutputCopy1 InputCopy2 993244853 OutputCopy6 InputCopy3 993244853 OutputCopy32 InputCopy2019 993244853 OutputCopy923958830 InputCopy2020 437122297 OutputCopy265955509 NoteFor sample input n=3n=3; let's consider all permutations of length 33: [1,2,3][1,2,3], all subsegments are framed segment. Happiness is 66. [1,3,2][1,3,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [2,1,3][2,1,3], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [2,3,1][2,3,1], all subsegments except [2,3][2,3] are framed segment. Happiness is 55. [3,1,2][3,1,2], all subsegments except [1,2][1,2] are framed segment. Happiness is 55. [3,2,1][3,2,1], all subsegments are framed segment. Happiness is 66. Thus, the sum of happiness is 6+5+5+5+5+6=326+5+5+5+5+6=32.
[ "combinatorics", "math" ]
// हर हर महादेव import java.util.*; import java.lang.*; import java.io.*; import java.text.DecimalFormat; public final class Solution { static int inf = Integer.MAX_VALUE; static long mod = 1000000000 + 7; static void ne(Scanner sc, BufferedWriter op) throws Exception { int n=sc.nextInt(); int m=sc.nextInt(); long ans=0L; long[] f= new long[(int)n+1]; f[0]=1; for(int i=1;i<n+1;i++){ f[i]=(f[i-1]*(long)i)%m; } for(int i=1;i<n;i++){ ans=(ans+( (n-i)* f[n-i]%m * f[i+1]%m ))%m; } ans=(ans+(n*f[n]%m))%m; ans%=m; op.write(ans+"\n"); } // static long fact(long no, long m){ // } static int gcd(int a, int b){ if(a==0) return b; return gcd(b%a,a); } static int lcm(int a, int b){ return (a*b)/gcd(a,b); } public static void main(String[] args) throws Exception { BufferedWriter op = new BufferedWriter(new OutputStreamWriter(System.out)); Scanner sc = new Scanner(System.in); // int t = sc.nextInt(); // while (t-->0){ne(sc, op);} ne(sc,op); op.flush(); } static void print(Object o) { System.out.println(String.valueOf(o)); } } // return -1 to put no ahed in array class pair { int xx; int yy; pair(int xx, int yy ) { this.xx = xx; this.yy = yy; } } class sortY implements Comparator<pair> { public int compare(pair p1, pair p2) { if (p1.yy > p2.yy) { return 1; } else if (p1.yy == p2.yy) { if (p1.xx > p2.xx) { return 1; } else if (p1.xx < p2.xx) { return -1; } return 0; } return -1; } } class sortX implements Comparator<pair> { public int compare(pair p1, pair p2) { if (p1.xx > p2.xx) { return 1; } else if (p1.xx == p2.xx) { if (p1.yy > p2.yy) { return 1; } else if (p1.yy < p2.yy) { return -1; } return 0; } return -1; } } class debug { static void print1d(long[] arr) { System.out.println(); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } static void print1d(int[] arr) { System.out.println(); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } static void print1d(boolean[] arr) { System.out.println(); for (int i = 0; i < arr.length; i++) { System.out.println(i + "= " + arr[i] + " "); } } static void print2d(int[][] arr) { System.out.println(); int n = arr.length; int n2 = arr[0].length; for (int i = 0; i < n; i++) { for (int j = 0; j < n2; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } } static void print2d(long[][] arr) { System.out.println(); int n = arr.length; int n2 = arr[0].length; for (int i = 0; i < n; i++) { for (int j = 0; j < n2; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } } static void printPair(ArrayList<pair> list) { if(list.size()==0){ System.out.println("empty list"); return; } System.out.println(); for(int i=0;i<list.size();i++){ System.out.println(list.get(i).xx+"-"+list.get(i).yy); } } } class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { if (cnt != 0) { break; } else { continue; } } buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } //bs // logical error we need to search next greater or next smaller both // and find min;
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" ]
import java.util.*; import java.io.*; public class dsu { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int t = Integer.parseInt(br.readLine()); TreeSet<Integer> div[] = new TreeSet[3 * 10000]; for (int i = 0; i < div.length; i++) { div[i] = new TreeSet<>(); } for (int i = 1; i < div.length; i++) { for (int j = 1; j <= Math.ceil(Math.sqrt(i)); j++) { if (i % j == 0) { div[i].add(j); div[i].add(i / j); } } } while (t-- > 0) { StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); ArrayList<Integer> a = new ArrayList<>(); int i = 1; int sum = 0; int idx = 0; int x = 1; int q = n - 1; while (n > 0) { a.add(Math.min(i, n)); n -= Math.min(i, n); i *= 2; } for (int j = 0; j < a.size(); j++) { sum += a.get(j) * (j); } boolean f = true; long max = (q * 1l * (q + 1)) / 2; if (m < sum || m > max) { f = false; } m -= sum; // System.out.println(a+" "+sum); x = -1; if (f) while (m != 0 && sum != max && sum != x) { x = sum; for (int j = 0; j < a.size() - 1; j++) { if ((a.get(j) - 1) * 2 >= (a.get(j + 1) + 1)) { a.set(j, a.get(j) - 1); a.set(j + 1, a.get(j + 1) + 1); sum++; m--; break; } } if (sum == x && a.get(a.size() - 1) != 1) { a.add(1); a.set(a.size() - 2, a.get(a.size() - 2) - 1); sum++; m--; } } if (f) { System.out.println("YES"); x = 1; int r=1; for (int j = 1; j < a.size(); j++) { x=r; int w = a.get(j); while (w != 0) { int e = Math.min(w, 2); w -= e; while (e-- > 0) { System.out.print(x + " "); } x++; } r+=a.get(j-1); } System.out.println(); } else System.out.println("NO"); } } static class pair { long x; int y; pair(long r, int t) { x = r; y = t; } } }
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.io.PrintWriter; import java.util.StringTokenizer; public class ProductOfThreeNumbersAgain { public static void main(String[] args) { // TODO Auto-generated method stub FastScanner fs = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); int T = fs.nextInt(); while (T-- > 0) { int N = fs.nextInt(); int a = -1; for (int i = 2; i * i <= N; i++) { /* * pw.println("i * i <= N " + (a*a <= N)); pw.println("i--> " + a); * pw.println("N%a == 0 " + (N%a == 0)); */ if (N%i == 0) { a = i; N /= a; break; } } // pw.println("a--> "+ a + " N---> "+N); if (a == -1) { pw.println("NO"); continue; } int b = -1; for (int i = a + 1; i * i <= N; i++) { if (N%i == 0) { b = i; N /= i; break; } } // pw.println("b--> "+ b + " N---> "+N); int c = N; // pw.println("c--> "+c); if (b == -1 || c <= b) { pw.println("NO"); } else { pw.println("YES"); pw.println(a + " " + b + " " + c); } } pw.close(); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } long[] readArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
java
1305
A
A. Kuroni and the Giftstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni has nn daughters. As gifts for them, he bought nn necklaces and nn bracelets: the ii-th necklace has a brightness aiai, where all the aiai are pairwise distinct (i.e. all aiai are different), the ii-th bracelet has a brightness bibi, where all the bibi are pairwise distinct (i.e. all bibi are different). Kuroni wants to give exactly one necklace and exactly one bracelet to each of his daughters. To make sure that all of them look unique, the total brightnesses of the gifts given to each daughter should be pairwise distinct. Formally, if the ii-th daughter receives a necklace with brightness xixi and a bracelet with brightness yiyi, then the sums xi+yixi+yi should be pairwise distinct. Help Kuroni to distribute the gifts.For example, if the brightnesses are a=[1,7,5]a=[1,7,5] and b=[6,1,2]b=[6,1,2], then we may distribute the gifts as follows: Give the third necklace and the first bracelet to the first daughter, for a total brightness of a3+b1=11a3+b1=11. Give the first necklace and the third bracelet to the second daughter, for a total brightness of a1+b3=3a1+b3=3. Give the second necklace and the second bracelet to the third daughter, for a total brightness of a2+b2=8a2+b2=8. Here is an example of an invalid distribution: Give the first necklace and the first bracelet to the first daughter, for a total brightness of a1+b1=7a1+b1=7. Give the second necklace and the second bracelet to the second daughter, for a total brightness of a2+b2=8a2+b2=8. Give the third necklace and the third bracelet to the third daughter, for a total brightness of a3+b3=7a3+b3=7. This distribution is invalid, as the total brightnesses of the gifts received by the first and the third daughter are the same. Don't make them this upset!InputThe input consists of multiple test cases. The first line contains an integer tt (1≤t≤1001≤t≤100)  — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1001≤n≤100)  — the number of daughters, necklaces and bracelets.The second line of each test case contains nn distinct integers a1,a2,…,ana1,a2,…,an (1≤ai≤10001≤ai≤1000)  — the brightnesses of the necklaces.The third line of each test case contains nn distinct integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤10001≤bi≤1000)  — the brightnesses of the bracelets.OutputFor each test case, print a line containing nn integers x1,x2,…,xnx1,x2,…,xn, representing that the ii-th daughter receives a necklace with brightness xixi. In the next line print nn integers y1,y2,…,yny1,y2,…,yn, representing that the ii-th daughter receives a bracelet with brightness yiyi.The sums x1+y1,x2+y2,…,xn+ynx1+y1,x2+y2,…,xn+yn should all be distinct. The numbers x1,…,xnx1,…,xn should be equal to the numbers a1,…,ana1,…,an in some order, and the numbers y1,…,yny1,…,yn should be equal to the numbers b1,…,bnb1,…,bn in some order. It can be shown that an answer always exists. If there are multiple possible answers, you may print any of them.ExampleInputCopy2 3 1 8 5 8 4 5 3 1 7 5 6 1 2 OutputCopy1 8 5 8 4 5 5 1 7 6 2 1 NoteIn the first test case; it is enough to give the ii-th necklace and the ii-th bracelet to the ii-th daughter. The corresponding sums are 1+8=91+8=9, 8+4=128+4=12, and 5+5=105+5=10.The second test case is described in the statement.
[ "brute force", "constructive algorithms", "greedy", "sortings" ]
import java.util.*; import java.io.*; import java.math.*; import java.lang.*; public class CP { static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() { 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(); } String nextLine() { String str=""; try { str=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } static void ruffleSort(int[] a) { Random rnd=new Random(); for(int i=0;i<=a.length-1;i++) { int temp=a[i]; int rndPos=i+rnd.nextInt(a.length-i); a[i]=a[rndPos]; a[rndPos]=temp; } Arrays.sort(a); } static void testCase(FastScanner sc) { long mod1=(long)1e9+7, mod2=998244353; long inf=(long)1e18+5; int n=sc.nextInt(); ArrayList<Integer> a=new ArrayList<Integer>(), b=new ArrayList<Integer>(); for(int i=0;i<=n-1;i++) { a.add(sc.nextInt()); } for(int i=0;i<=n-1;i++) { b.add(sc.nextInt()); } Collections.sort(a); Collections.sort(b); for(int val: a) { System.out.print(val+" "); } System.out.println(); for(int val: b) { System.out.print(val+" "); } System.out.println(); } public static void main(String[] args) { FastScanner sc=new FastScanner(); boolean test=true; int t=1; if(test) { t=sc.nextInt(); } for(int i=0;i<=t-1;i++) { testCase(sc); } } }
java
1304
B
B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has nn distinct strings of equal length mm. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers nn and mm (1≤n≤1001≤n≤100, 1≤m≤501≤m≤50) — the number of strings and the length of each string.Next nn lines contain a string of length mm each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInputCopy3 3 tab one bat OutputCopy6 tabbat InputCopy4 2 oo ox xo xx OutputCopy6 oxxxxo InputCopy3 5 hello codef orces OutputCopy0 InputCopy9 4 abab baba abcd bcde cdef defg wxyz zyxw ijji OutputCopy20 ababwxyzijjizyxwbaba NoteIn the first example; "battab" is also a valid answer.In the second example; there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example; the empty string is the only valid palindrome string.
[ "brute force", "constructive algorithms", "greedy", "implementation", "strings" ]
import java.util.*; import java.lang.*; import java.io.*; public class Main { static long mod = (int)1e9+7; static PrintWriter out=new PrintWriter(new BufferedOutputStream(System.out)); public static void main (String[] args) throws java.lang.Exception { FastReader sc =new FastReader(); // int t=sc.nextInt(); int m=1; O : while(m-->0) { int n = sc.nextInt(); int t = sc.nextInt(); boolean[] used = new boolean[n]; String[] a = new String[n]; for (int i = 0; i < n; i++) { a[i] = sc.next(); } String ans = ""; for (int i = 0; i < n; i++) { if (used[i]) continue; for (int j = i + 1; j < n; j++) { if (used[j]) continue; boolean good = true; for (int k = 0; k < t; k++) { if (a[i].charAt(k) != a[j].charAt(t-1-k)) { good = false; break; } } if (good) { used[i] = used[j] = true; ans = a[i] + ans + a[j]; } } } for (int i = 0; i < n; i++) { if (used[i]) continue; boolean good = true; for (int k = 0; k < t; k++) { if (a[i].charAt(k) != a[i].charAt(t-1-k)) { good = false; break; } } if (good) { if (ans.length() == 0) ans = a[i]; else { ans = ans.substring(0, ans.length() / 2) + a[i] + ans.substring(ans.length() / 2); } break; } } out.println(ans.length()); out.println(ans); } out.flush(); } static void printN() { System.out.println("NO"); } static void printY() { System.out.println("YES"); } static int findfrequencies(int a[],int n) { int count=0; for(int i=0;i<a.length;i++) { if(a[i]==n) { count++; } } return count; } 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()); } String nextLine() { String str = ""; 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[] readArrayLong(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } } 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[] EvenOddArragement(int a[]) { ArrayList<Integer> list=new ArrayList<>(); for(int i=0;i<a.length;i++) { if(a[i]%2==0) { list.add(a[i]); } } for(int i=0;i<a.length;i++) { if(a[i]%2!=0) { list.add(a[i]); } } for(int i=0;i<a.length;i++) { a[i]=list.get(i); } return a; } static int gcd(int a, int b) { while (b != 0) { int t = a; a = b; b = t % b; } return a; } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } public static HashMap<Integer, Integer> sortByValue(HashMap<Integer, Integer> hm) { // Create a list from elements of HashMap List<Map.Entry<Integer, Integer> > list = new LinkedList<Map.Entry<Integer, Integer> >(hm.entrySet()); // Sort the list Collections.sort(list, new Comparator<Map.Entry<Integer, Integer> >() { public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); // put data from sorted list to hashmap HashMap<Integer, Integer> temp = new LinkedHashMap<Integer, Integer>(); for (Map.Entry<Integer, Integer> aa : list) { temp.put(aa.getKey(), aa.getValue()); } return temp; } static int DigitSum(int n) { int r=0,sum=0; while(n>=0) { r=n%10; sum=sum+r; n=n/10; } return sum; } static boolean checkPerfectSquare(int number) { double sqrt=Math.sqrt(number); return ((sqrt - Math.floor(sqrt)) == 0); } static boolean isPowerOfTwo(int n) { if(n==0) return false; return (int)(Math.ceil((Math.log(n) / Math.log(2)))) == (int)(Math.floor(((Math.log(n) / Math.log(2))))); } static boolean isPrime2(int n) { if (n <= 1) { return false; } if (n == 2) { return true; } if (n % 2 == 0) { return false; } for (int i = 3; i <= Math.sqrt(n) + 1; i = i + 2) { if (n % i == 0) { return false; } } return true; } static String minLexRotation(String str) { int n = str.length(); String arr[] = new String[n]; String concat = str + str; for(int i=0;i<n;i++) { arr[i] = concat.substring(i, i + n); } Arrays.sort(arr); return arr[0]; } static String maxLexRotation(String str) { int n = str.length(); String arr[] = new String[n]; String concat = str + str; for (int i = 0; i < n; i++) { arr[i] = concat.substring(i, i + n); } Arrays.sort(arr); return arr[arr.length-1]; } static class P implements Comparable<P> { int i, j; public P(int i, int j) { this.i=i; this.j=j; } public int compareTo(P o) { return Integer.compare(i, o.i); } } static int binary_search(int a[],int value) { int start=0; int end=a.length-1; int mid=start+(end-start)/2; while(start<=end) { if(a[mid]==value) { return mid; } if(a[mid]>value) { end=mid-1; } else { start=mid+1; } mid=start+(end-start)/2; } return -1; } }
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" ]
// package CP; import java.util.*; import java.io.*; public class Main { 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 java.lang.Exception { FastReader sc = new FastReader(); BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out)); int t = 1; // t = sc.nextInt(); while (t-- != 0) { int n = sc.nextInt(); int m[] = new int[n]; int lr_nextSmaller[] = new int[n]; int rl_nextSmaller[] = new int[n]; for (int i = 0; i < n; i++) { m[i] = sc.nextInt(); } Stack<Integer> st = new Stack<>(); for (int i = n - 1; i >= 0; i--) { while (!st.isEmpty() && m[i] <= m[st.peek()]) { st.pop(); } if (st.isEmpty()) { lr_nextSmaller[i] = -1; } else { lr_nextSmaller[i] = st.peek(); } st.push(i); } st.clear(); for (int i = 0; i < n; i++) { while (!st.isEmpty() && m[i] <= m[st.peek()]) { st.pop(); } if (st.isEmpty()) { rl_nextSmaller[i] = -1; } else { rl_nextSmaller[i] = st.peek(); } st.push(i); } long leftdp[] = new long[n]; leftdp[0] = m[0]; for (int i = 1; i < n; i++) { if (m[i - 1] <= m[i]) { leftdp[i] = leftdp[i - 1] + m[i]; } else { int nextSmaller = rl_nextSmaller[i]; if (nextSmaller == -1) { leftdp[i] = m[i] * (i * 1L - (-1L)); } else { leftdp[i] = leftdp[nextSmaller] + m[i] * (i * 1L - nextSmaller); } } } long rightdp[] = new long[n]; rightdp[n - 1] = m[n - 1]; for (int i = n - 2; i >= 0; i--) { if (m[i + 1] <= m[i]) { rightdp[i] = rightdp[i + 1] + m[i]; } else { int nextSmaller = lr_nextSmaller[i]; if (nextSmaller == -1) { rightdp[i] = m[i] * (n * 1L - i * 1L); } else { rightdp[i] = rightdp[nextSmaller] + m[i] * (nextSmaller - i * 1L); } } } int max = 0; for (int i = 0; i < n; i++) { if ((leftdp[max] + rightdp[max] - m[max]) < (leftdp[i] + rightdp[i] - m[i])) { max = i; } } for (int i = max + 1; i < n; i++) { m[i] = Math.min(m[i - 1], m[i]); } for (int i = max - 1; i >= 0; i--) { m[i] = Math.min(m[i + 1], m[i]); } for (int i = 0; i < n; i++) { w.write(m[i] + "\n"); } } w.flush(); w.close(); } }
java
1301
C
C. Ayoub's functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAyoub thinks that he is a very smart person; so he created a function f(s)f(s), where ss is a binary string (a string which contains only symbols "0" and "1"). The function f(s)f(s) is equal to the number of substrings in the string ss that contains at least one symbol, that is equal to "1".More formally, f(s)f(s) is equal to the number of pairs of integers (l,r)(l,r), such that 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of string ss), such that at least one of the symbols sl,sl+1,…,srsl,sl+1,…,sr is equal to "1". For example, if s=s="01010" then f(s)=12f(s)=12, because there are 1212 such pairs (l,r)(l,r): (1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5)(1,2),(1,3),(1,4),(1,5),(2,2),(2,3),(2,4),(2,5),(3,4),(3,5),(4,4),(4,5).Ayoub also thinks that he is smarter than Mahmoud so he gave him two integers nn and mm and asked him this problem. For all binary strings ss of length nn which contains exactly mm symbols equal to "1", find the maximum value of f(s)f(s).Mahmoud couldn't solve the problem so he asked you for help. Can you help him? InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1051≤t≤105)  — the number of test cases. The description of the test cases follows.The only line for each test case contains two integers nn, mm (1≤n≤1091≤n≤109, 0≤m≤n0≤m≤n) — the length of the string and the number of symbols equal to "1" in it.OutputFor every test case print one integer number — the maximum value of f(s)f(s) over all strings ss of length nn, which has exactly mm symbols, equal to "1".ExampleInputCopy5 3 1 3 2 3 3 4 0 5 2 OutputCopy4 5 6 0 12 NoteIn the first test case; there exists only 33 strings of length 33, which has exactly 11 symbol, equal to "1". These strings are: s1=s1="100", s2=s2="010", s3=s3="001". The values of ff for them are: f(s1)=3,f(s2)=4,f(s3)=3f(s1)=3,f(s2)=4,f(s3)=3, so the maximum value is 44 and the answer is 44.In the second test case, the string ss with the maximum value is "101".In the third test case, the string ss with the maximum value is "111".In the fourth test case, the only string ss of length 44, which has exactly 00 symbols, equal to "1" is "0000" and the value of ff for that string is 00, so the answer is 00.In the fifth test case, the string ss with the maximum value is "01010" and it is described as an example in the problem statement.
[ "binary search", "combinatorics", "greedy", "math", "strings" ]
/* TO LEARN 1-segment trees 2-euler tour 3-fenwick tree and interval tree */ /* TO SOLVE uva 1103 program codeforces edu 102 D */ /* bit manipulation shit 1-Computer Systems: A Programmer's Perspective 2-hacker's delight 3-(02-03-bits-ints) 4-machine-basics 5-Bits Manipulation tutorialspoint */ /* TO WATCH 1-what is bitmasking by kartik arora youtube */ import java.util.*; import java.math.*; import java.io.*; import java.util.stream.Collectors; public class A{ static InputStream inputStream = System.in; static FastScanner scan=new FastScanner(); public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); public static void main(String[] args) throws Exception { // scan=new FastScanner("help.in"); //out = new PrintWriter("lifeguards.out"); /* currently doing 1-digit dp 2-ds like fenwick and interval tree and sparse table */ /* READING 1-Everything About Dynamic Programming codeforces 2-DYNAMIC PROGRAMMING: FROM NOVICE TO ADVANCED topcoder 3-Introduction to DP with Bitmasking codefoces 4-Bit Manipulation hackerearth 5-read more about mobious and inculsion-exclusion */ int tt=1; tt=scan.nextInt(); outer:while(tt-->0) { long n=scan.nextLong(),m=scan.nextLong(); if(m>=n/2) { long num=n*(n+1)/2; out.println(num-(n-m)); } else { long todivide=m+1; long num=(n-m)/todivide; long mod=(n-m)%todivide; long first=(((num+1)*(num+2))/2)*mod; long second=(m+1)-mod; second=second*(num*(num+1)/2); out.println((n*(n+1)/2)-(first+second)); } } out.close(); } static class special{ long x1,y1,x2,y2; //int id; special(long x1,long y1,long x2,long y2) { this.x1=x1; this.y1=y1; this.x2=x2; this.y2=y2; //this.id=id; } @Override public int hashCode() { int hash = 7; hash = 31 * hash + (int) x1; hash = 31 * hash + (int)x2; hash = 31 * hash + (int)y1; hash = 31 * hash + (int)y2; return hash; } @Override public boolean equals(Object o){ if (o == this) return true; if (o.getClass() != getClass()) return false; special t = (special)o; return t.x1 == x1 && t.y1 == y1&&t.x2==x2&&t.y2==y2; } } static long binexp(long a,long n) { if(n==0) return 1; long res=binexp(a,n/2); if(n%2==1) return res*res*a; else return res*res; } static long powMod(long base, long exp, long mod) { if (base == 0 || base == 1) return base; if (exp == 0) return 1; if (exp == 1) return (base % mod+mod)%mod; long R = (powMod(base, exp/2, mod) % mod+mod)%mod; R *= R; R %= mod; if ((exp & 1) == 1) { return (base * R % mod+mod)%mod; } else return (R %mod+mod)%mod; } static double dis(double x1,double y1,double x2,double y2) { return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); } static long mod(long x,long y) { if(x<0) x=x+(-x/y+1)*y; return x%y; } public static long pow(long b, long e) { long r = 1; while (e > 0) { if (e % 2 == 1) r = r * b ; b = b * b; e >>= 1; } return r; } private static void sort(long[] arr) { List<Long> list = new ArrayList<>(); for (long object : arr) list.add(object); Collections.sort(list); //Collections.reverse(list); for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i); } private static void sort2(long[] arr) { List<Long> list = new ArrayList<>(); for (Long object : arr) list.add(object); Collections.sort(list); Collections.reverse(list); for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i); } static class FastScanner { private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] nextInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] nextLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] nextDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } } static class Pair implements Comparable<Pair>{ public long x, y,z; public Pair(long x1, long y1,long z1) { x=x1; y=y1; z=z1; } public Pair(long x1, long y1) { x=x1; y=y1; } @Override public int hashCode() { return (int)(x + 31 * y); } public String toString() { return x + " " + y+" "+z; } @Override public boolean equals(Object o){ if (o == this) return true; if (o.getClass() != getClass()) return false; Pair t = (Pair)o; return t.x == x && t.y == y&&t.z==z; } public int compareTo(Pair o) { return (int)(x-o.x); } } }
java
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.*; import java.lang.*; public class Codeforces{ public static void main(String[] args){ Scanner input=new Scanner(System.in); int test=input.nextInt(); while(test-->0) { int n=input.nextInt(); int m=input.nextInt(); int[] ar=new int[n]; int[] br=new int[m]; for(int i=0;i<n;i++) { ar[i]=input.nextInt(); } for(int i=0;i<m;i++) { br[i]=input.nextInt(); } Arrays.sort(br); int val=br[0]; int start=br[0]; int end=br[0]; for(int i=1;i<m;i++) { if(val+1==br[i]) { end=br[i]; val=br[i]; } else { Arrays.sort(ar,start-1,end+1); start=br[i]; end=br[i]; val=br[i]; } } Arrays.sort(ar,start-1,end+1); System.out.println(isSorted(ar,n)?"YES":"NO"); } } public static boolean isSorted(int arr[], int n) { if (n == 0 || n == 1) return true; for (int i = 1; i < n; i++) if (arr[i - 1] > arr[i]) return false; return true; } }
java
1304
C
C. Air Conditionertime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGildong owns a bulgogi restaurant. The restaurant has a lot of customers; so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: titi — the time (in minutes) when the ii-th customer visits the restaurant, lili — the lower bound of their preferred temperature range, and hihi — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the ii-th customer is satisfied if and only if the temperature is between lili and hihi (inclusive) in the titi-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.InputEach test contains one or more test cases. The first line contains the number of test cases qq (1≤q≤5001≤q≤500). Description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1001≤n≤100, −109≤m≤109−109≤m≤109), where nn is the number of reserved customers and mm is the initial temperature of the restaurant.Next, nn lines follow. The ii-th line of them contains three integers titi, lili, and hihi (1≤ti≤1091≤ti≤109, −109≤li≤hi≤109−109≤li≤hi≤109), where titi is the time when the ii-th customer visits, lili is the lower bound of their preferred temperature range, and hihi is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive.The customers are given in non-decreasing order of their visit time, and the current time is 00.OutputFor each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO".You can print each letter in any case (upper or lower).ExampleInputCopy4 3 0 5 1 2 7 3 5 10 -1 0 2 12 5 7 10 10 16 20 3 -100 100 0 0 100 -50 50 200 100 100 1 100 99 -100 0 OutputCopyYES NO YES NO NoteIn the first case; Gildong can control the air conditioner to satisfy all customers in the following way: At 00-th minute, change the state to heating (the temperature is 0). At 22-nd minute, change the state to off (the temperature is 2). At 55-th minute, change the state to heating (the temperature is 2, the 11-st customer is satisfied). At 66-th minute, change the state to off (the temperature is 3). At 77-th minute, change the state to cooling (the temperature is 3, the 22-nd customer is satisfied). At 1010-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at 00-th minute and leave it be. Then all customers will be satisfied. Note that the 11-st customer's visit time equals the 22-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.
[ "dp", "greedy", "implementation", "sortings", "two pointers" ]
import 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_Air_Conditioner { static long mod = Long.MAX_VALUE; public static void main(String[] args) { OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); FastReader f = new FastReader(); int t = f.nextInt(); while(t-- > 0){ solve(f, out); } out.close(); } public static void solve(FastReader f, PrintWriter out) { int n = f.nextInt(); long start = f.nextLong(); ArrayList<Pair> arrli = new ArrayList<>(); for(int i = 0; i < n; i++) { arrli.add(new Pair(f.nextLong(), f.nextLong(), f.nextLong())); } long lastHi = start; long lastLo = start; for(int i = 0; i < arrli.size(); i++) { long delT = (i != 0) ? arrli.get(i).t-arrli.get(i-1).t : arrli.get(i).t; long currHi = lastHi + delT; long currLo = lastLo - delT; if(currLo > arrli.get(i).hi || currHi < arrli.get(i).lo) { out.println("NO"); return; } lastHi = min(currHi, arrli.get(i).hi); lastLo = max(currLo, arrli.get(i).lo); } out.println("YES"); } static class Pair { long t; long lo; long hi; public Pair(long t, long lo, long hi) { this.t = t; this.lo = lo; this.hi = hi; } } // Sort an array public static void sort(int arr[]) { ArrayList<Integer> al = new ArrayList<>(); for(int i: arr) { al.add(i); } Collections.sort(al); for(int i = 0; i < arr.length; i++) { arr[i] = al.get(i); } } // Find all divisors of n public static void allDivisors(int n) { for(int i = 1; i*i <= n; i++) { if(n%i == 0) { System.out.println(i + " "); if(i != n/i) { System.out.println(n/i + " "); } } } } // Check if n is prime or not public static boolean isPrime(int n) { if(n < 1) return false; if(n == 2 || n == 3) return true; if(n % 2 == 0 || n % 3 == 0) return false; for(int i = 5; i*i <= n; i += 6) { if(n % i == 0 || n % (i+2) == 0) { return false; } } return true; } // Find gcd of a and b public static long gcd(long a, long b) { long dividend = a > b ? a : b; long divisor = a < b ? a : b; while(divisor > 0) { long reminder = dividend % divisor; dividend = divisor; divisor = reminder; } return dividend; } // Find lcm of a and b public static long lcm(long a, long b) { long lcm = gcd(a, b); long hcf = (a * b) / lcm; return hcf; } // Find factorial in O(n) time public static long fact(int n) { long res = 1; for(int i = 2; i <= n; i++) { res = res * i; } return res; } // Find power in O(logb) time public static long power(long a, long b) { long res = 1; while(b > 0) { if((b&1) == 1) { res = (res * a)%mod; } a = (a * a)%mod; b >>= 1; } return res; } // Find nCr public static long nCr(int n, int r) { if(r < 0 || r > n) { return 0; } long ans = fact(n) / (fact(r) * fact(n-r)); return ans; } // Find nPr public static long nPr(int n, int r) { if(r < 0 || r > n) { return 0; } long ans = fact(n) / fact(r); return ans; } // sort all characters of a string public static String sortString(String inputString) { char tempArray[] = inputString.toCharArray(); Arrays.sort(tempArray); return new String(tempArray); } // User defined class for fast I/O static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } boolean hasNext() { if (st != null && st.hasMoreTokens()) { return true; } String tmp; try { br.mark(1000); tmp = br.readLine(); if (tmp == null) { return false; } br.reset(); } catch (IOException e) { return false; } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } boolean nextBoolean() { return Boolean.parseBoolean(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextArray(int n) { int[] a = new int[n]; for(int i=0; i<n; i++) { a[i] = nextInt(); } return a; } } } /** Dec Char Dec Char Dec Char Dec Char --------- --------- --------- ---------- 0 NUL (null) 32 SPACE 64 @ 96 ` 1 SOH (start of heading) 33 ! 65 A 97 a 2 STX (start of text) 34 " 66 B 98 b 3 ETX (end of text) 35 # 67 C 99 c 4 EOT (end of transmission) 36 $ 68 D 100 d 5 ENQ (enquiry) 37 % 69 E 101 e 6 ACK (acknowledge) 38 & 70 F 102 f 7 BEL (bell) 39 ' 71 G 103 g 8 BS (backspace) 40 ( 72 H 104 h 9 TAB (horizontal tab) 41 ) 73 I 105 i 10 LF (NL line feed, new line) 42 * 74 J 106 j 11 VT (vertical tab) 43 + 75 K 107 k 12 FF (NP form feed, new page) 44 , 76 L 108 l 13 CR (carriage return) 45 - 77 M 109 m 14 SO (shift out) 46 . 78 N 110 n 15 SI (shift in) 47 / 79 O 111 o 16 DLE (data link escape) 48 0 80 P 112 p 17 DC1 (device control 1) 49 1 81 Q 113 q 18 DC2 (device control 2) 50 2 82 R 114 r 19 DC3 (device control 3) 51 3 83 S 115 s 20 DC4 (device control 4) 52 4 84 T 116 t 21 NAK (negative acknowledge) 53 5 85 U 117 u 22 SYN (synchronous idle) 54 6 86 V 118 v 23 ETB (end of trans. block) 55 7 87 W 119 w 24 CAN (cancel) 56 8 88 X 120 x 25 EM (end of medium) 57 9 89 Y 121 y 26 SUB (substitute) 58 : 90 Z 122 z 27 ESC (escape) 59 ; 91 [ 123 { 28 FS (file separator) 60 < 92 \ 124 | 29 GS (group separator) 61 = 93 ] 125 } 30 RS (record separator) 62 > 94 ^ 126 ~ 31 US (unit separator) 63 ? 95 _ 127 DEL */ // (a/b)%mod == (a * moduloInverse(b)) % mod; // moduloInverse(b) = power(b, mod-2);
java
1313
A
A. Fast Food Restauranttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTired of boring office work; Denis decided to open a fast food restaurant.On the first day he made aa portions of dumplings, bb portions of cranberry juice and cc pancakes with condensed milk.The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes that this visitor will receive. When doing so, Denis is guided by the following rules: every visitor should receive at least one dish (dumplings, cranberry juice, pancakes with condensed milk are all considered to be dishes); each visitor should receive no more than one portion of dumplings, no more than one portion of cranberry juice and no more than one pancake with condensed milk; all visitors should receive different sets of dishes. What is the maximum number of visitors Denis can feed?InputThe first line contains an integer tt (1≤t≤5001≤t≤500) — the number of test cases to solve.Each of the remaining tt lines contains integers aa, bb and cc (0≤a,b,c≤100≤a,b,c≤10) — the number of portions of dumplings, the number of portions of cranberry juice and the number of condensed milk pancakes Denis made.OutputFor each test case print a single integer — the maximum number of visitors Denis can feed.ExampleInputCopy71 2 10 0 09 1 72 2 32 3 23 2 24 4 4OutputCopy3045557NoteIn the first test case of the example, Denis can feed the first visitor with dumplings, give the second a portion of cranberry juice, and give the third visitor a portion of cranberry juice and a pancake with a condensed milk.In the second test case of the example, the restaurant Denis is not very promising: he can serve no customers.In the third test case of the example, Denise can serve four visitors. The first guest will receive a full lunch of dumplings, a portion of cranberry juice and a pancake with condensed milk. The second visitor will get only dumplings. The third guest will receive a pancake with condensed milk, and the fourth guest will receive a pancake and a portion of dumplings. Please note that Denis hasn't used all of the prepared products, but is unable to serve more visitors.
[ "brute force", "greedy", "implementation" ]
import java.util.*; public class FastFood { public static void main(String[] args){ Scanner scanner=new Scanner(System.in); int t=scanner.nextInt(); for(int i = 0; i<t; i++){ int arr[]=new int[3]; arr[0]=scanner.nextInt(); arr[1]=scanner.nextInt(); arr[2]=scanner.nextInt(); Arrays.sort(arr); if(arr[0]>=4){ System.out.println("7"); } else if(arr[0]==3){ System.out.println("6"); } else if(arr[0]==2){ if(arr[1]>=3){ System.out.println("5"); } else{ if(arr[2]>=3){ System.out.println("5"); } else { System.out.println("4"); } } } else if(arr[0]==1){ if(arr[1]==1){ System.out.println("3"); } else{ System.out.println("4"); } } else if(arr[0]==0){ if(arr[1]==1){ System.out.println("2"); } else if(arr[1]==0&&arr[2]>0){ System.out.println("1"); } else if(arr[1]==0&&arr[2]==0){ System.out.println("0"); } else{ System.out.println("3"); } } } } }
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.util.*; import java.io.*; public class E83 { public static void main(String [] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); int [] a = new int [n]; for (int i = 0; i < n; i++) a[i] = sc.nextInt(); int [][] dp = new int [n][n]; for (int len = 1; len <= n; len++) { for (int i = 0; i <= n - len; i++) { int j = i + len - 1; if (len == 1) { dp[i][j] = a[i]; continue; } for (int k = i; k < j; k++) { if (dp[i][k] > 0 && dp[k+1][j] == dp[i][k]) { dp[i][j] = dp[i][k] + 1; } } } } int [] min = new int [n]; Arrays.fill(min, Integer.MAX_VALUE); min[0] = 1; for (int i = 1; i < n; i++) { for (int j = -1; j < i; j++) { int cont = -1; if (j == -1) { cont = 0; } else { cont = min[j]; } if (dp[j+1][i] > 0) { min[i] = Math.min(min[i], 1 + cont); } else { min[i] = Math.min(min[i], cont + i - j); } } } out.println(min[n-1]); out.close(); } //-----------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
A
A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5 2 2 3 4 2 2 8 8 3 3 3 3 4 5 5 5 5 4 1 1 1 1 OutputCopyYES NO YES NO NO
[ "math" ]
import java.util.Scanner; 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]; int c = 0, l = 0; for (int i = 0; i < n; i++) { a[i] = sc.nextInt(); if (a[i] %2 == 0) { c++; } else { l++; } } if (l == 0) { System.out.println("NO"); } else if (c == 0) { if (l %2 == 0) { System.out.println("NO"); } else { System.out.println("YES"); } } else { System.out.println("YES"); } } } }
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.*; import java.util.*; public class Main{ static class ftreeReversed{ int n; long[]ft; ftreeReversed(int z){ ft=new long[z+1]; n=z; } void updatesum(int idx,int k) { while(idx>0) { ft[idx]+=k; idx-=(idx&(-1*idx)); } } int querysum(int idx) { int sum=0; while(idx<=n) { sum+=ft[idx]; idx+=(idx&(-1*idx)); } return sum; } } static class ftree{ int n; long[]ft; ftree(int z){ ft=new long[z+1]; n=z; } void updatesum(int idx,int k) { while(idx<=n) { ft[idx]+=k; idx+=(idx&(-1*idx)); } } int querysum(int idx) { int sum=0; while(idx>0) { sum+=ft[idx]; idx-=(idx&(-1*idx)); } return sum; } } public static void main(String[] args) throws Exception{ MScanner sc=new MScanner(System.in); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt(),m=sc.nextInt(); int[]messages=new int[m+1]; for(int i=1;i<=m;i++)messages[i]=sc.nextInt(); int[]lastOcc=new int[n+1]; Arrays.fill(lastOcc, -1); int[]ansMin=new int[n+1]; int[]ansMax=new int[n+1]; for(int i=1;i<=n;i++) { ansMin[i]=i;ansMax[i]=i; } for(int i=1;i<=m;i++)ansMin[messages[i]]=1; ftreeReversed ftSeen=new ftreeReversed(n+7); ftree ftCount=new ftree(m+7); for(int i=1;i<=m;i++) { if(lastOcc[messages[i]]==-1) { int query=ftSeen.querysum(messages[i]); ansMax[messages[i]]+=query; ftSeen.updatesum(messages[i], 1); ftCount.updatesum(i, 1); lastOcc[messages[i]]=i; } else { ftCount.updatesum(lastOcc[messages[i]], -1); ftCount.updatesum(i, 1); int left=lastOcc[messages[i]]+1; int right=i-1; lastOcc[messages[i]]=i; if(left>right)continue; int cnt=ftCount.querysum(right)-ftCount.querysum(left-1); ansMax[messages[i]]=Math.max(ansMax[messages[i]], cnt+1); } } for(int i=1;i<=n;i++) { if(lastOcc[i]==-1) { int query=ftSeen.querysum(i); ansMax[i]+=query; } else { int left=lastOcc[i]+1; int right=m; if(left>right)continue; int cnt=ftCount.querysum(right)-ftCount.querysum(left-1); ansMax[i]=Math.max(ansMax[i], cnt+1); } } for(int i=1;i<=n;i++) { pw.println(ansMin[i]+" "+ansMax[i]); } 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
1296
B
B. Food Buyingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputMishka wants to buy some food in the nearby shop. Initially; he has ss burles on his card. Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1≤x≤s1≤x≤s, buy food that costs exactly xx burles and obtain ⌊x10⌋⌊x10⌋ burles as a cashback (in other words, Mishka spends xx burles and obtains ⌊x10⌋⌊x10⌋ back). The operation ⌊ab⌋⌊ab⌋ means aa divided by bb rounded down.It is guaranteed that you can always buy some food that costs xx for any possible value of xx.Your task is to say the maximum number of burles Mishka can spend if he buys food optimally.For example, if Mishka has s=19s=19 burles then the maximum number of burles he can spend is 2121. Firstly, he can spend x=10x=10 burles, obtain 11 burle as a cashback. Now he has s=10s=10 burles, so can spend x=10x=10 burles, obtain 11 burle as a cashback and spend it too.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases.The next tt lines describe test cases. Each test case is given on a separate line and consists of one integer ss (1≤s≤1091≤s≤109) — the number of burles Mishka initially has.OutputFor each test case print the answer on it — the maximum number of burles Mishka can spend if he buys food optimally.ExampleInputCopy6 1 10 19 9876 12345 1000000000 OutputCopy1 11 21 10973 13716 1111111111
[ "math" ]
import java.util.Scanner; public class Codeforces_1296B_Food_Buying { 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(), ret = 0; while (n > 0) { if (n < 10) { ret += n; break; } int back = n / 10, cost = back * 10; ret += cost; n -= cost; n += back; } System.out.println(ret); } } }
java
1288
A
A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in ⌈dx+1⌉⌈dx+1⌉ days (⌈a⌉⌈a⌉ is the ceiling function: ⌈2.4⌉=3⌈2.4⌉=3, ⌈2⌉=2⌈2⌉=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+⌈dx+1⌉x+⌈dx+1⌉.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1≤T≤501≤T≤50) — the number of test cases.The next TT lines contain test cases – one per line. Each line contains two integers nn and dd (1≤n≤1091≤n≤109, 1≤d≤1091≤d≤109) — the number of days before the deadline and the number of days the program runs.OutputPrint TT answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3 1 1 4 5 5 11 OutputCopyYES YES NO NoteIn the first test case; Adilbek decides not to optimize the program at all; since d≤nd≤n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run ⌈52⌉=3⌈52⌉=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work ⌈112+1⌉=4⌈112+1⌉=4 days.
[ "binary search", "brute force", "math", "ternary search" ]
import java.util.Scanner; public class problemUnnamed { static Scanner sc= new Scanner(System.in); public static void main(String[] args) { int x=sc.nextInt(); int n; int d; for(int i=0;i<x;i++) { if(testCases()) { System.out.println("YES"); }else { System.out.println("NO"); } } } public static boolean testCases() { int n=sc.nextInt(); int d=sc.nextInt(); if(n>=d) { return true; } return optimize(n,d); } //d is greater than n public static boolean optimize(int n,int d) { for(int i=n;i>0;i--) { if(func(d,i)<=n){ return true; } } return false; } public static int func(int d, int i) { double x =i+(double)d/(i+1); int y=i+d/(i+1); if(x>y) { return y+1; } return y; } }
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.*; import java.lang.reflect.Array; import java.util.*; import static java.lang.Math.*; import static java.lang.Math.pow; public class Main { void run() throws IOException { int n = nextInt(); int[][] otr = new int[n][4]; touple[] event = new touple[n * 2]; for (int i = 0; i < 2 * n; i += 2) { for (int j = 0; j < 4; j++) { otr[i / 2][j] = nextInt(); } event[i] = new touple(otr[i / 2][0], 0, i / 2); event[i + 1] = new touple(otr[i / 2][1], 1, i / 2); } Arrays.sort(event); int[] cnt_for_a = new int[n]; int ended = 0; int not_started = n; Arrays.fill(cnt_for_a, n - 1); for (int i = 0; i < event.length; i++) { int num = event[i].num; if (event[i].type == 0) { cnt_for_a[num] -= ended; not_started--; } else { cnt_for_a[num] -= not_started; ended++; } } event = new touple[n * 2]; for (int i = 0; i < 2 * n; i += 2) { event[i] = new touple(otr[i / 2][2], 0, i / 2); event[i + 1] = new touple(otr[i / 2][3], 1, i / 2); } Arrays.sort(event); int[] cnt_for_b = new int[n]; ended = 0; not_started = n; Arrays.fill(cnt_for_b, n - 1); for (int i = 0; i < event.length; i++) { int num = event[i].num; if (event[i].type == 0) { cnt_for_b[num] -= ended; not_started--; } else { cnt_for_b[num] -= not_started; ended++; } } for (int i = 0; i < cnt_for_a.length; i++) { if(cnt_for_a[i] != cnt_for_b[i]){ pw.println("NO"); pw.close(); return; } } pw.println("YES"); pw.close(); } class touple implements Comparable<touple> { int x, type, num; public touple(int x, int type, int num) { this.x = x; this.type = type; this.num = num; } @Override public int compareTo(touple o) { if (o.x == this.x) return -Integer.compare(o.type, this.type); return -Integer.compare(o.x, this.x); } } class point implements Comparable<point> { int x, num; public point(int a, int b) { x = a; num = b; } @Override public int compareTo(point o) { return -Long.compare(o.x, this.x); } } long mod = (long) 1e9 + 7; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //BufferedReader br = new BufferedReader(new FileReader("cond.in")); StringTokenizer st = new StringTokenizer(""); PrintWriter pw = new PrintWriter(System.out); //PrintWriter pw = new PrintWriter("cond.out"); int nextInt() throws IOException { return Integer.parseInt(next()); } String next() throws IOException { if (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } public Main() throws FileNotFoundException { } public static void main(String[] args) throws IOException { new Main().run(); } }
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 Ex3 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int q = in.nextInt(); for (int t = 0; t < q; t++) { int x = in.nextInt(); HashSet<Integer> set = new HashSet<>(); for(int i = 0; i < x; i++){ set.add(in.nextInt()); } System.out.println(set.size()); } } public class ListNode<E> { private E value; private Ex3.ListNode next; public ListNode(E newVal, Ex3.ListNode<E> newNext) { this.value = newVal; this.next = newNext; } public E getValue() { return this.value; } public Ex3.ListNode<E> getNext() { return this.next; } public void setValue(E newValue) { this.value = newValue; } public void setNext(Ex3.ListNode<E> newNext) { this.next = newNext; } } }
java
1292
A
A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1,1)(1,1) to the gate at (2,n)(2,n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only qq such moments: the ii-th moment toggles the state of cell (ri,ci)(ri,ci) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the qq moments, whether it is still possible to move from cell (1,1)(1,1) to cell (2,n)(2,n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers nn, qq (2≤n≤1052≤n≤105, 1≤q≤1051≤q≤105).The ii-th of qq following lines contains two integers riri, cici (1≤ri≤21≤ri≤2, 1≤ci≤n1≤ci≤n), denoting the coordinates of the cell to be flipped at the ii-th moment.It is guaranteed that cells (1,1)(1,1) and (2,n)(2,n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1,1)(1,1) to cell (2,n)(2,n), print "Yes", otherwise print "No". There should be exactly qq answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInputCopy5 5 2 3 1 4 2 4 2 3 1 4 OutputCopyYes No No No Yes NoteWe'll crack down the example test here: After the first query; the girl still able to reach the goal. One of the shortest path ways should be: (1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5)(1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5). After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1,3)(1,3). After the fourth query, the (2,3)(2,3) is not blocked, but now all the 44-th column is blocked, so she still can't reach the goal. After the fifth query, the column barrier has been lifted, thus she can go to the final goal again.
[ "data structures", "dsu", "implementation" ]
import java.util.*; import java.io.*; public class Practice { static boolean multipleTC = false; FastReader in; PrintWriter out; static int mod = (int) (1e9 + 7); static int mod2 = 998244353; int parent[]; int rank[]; ArrayList<Integer> primes; boolean sieve[]; int pf[]; int MAX = 1000005; int dirX[] = { 1, -1, 0, 0 }; int dirY[] = { 0, 0, -1, 1 }; public static void main(String[] args) throws Exception { new Practice().run(); } void run() throws Exception { in = new FastReader(); out = new PrintWriter(System.out); int T = (multipleTC) ? ni() : 1; pre(); for (int t = 1; t <= T; t++) solve(t); out.flush(); out.close(); } void pre() throws Exception { } // declare all variables fucking long even array indices. // if you are copying some code make sure you done all necessary modifications // that's leads WA. // Divide by Zero Exception Ruin Your Life. // Number Format Exception : Make sure you read constraint carefully. // Always use TreeMap instead of HashMap. // Always write comparators using wrapper classes; void solve(int TC) throws Exception { int n = ni(), q = ni(); boolean block[][] = new boolean[2][n]; int blockages = 0; for (int i = 0; i < q; i++) { int r = ni() - 1, c = ni() - 1; block[r][c] = !block[r][c]; boolean isOk = true; int count = 0; for (int rr = r - 1; rr <= r + 1; rr++) { for (int cc = c - 1; cc <= c + 1; cc++) { if (c == cc && r == rr) continue; if (r == rr || rr < 0 || rr >= 2 || cc < 0 || cc >= n) continue; if (block[rr][cc]) count++; } } if (block[r][c]) { blockages += count; } else { blockages -= count; } if (blockages == 0) { pn("YES"); } else { pn("NO"); } } } int[] readArr(int n) throws Exception { int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = ni(); } return arr; } void sort(int arr[]) { ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < arr.length; i++) list.add(arr[i]); Collections.sort(list); for (int i = 0; i < arr.length; i++) arr[i] = list.get(i); } public long max(long... arr) { long max = arr[0]; for (long itr : arr) max = Math.max(max, itr); return max; } public int max(int... arr) { int max = arr[0]; for (int itr : arr) max = Math.max(max, itr); return max; } public long min(long... arr) { long min = arr[0]; for (long itr : arr) min = Math.min(min, itr); return min; } public int min(int... arr) { int min = arr[0]; for (int itr : arr) min = Math.min(min, itr); return min; } public long sum(long... arr) { long sum = 0; for (long itr : arr) sum += itr; return sum; } public long sum(int... arr) { long sum = 0; for (int itr : arr) sum += itr; return sum; } public StringBuilder printArr(int arr[]) { StringBuilder sb = new StringBuilder(); int n = arr.length; for (int i = 0; i < n; i++) { sb.append(arr[i] + " "); } return sb; } static int bitCount(int x) { return x == 0 ? 0 : (1 + bitCount(x & (x - 1))); } static void dbg(Object... o) { System.err.println(Arrays.deepToString(o)); } int bit(long n) { return (n == 0) ? 0 : (1 + bit(n & (n - 1))); } int abs(int a) { return (a < 0) ? -a : a; } long abs(long a) { return (a < 0) ? -a : a; } void p(Object o) { out.print(o); } void pn(Object o) { out.println(o); } void pni(Object o) { out.println(o); out.flush(); } String n() throws Exception { return in.next(); } String nln() throws Exception { return in.nextLine(); } int ni() throws Exception { return Integer.parseInt(in.next()); } long nl() throws Exception { return Long.parseLong(in.next()); } double nd() throws Exception { return Double.parseDouble(in.next()); } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception { br = new BufferedReader(new FileReader(s)); } String next() throws Exception { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new Exception(e.toString()); } } return st.nextToken(); } String nextLine() throws Exception { String str = ""; try { str = br.readLine(); } catch (IOException e) { throw new Exception(e.toString()); } return str; } } }
java
1287
A
A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": "A" corresponds to an angry student "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt — the number of groups of students (1≤t≤1001≤t≤100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1≤ki≤1001≤ki≤100) — the number of students in the group, followed by a string sisi, consisting of kiki letters "A" and "P", which describes the ii-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInputCopy1 4 PPAP OutputCopy1 InputCopy3 12 APPAPPPAPPPP 3 AAP 3 PPA OutputCopy4 1 0 NoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after 11 minute — AAPAAPPAAPPP after 22 minutes — AAAAAAPAAAPP after 33 minutes — AAAAAAAAAAAP after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry.
[ "greedy", "implementation" ]
import java.util.*; import java.lang.*; import java.io.*; 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(); String s =sc.next(); char[] a = s.toCharArray(); int ans=0; while(true){ int c=0; for(int i=0;i<n-1;i++){ if(a[i]=='A'&& a[i+1]=='P'){ c++; a[i+1]='A'; i++; } } if(c==0) break; else ans++; } System.out.println(ans); } } }
java
1320
A
A. Journey Planningtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTanya wants to go on a journey across the cities of Berland. There are nn cities situated along the main railroad line of Berland, and these cities are numbered from 11 to nn. Tanya plans her journey as follows. First of all, she will choose some city c1c1 to start her journey. She will visit it, and after that go to some other city c2>c1c2>c1, then to some other city c3>c2c3>c2, and so on, until she chooses to end her journey in some city ck>ck−1ck>ck−1. So, the sequence of visited cities [c1,c2,…,ck][c1,c2,…,ck] should be strictly increasing.There are some additional constraints on the sequence of cities Tanya visits. Each city ii has a beauty value bibi associated with it. If there is only one city in Tanya's journey, these beauty values imply no additional constraints. But if there are multiple cities in the sequence, then for any pair of adjacent cities cici and ci+1ci+1, the condition ci+1−ci=bci+1−bcici+1−ci=bci+1−bci must hold.For example, if n=8n=8 and b=[3,4,4,6,6,7,8,9]b=[3,4,4,6,6,7,8,9], there are several three possible ways to plan a journey: c=[1,2,4]c=[1,2,4]; c=[3,5,6,8]c=[3,5,6,8]; c=[7]c=[7] (a journey consisting of one city is also valid). There are some additional ways to plan a journey that are not listed above.Tanya wants her journey to be as beautiful as possible. The beauty value of the whole journey is the sum of beauty values over all visited cities. Can you help her to choose the optimal plan, that is, to maximize the beauty value of the journey?InputThe first line contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the number of cities in Berland.The second line contains nn integers b1b1, b2b2, ..., bnbn (1≤bi≤4⋅1051≤bi≤4⋅105), where bibi is the beauty value of the ii-th city.OutputPrint one integer — the maximum beauty of a journey Tanya can choose.ExamplesInputCopy6 10 7 1 9 10 15 OutputCopy26 InputCopy1 400000 OutputCopy400000 InputCopy7 8 9 26 11 12 29 14 OutputCopy55 NoteThe optimal journey plan in the first example is c=[2,4,5]c=[2,4,5].The optimal journey plan in the second example is c=[1]c=[1].The optimal journey plan in the third example is c=[3,6]c=[3,6].
[ "data structures", "dp", "greedy", "math", "sortings" ]
import java.util.HashMap; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Scanner; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.io.IOException; public class journey { public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); int n = in.nextInt(); BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out)); int[] a = new int[n]; HashMap<Integer,Long> h = new HashMap<>(); int max = 0; for(int i = 0; i<n; i++) { a[i] = in.nextInt(); max = Math.max(a[i], max); } long ans = max; for(int i = 0; i<n; i++) { int x = a[i]-i; h.put(x, h.getOrDefault(x,0L)+a[i]); ans = Math.max(ans,h.get(x)); } log.write(ans+"\n"); log.flush(); } }
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; 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 orig = 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, orig, 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 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 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[] orig, 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++; orig[order[h]] = h; 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
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.io.PrintWriter; import java.util.StringTokenizer; public class ProductOfThreeNumbersAgain { public static void main(String[] args) { // TODO Auto-generated method stub FastScanner fs = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); int T = fs.nextInt(); while (T-- > 0) { int N = fs.nextInt(); int a = -1, b = -1; boolean ok = false; for (int i = 2; i * i <= N; i++) { if (N%i == 0) { if (a == -1) { a = i; N /= a; } else { b = i; N /= b; if (N > b) { pw.println("YES"); pw.println(a + " " + b + " " + N); ok = true; break; } else { break; } } } } if (!ok) { pw.println("NO"); } } pw.close(); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } long[] readArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
java
1294
B
B. Collecting Packagestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot in a warehouse and nn packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0,0)(0,0). The ii-th package is at the point (xi,yi)(xi,yi). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The robot is semi-broken and only can move up ('U') and right ('R'). In other words, in one move the robot can go from the point (x,y)(x,y) to the point (x+1,yx+1,y) or to the point (x,y+1)(x,y+1).As we say above, the robot wants to collect all nn packages (in arbitrary order). He wants to do it with the minimum possible number of moves. If there are several possible traversals, the robot wants to choose the lexicographically smallest path.The string ss of length nn is lexicographically less than the string tt of length nn if there is some index 1≤j≤n1≤j≤n that for all ii from 11 to j−1j−1 si=tisi=ti and sj<tjsj<tj. It is the standard comparison of string, like in a dictionary. Most programming languages compare strings in this way.InputThe first line of the input contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases. Then test cases follow.The first line of a test case contains one integer nn (1≤n≤10001≤n≤1000) — the number of packages.The next nn lines contain descriptions of packages. The ii-th package is given as two integers xixi and yiyi (0≤xi,yi≤10000≤xi,yi≤1000) — the xx-coordinate of the package and the yy-coordinate of the package.It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point (0,0)(0,0) doesn't contain a package.The sum of all values nn over test cases in the test doesn't exceed 10001000.OutputPrint the answer for each test case.If it is impossible to collect all nn packages in some order starting from (0,00,0), print "NO" on the first line.Otherwise, print "YES" in the first line. Then print the shortest path — a string consisting of characters 'R' and 'U'. Among all such paths choose the lexicographically smallest path.Note that in this problem "YES" and "NO" can be only uppercase words, i.e. "Yes", "no" and "YeS" are not acceptable.ExampleInputCopy3 5 1 3 1 2 3 3 5 5 4 3 2 1 0 0 1 1 4 3 OutputCopyYES RUUURRRRUU NO YES RRRRUUU NoteFor the first test case in the example the optimal path RUUURRRRUU is shown below:
[ "implementation", "sortings" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class CollectingPackages { public static void main(String[] args) throws IOException { BufferedReader r = new BufferedReader(new InputStreamReader(System.in)); var st = new StringTokenizer(r.readLine()); var t = Integer.parseInt(st.nextToken()); for (int i = 0; i < t; i++) { st = new StringTokenizer(r.readLine()); var n = Integer.parseInt(st.nextToken()); var points = new Point[n]; for (int j = 0; j < n; j++) { st = new StringTokenizer(r.readLine()); points[j] = new Point(Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken())); } Arrays.sort(points); var prevX = 0; var prevY = 0; var str = new StringBuilder(); var check = true; for (Point p : points) { if(p.y<prevY) { check = false; break; } str.append("R".repeat(Math.max(0, p.x - prevX))); str.append("U".repeat(Math.max(0, p.y - prevY))); prevY = p.y; prevX = p.x; } if (check) { System.out.println("YES\n"+str); } else { System.out.println("NO"); } } } static class Point implements Comparable<Point> { int x; int y; public Point(int x,int y) { this.x = x; this.y = y; } public int compareTo(Point p) { if (p.x!=this.x) { return Integer.compare(this.x,p.x); } else { return Integer.compare(this.y,p.y); } } } }
java
1320
C
C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1≤n,m,p≤2⋅1051≤n,m,p≤2⋅105) — the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1≤ai≤1061≤ai≤106, 1≤cai≤1091≤cai≤109) — the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1≤bj≤1061≤bj≤106, 1≤cbj≤1091≤cbj≤109) — the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1≤xk,yk≤1061≤xk,yk≤106, 1≤zk≤1031≤zk≤103) — defense, attack and the number of coins of the monster kk.OutputPrint a single integer — the maximum profit of the grind.ExampleInputCopy2 3 3 2 3 4 7 2 4 3 2 5 11 1 2 4 2 1 6 3 4 6 OutputCopy1
[ "brute force", "data structures", "sortings" ]
import java.io.BufferedOutputStream; import java.io.Closeable; import java.io.DataInputStream; import java.io.Flushable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; import java.util.Comparator; import java.util.InputMismatchException; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); Output out = new Output(outputStream); CWorldOfDarkraftBattleForAzathoth solver = new CWorldOfDarkraftBattleForAzathoth(); solver.solve(1, in, out); out.close(); } } public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1<<28); thread.start(); thread.join(); } static class CWorldOfDarkraftBattleForAzathoth { private final int iinf = 1_000_000_000; private final long linf = 4_000_000_000_000_000_000L; public CWorldOfDarkraftBattleForAzathoth() { } public void solve(int kase, InputReader in, Output pw) { int n = in.nextInt(), m = in.nextInt(), p = in.nextInt(), mn = (int) 1e6; SegmentTree st = new SegmentTree(mn+1); int[][] arr = in.nextInt(n, 2); { int[][] tmp = in.nextInt(m, 2); Arrays.sort(tmp, Comparator.comparingInt(o -> -o[0])); int min = iinf; st.add(tmp[0][0], mn, -linf); for(int i = 0; i<m; i++) { st.add(i==m-1 ? 0 : tmp[i+1][0], tmp[i][0]-1, -(min = Math.min(min, tmp[i][1]))); } } Arrays.sort(arr, Comparator.comparingInt(o -> o[0])); int[][] mon = in.nextInt(p, 3); Arrays.sort(mon, Comparator.comparingInt(o -> o[0])); long ans = -linf; int j = 0; for(int i = 0; i<n; i++) { while(j<p&&mon[j][0]<arr[i][0]) { st.add(mon[j][1], mn, mon[j++][2]); } ans = Math.max(ans, st.max(0, mn)-arr[i][1]); } pw.println(ans); } } static class Output implements Closeable, Flushable { public StringBuilder sb; public OutputStream os; public int BUFFER_SIZE; public String lineSeparator; public Output(OutputStream os) { this(os, 1<<16); } public Output(OutputStream os, int bs) { BUFFER_SIZE = bs; sb = new StringBuilder(BUFFER_SIZE); this.os = new BufferedOutputStream(os, 1<<17); lineSeparator = System.lineSeparator(); } public void println(long l) { println(String.valueOf(l)); } public void println(String s) { sb.append(s); println(); } public void println() { sb.append(lineSeparator); } private void flushToBuffer() { try { os.write(sb.toString().getBytes()); }catch(IOException e) { e.printStackTrace(); } sb = new StringBuilder(BUFFER_SIZE); } public void flush() { try { flushToBuffer(); os.flush(); }catch(IOException e) { e.printStackTrace(); } } public void close() { flush(); try { os.close(); }catch(IOException e) { e.printStackTrace(); } } } static class FastReader implements InputReader { final private int BUFFER_SIZE = 1<<16; private DataInputStream din; private byte[] buffer; private int bufferPointer; private int bytesRead; public FastReader(InputStream is) { din = new DataInputStream(is); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public int nextInt() { int ret = 0; byte c = skipToDigit(); boolean neg = (c=='-'); if(neg) { c = read(); } do { ret = ret*10+c-'0'; } while((c = read())>='0'&&c<='9'); if(neg) { return -ret; } return ret; } private boolean isDigit(byte b) { return b>='0'&&b<='9'; } private byte skipToDigit() { byte ret; while(!isDigit(ret = read())&&ret!='-') ; return ret; } private void fillBuffer() { try { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); }catch(IOException e) { e.printStackTrace(); throw new InputMismatchException(); } if(bytesRead==-1) { buffer[0] = -1; } } private byte read() { if(bytesRead==-1) { throw new InputMismatchException(); }else if(bufferPointer==bytesRead) { fillBuffer(); } return buffer[bufferPointer++]; } } static interface InputReader { int nextInt(); default int[] nextInt(int n) { int[] ret = new int[n]; for(int i = 0; i<n; i++) { ret[i] = nextInt(); } return ret; } default int[][] nextInt(int n, int m) { int[][] ret = new int[n][m]; for(int i = 0; i<n; i++) { ret[i] = nextInt(m); } return ret; } } static class SegmentTree { public long[] arr; public long[] sumv; public long[] minv; public long[] maxv; public long[] addv; public long[] setv; public long _sum; public long _min; public long _max; public long y1; public long y2; public long v; public int n; public boolean[] setc; public boolean add; public SegmentTree(int n) { arr = new long[n]; this.n = n; sumv = new long[n<<2]; minv = new long[n<<2]; maxv = new long[n<<2]; addv = new long[n<<2]; setv = new long[n<<2]; setc = new boolean[n<<2]; build0(1, 0, n-1); } public SegmentTree(long[] arr) { this.arr = arr.clone(); n = arr.length; sumv = new long[n<<2]; minv = new long[n<<2]; maxv = new long[n<<2]; addv = new long[n<<2]; setv = new long[n<<2]; setc = new boolean[n<<2]; build(1, 0, n-1); } private void build0(int o, int l, int r) { if(l==r) { setc[o] = true; }else { int m = l+r >> 1; build(o<<1, l, m); build(o<<1|1, m+1, r); } } private void build(int o, int l, int r) { if(l==r) { setc[o] = true; setv[o] = arr[l]; }else { int m = l+r >> 1; build(o<<1, l, m); build(o<<1|1, m+1, r); } maintain(o, l, r); } public void query(int o, int l, int r, long add) { if(setc[o]) { long v = setv[o]+add+addv[o]; _sum += v*(Math.min(r, y2)-Math.max(l, y1)+1); _min = Math.min(_min, v); _max = Math.max(_max, v); }else if(y1<=l&&y2>=r) { _sum += sumv[o]+add*(r-l+1); _min = Math.min(_min, minv[o]+add); _max = Math.max(_max, maxv[o]+add); }else { int m = (l+r) >> 1; if(y1<=m) { query(o<<1, l, m, add+addv[o]); } if(y2>m) { query(o<<1|1, m+1, r, add+addv[o]); } } } public void update(int o, int l, int r) { int lc = o<<1, rc = o<<1|1; if(y1<=l&&y2>=r) { if(add) { addv[o] += v; }else { setv[o] = v; setc[o] = true; addv[o] = 0; } }else { pushdown(o); int m = (l+r) >> 1; if(y1<=m) { update(lc, l, m); }else { maintain(lc, l, m); } if(y2>m) { update(rc, m+1, r); }else { maintain(rc, m+1, r); } } maintain(o, l, r); } private void maintain(int o, int l, int r) { int lc = o<<1, rc = o<<1|1; if(r>l) { sumv[o] = sumv[lc]+sumv[rc]; minv[o] = Math.min(minv[lc], minv[rc]); maxv[o] = Math.max(maxv[lc], maxv[rc]); } if(setc[o]) { minv[o] = maxv[o] = setv[o]; sumv[o] = setv[o]*(r-l+1); } if(addv[o]!=0) { minv[o] += addv[o]; maxv[o] += addv[o]; sumv[o] += addv[o]*(r-l+1); } } private void pushdown(int o) { int lc = o<<1, rc = o<<1|1; if(setc[o]) { setv[lc] = setv[rc] = setv[o]; addv[lc] = addv[rc] = 0; setc[o] = false; setc[lc] = setc[rc] = true; } if(addv[o]!=0) { addv[lc] += addv[o]; addv[rc] += addv[o]; addv[o] = 0; } } public void add(int l, int r, long v) { y1 = l; y2 = r; this.v = v; add = true; update(1, 0, n-1); } public void query(int l, int r) { y1 = l; y2 = r; _sum = 0; _max = Long.MIN_VALUE; _min = Long.MAX_VALUE; query(1, 0, n-1, 0); } public long max(int l, int r) { query(l, r); return _max; } } }
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; /** * * @author Acer */ public class CowAndHybales { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while(T-- > 0){ int n = sc.nextInt(); int d = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } int x = arr[0]; int j = 0; for (int i = 1; i < n; i++) { int y = arr[i]; for (int k = y; k > 0; k--) { d-=(j+1); if(d < 0){ break; } x+=1; y--; } j++; } System.out.println(x); } } }
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" ]
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.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); E1TreesAndQueries solver = new E1TreesAndQueries(); solver.solve(1, in, out); out.close(); } static class E1TreesAndQueries { int[][] par; int n; int m; ArrayList<Integer>[] g; int[] dist; boolean[] vis; public void solve(int testNumber, InputReader in, OutputWriter out) { pre(in); par = new int[n + 1][20]; dfs(1, 0, 0); int q = in.nextInt(); while (q-- > 0) { int x = in.nextInt(), y = in.nextInt(), a = in.nextInt(), b = in.nextInt(), k = in.nextInt(); int l1 = lca(a, b); int d1 = dist[a] + dist[b] - 2 * dist[l1]; if (d1 == k || (k > d1 && (k - d1) % 2 == 0)) { out.println("YES"); continue; } int xda = dist[x] + dist[a] - 2 * dist[lca(x, a)], yda = dist[y] + dist[a] - 2 * dist[lca(y, a)]; int xdb = dist[x] + dist[b] - 2 * dist[lca(x, b)], ydb = dist[y] + dist[b] - 2 * dist[lca(y, b)]; // int xdy= dist[x]+dist[y]-2*dist[lca(x,y)]; int d2 = xda + 1 + ydb, d3 = yda + 1 + xdb; if (d2 == k || d3 == k || (k > d2 && (k - d2) % 2 == 0) || (k > d3 && (k - d3) % 2 == 0)) { out.println("YES"); } else { out.println("NO"); } } } void dfs(int nn, int pp, int d) { dist[nn] = d; par[nn][0] = pp; for (int i = 1; i <= 19; i++) { par[nn][i] = par[par[nn][i - 1]][i - 1]; } for (int a : g[nn]) { if (a == pp) continue; dfs(a, nn, d + 1); } } int lca(int u, int v) { if (dist[u] < dist[v]) { u ^= v; v ^= u; u ^= v; } int d = dist[u] - dist[v]; for (int i = 19; i >= 0; i--) { if (((1 << i) & d) != 0) { u = par[u][i]; } } if (u == v) return u; for (int i = 19; i >= 0; i--) { if (par[u][i] != par[v][i]) { u = par[u][i]; v = par[v][i]; } } return par[u][0]; } void pre(InputReader in) { n = in.nextInt(); m = n - 1; g = new ArrayList[n + 1]; dist = new int[n + 1]; vis = new boolean[n + 1]; for (int i = 0; i <= n; i++) g[i] = new ArrayList<>(); for (int i = 0; i < m; i++) { int a = in.nextInt(), b = in.nextInt(); g[a].add(b); g[b].add(a); } } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
java
1305
C
C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10 8 5 OutputCopy3InputCopy3 12 1 4 5 OutputCopy0InputCopy3 7 1 4 9 OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7.
[ "brute force", "combinatorics", "math", "number theory" ]
import java.util.*; public class Codeforces { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // int t = sc.nextInt(); // // while (t-- > 0) { // int n = sc.nextInt(); // int[] arr = new int[n]; // for(int i = 0 ; i < n ; i++) { // arr[i] = sc.nextInt(); // } // // } long n = sc.nextLong(); long m = sc.nextLong(); long[] arr = new long[(int)n]; for(int i = 0 ; i < n ; i++) { arr[i] = sc.nextLong(); } long res = 1; if(n<=m) { for(int i = 0 ; i < arr.length ; i++) { for(int j = i+1 ; j<arr.length ; j++) { res = (res%m *(Math.abs(arr[i]-arr[j])%m))%m; } } } else res = 0; System.out.println(res%m); } public static int lower_bound(List<Integer> l , int x) { int start = 0; int end = l.size()-1; int ans = Integer.MAX_VALUE; while(start<=end) { int mid = start + (end-start)/2; if(l.get(mid)==x) return l.get(mid); else if(l.get(mid)>x) { ans = Math.min(ans, l.get(mid)); end = mid -1; } else start = mid + 1; } return ans==Integer.MAX_VALUE ? -1 : ans; } }
java
1284
A
A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12 sin im gye gap eul byeong jeong mu gi gyeong yu sul hae ja chuk in myo jin sa o mi sin 14 1 2 3 4 10 11 12 13 73 2016 2017 2018 2019 2020 OutputCopysinyu imsul gyehae gapja gyeongo sinmi imsin gyeyu gyeyu byeongsin jeongyu musul gihae gyeongja NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.
[ "implementation", "strings" ]
/* _oo0oo_ o8888888o 88" . "88 (| -_- |) 0\ = /0 ___/`---'\___ .' \\| |// '. / \\||| : |||// \ / _||||| -:- |||||- \ | | \\\ - /// | | | \_| ''\---/'' |_/ | \ .-\__ '-' ___/-. / ___'. .' /--.--\ `. .'___ ."" '< `.___\_<|>_/___.' >' "". | | : `- \`.;`\ _ /`;.`/ - ` : | | \ \ `_. \_ __\ /__ _/ .-` / / =====`-.____`.___ \_____/___.-`___.-'===== `=---=' */ import java.util.*; import java.math.*; import java.io.*; import java.lang.Math.*; public class KickStart2020 { 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()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long lcm(long a, long b) { return a / gcd(a, b) * b; } public static class Pair implements Comparable<Pair> { public int index; public int value; public Pair(int index,int value) { this.index = index; this.value = value; } @Override public int compareTo(Pair other) { // multiplied to -3 as the author need descending sort order if(other.index < this.index) return -1; if(other.index > this.index) return 1; else return 0; } @Override public String toString() { return this.index + " " + this.value; } } static boolean isPrime(long d) { if (d == 3) return false; for (int i = 2; i <= (long) Math.sqrt(d); i++) { if (d % i == 0) return false; } return true; } static void decimalTob(int n, int k, Stack<Integer> ss) { int x = n % k; int y = n / k; ss.push(x); if(y > 0) { decimalTob(y, k, ss); } } static long powermod(long x, long y, long mod) { long ans = 1; x = x % mod; if (x == 0) return 0; int i = 1; while (y > 0) { if ((y & 1) != 0) ans = (ans * x) % mod; y = y >> 1; x = (x * x) % mod; } return ans; } static long power(long x, long y) { long res = 1; while (y > 0) { if ((y & 1) != 0) res = res * x; y = y >> 1; x = x * x; } return res; }static void dfsdd(int node, int count, ArrayList<ArrayList<Integer>> ss, boolean visited[], PriorityQueue<Pair> queue) { visited[node] = true; queue.add(new Pair(count, node)); for(int e: ss.get(node)) { if(!visited[e]) { dfsdd(e, count + 1, ss, visited, queue); } } } static void dfs(int node, long count, ArrayList<ArrayList<Integer>> ss , int brr[], long ans[], boolean visited[]) { visited[node] = true; count += brr[node]; for(int e: ss.get(node)) { if(!visited[e]) { dfs(e, count, ss, brr, ans, visited); } } if(brr[node] == 0) ans[0] += count; } public static void main(String[] args) throws Exception { FastReader sc = new FastReader(); PrintWriter out = new PrintWriter(System.out); int t = 1; outerloop: while(t-- > 0) { int n = sc.nextInt(); int m = sc.nextInt(); String arr[] = new String[n]; String brr[] = new String[m]; for(int i = 0; i < n; i++) arr[i] = sc.next(); for(int i = 0; i < m; i++) brr[i] = sc.next(); String crr[] = new String[(int)lcm(n, m)]; int j = 0; int i = 0; int k = 0; int z = (int)lcm(n, m); while(k < z) { crr[k++] = arr[i++] + brr[j++]; if(i >= n) { i = 0; } if(j >= m) j = 0; } int q = sc.nextInt(); while(q-- > 0) { int a = sc.nextInt(); if(a % z == 0) a = z - 1; else a = a%z - 1; out.println(crr[a]); } } out.close(); } }
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.math.*; import java.util.*; public class Main { static final int INF = 0x3f3f3f3f; static final long LNF = 0x3f3f3f3f3f3f3f3fL; public static void main(String[] args) throws IOException { initReader(); int t=nextInt(); while (t--!=0){ int n=nextInt(); int k=nextInt(); long[]a=new long[n+1]; for(int i=1;i<=n;i++){ a[i]=nextLong(); } int[]K=new int[101]; boolean ans=true; for(int i=1;i<=n;i++) { long p = a[i]; if (a[i] == 0) continue; ArrayList<Integer> arr = new ArrayList<>(); for (int j = 100; j >= 0; j--) { if (K[j] == 1) continue; if ((long)Math.pow(k, j) <= p) { p-= (long) Math.pow(k, j); arr.add(j); } } if (p == 0) { for (int j = 0; j < arr.size(); j++) { K[arr.get(j)] = 1; } } else { ans = false; break; } } if(ans)pw.println("YES"); else pw.println("NO"); } pw.close(); } /***************************************************************************************/ static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter pw; public static void initReader() throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = new StringTokenizer(""); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); // 从文件读写 // reader = new BufferedReader(new FileReader("test.in")); // tokenizer = new StringTokenizer(""); // pw = new PrintWriter(new BufferedWriter(new FileWriter("test1.out"))); } public static boolean hasNext() { try { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } } catch (Exception e) { return false; } return true; } public static String next() throws IOException { while (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } public static String nextLine() { try { return reader.readLine(); } catch (Exception e) { return null; } } public static int nextInt() throws IOException { return Integer.parseInt(next()); } public static long nextLong() throws IOException { return Long.parseLong(next()); } public static double nextDouble() throws IOException { return Double.parseDouble(next()); } public static char nextChar() throws IOException { return next().charAt(0); } }
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" ]
//<———My cp———— //https://takeuforward.org/interview-experience/strivers-cp-sheet/?utm_source=youtube&utm_medium=striver&utm_campaign=yt_video import java.util.*; import java.io.*; public class Solution{ static PrintWriter pw = new PrintWriter(System.out); static FastReader fr = new FastReader(System.in); private static long MOD = 1_000_000_007; public static void main(String[] args) throws Exception{ int t = fr.nextInt(); while(t-->0){ String a = fr.next(); String b = fr.next(); String c = fr.next(); boolean p = true; for(int i = 0;i<a.length();i++){ if(a.charAt(i)==b.charAt(i)&&b.charAt(i)==c.charAt(i)){ }else if(a.charAt(i)!=b.charAt(i)&&(a.charAt(i)==c.charAt(i)||b.charAt(i)==c.charAt(i))){ }else{ p=false; } } if(p){ pw.println("YES"); }else{ pw.println("NO"); } } pw.close(); } public static boolean poss(int[][] mat,int r,int c,int n){ if(r<0||c<0||r>=n||c>=n||mat[r][c]!=0){ return false; } return true; } static class Pair{ int min; int max; public Pair(int min,int max){ this.min = min; this.max = max; } @Override public String toString() { return "min: "+min+" max: "+max; } } public static long opNeeded(long c,long[] vals){ long tempResult = 0; for(int j = 0;j<vals.length;j++){ tempResult=tempResult+Math.abs((long)(vals[j]-Math.pow(c,j))); } if(tempResult<0){ tempResult=Long.MAX_VALUE; } return tempResult; } static int isPerfectSquare(int vals){ int lastPow=1; while(lastPow*lastPow<vals){ lastPow++; } if(lastPow*lastPow==vals){ return lastPow*lastPow; }else{ return -1; } } public static int[] sort(int[] vals){ ArrayList<Integer> values = new ArrayList<>(); for(int i = 0;i<vals.length;i++){ values.add(vals[i]); } Collections.sort(values); for(int i =0;i<values.size();i++){ vals[i] = values.get(i); } return vals; } public static long[] sort(long[] vals){ ArrayList<Long> values = new ArrayList<>(); for(int i = 0;i<vals.length;i++){ values.add(vals[i]); } Collections.sort(values); for(int i =0;i<values.size();i++){ vals[i] = values.get(i); } return vals; } public static void reverseArray(long[] vals){ int startIndex = 0; int endIndex = vals.length-1; while(startIndex<=endIndex){ long temp = vals[startIndex]; vals[startIndex] = vals[endIndex]; vals[endIndex] = temp; startIndex++; endIndex--; } } public static void reverseArray(int[] vals){ int startIndex = 0; int endIndex = vals.length-1; while(startIndex<=endIndex){ int temp = vals[startIndex]; vals[startIndex] = vals[endIndex]; vals[endIndex] = temp; startIndex++; endIndex--; } } static class FastReader{ byte[] buf = new byte[2048]; int index, total; InputStream in; FastReader(InputStream is) { in = is; } int scan() throws IOException { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) { return -1; } } return buf[index++]; } String next() throws IOException { int c; for (c = scan(); c <= 32; c = scan()); StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) { sb.append((char) c); } return sb.toString(); } int nextInt() throws IOException { int c, val = 0; for (c = scan(); c <= 32; c = scan()); boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } long nextLong() throws IOException { int c; long val = 0; for (c = scan(); c <= 32; c = scan()); boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } } public static int GCD(int numA, int numB){ if(numA==0){ return numB; }else if(numB==0){ return numA; }else{ if(numA>numB){ return GCD(numA%numB,numB); }else{ return GCD(numA,numB%numA); } } } }
java
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" ]
//package shortestandlongestlis; import java.util.*; import java.io.*; public class shortestandlongestlis { public static void main(String[] args) throws IOException { BufferedReader fin = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(fin.readLine()); StringBuilder fout = new StringBuilder(); while(t-- > 0) { StringTokenizer st = new StringTokenizer(fin.readLine()); int n = Integer.parseInt(st.nextToken()); char[] s = st.nextToken().toCharArray(); char prev = s[0]; int counter = 0; boolean increasingFirst = s[0] == '<'; boolean inc = false; ArrayList<Integer> groups = new ArrayList<Integer>(); for(int i = 0; i < n - 1; i++) { if(s[i] != prev) { groups.add(counter); counter = 0; prev = s[i]; } counter ++; } groups.add(counter); inc = increasingFirst; int pointer = n; //System.out.println(groups); for(int i = 0; i < groups.size(); i++) { if(!inc && i != groups.size() - 1) { int cur = groups.get(i); int next = groups.get(i + 1); if(i == 0) { cur ++; } for(int j = 0; j < cur - 1; j++) { fout.append(pointer).append(" "); pointer --; } pointer -= (next); fout.append(pointer).append(" "); } else if(!inc && i == groups.size() - 1) { int cur = groups.get(i); if(i == 0) { cur ++; } for(int j = 0; j < cur; j++) { fout.append(pointer).append(" "); pointer --; } } else { //System.out.println(pointer); int cur = groups.get(i); int lowPointer = pointer; if(i == 0) { cur ++; lowPointer = n - cur; } pointer = lowPointer + 1; for(int j = 0; j < cur; j++) { fout.append(pointer).append(" "); pointer ++; } pointer = lowPointer; if(i != 0) { pointer --; } } inc = !inc; } fout.append("\n"); inc = increasingFirst; pointer = 1; for(int i = 0; i < groups.size(); i++) { if(inc && i != groups.size() - 1) { int cur = groups.get(i); int next = groups.get(i + 1); if(i == 0) { cur ++; } for(int j = 0; j < cur - 1; j++) { fout.append(pointer).append(" "); pointer ++; } pointer += (next); fout.append(pointer).append(" "); } else if(inc && i == groups.size() - 1) { int cur = groups.get(i); if(i == 0) { cur ++; } for(int j = 0; j < cur; j++) { fout.append(pointer).append(" "); pointer ++; } } else { //System.out.println(pointer); int cur = groups.get(i); int lowPointer = pointer; if(i == 0) { cur ++; lowPointer = cur + 1; } pointer = lowPointer - 1; for(int j = 0; j < cur; j++) { fout.append(pointer).append(" "); pointer --; } pointer = lowPointer; if(i != 0) { pointer ++; } } inc = !inc; } fout.append("\n"); } System.out.print(fout); } }
java
13
E
E. Holestime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes to play a lot. Most of all he likes to play a game «Holes». This is a game for one person with following rules:There are N holes located in a single row and numbered from left to right with numbers from 1 to N. Each hole has it's own power (hole number i has the power ai). If you throw a ball into hole i it will immediately jump to hole i + ai; then it will jump out of it and so on. If there is no hole with such number, the ball will just jump out of the row. On each of the M moves the player can perform one of two actions: Set the power of the hole a to value b. Throw a ball into the hole a and count the number of jumps of a ball before it jump out of the row and also write down the number of the hole from which it jumped out just before leaving the row. Petya is not good at math, so, as you have already guessed, you are to perform all computations.InputThe first line contains two integers N and M (1 ≤ N ≤ 105, 1 ≤ M ≤ 105) — the number of holes in a row and the number of moves. The second line contains N positive integers not exceeding N — initial values of holes power. The following M lines describe moves made by Petya. Each of these line can be one of the two types: 0 a b 1 a Type 0 means that it is required to set the power of hole a to b, and type 1 means that it is required to throw a ball into the a-th hole. Numbers a and b are positive integers do not exceeding N.OutputFor each move of the type 1 output two space-separated numbers on a separate line — the number of the last hole the ball visited before leaving the row and the number of jumps it made.ExamplesInputCopy8 51 1 1 1 1 2 8 21 10 1 31 10 3 41 2OutputCopy8 78 57 3
[ "data structures", "dsu" ]
import java.io.*; import java.util.*; public class Main{ public static void main(String[] args) throws Exception{ MScanner sc=new MScanner(System.in); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt(),m=sc.nextInt(); int[]in=sc.takearr(n); int sqrt=0; while(sqrt*sqrt<n) { sqrt++; } int []next=new int[n],cnt=new int[n]; int []rep=new int[n]; for(int i=n-1;i>=0;i--) { if(in[i]+i>=n) { next[i]=n; cnt[i]=1; rep[i]=i; } else { int curPortion=i/sqrt,nextPortion=(in[i]+i)/sqrt; if(curPortion==nextPortion) { next[i]=next[i+in[i]]; cnt[i]=cnt[i+in[i]]+1; rep[i]=rep[i+in[i]]; } else { next[i]=i+in[i]; cnt[i]=1; rep[i]=i; } } } while(m-->0) { if(sc.nextInt()==0) { int a=sc.nextInt()-1,p=sc.nextInt(); in[a]=p; for(int i=a;i>=0;i--) { if(in[i]+i>=n) { next[i]=n; cnt[i]=1; rep[i]=i; } else { int curPortion=i/sqrt,nextPortion=(in[i]+i)/sqrt; if(curPortion==nextPortion) { next[i]=next[i+in[i]]; cnt[i]=cnt[i+in[i]]+1; rep[i]=rep[i+in[i]]; } else { next[i]=i+in[i]; cnt[i]=1; rep[i]=i; } } if(i%sqrt==0) { break; } } } else { int ans=0,last=sc.nextInt()-1; while(true) { ans+=cnt[last]; if(next[last]==n) { last=rep[last]; break; } last=next[last]; } pw.println((last+1)+" "+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
1307
D
D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n)  — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n)  — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3 1 3 5 1 2 2 3 3 4 3 5 2 4 OutputCopy3 InputCopy5 4 2 2 4 1 2 2 3 3 4 4 5 OutputCopy3 NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33. The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33.
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "shortest paths", "sortings" ]
import java.io.*; import java.util.*; public class Main { private static int n; private static ArrayList<ArrayList<Integer>> adjacencyList; private static int[] bfs(int u) { int[] dist = new int[n]; Arrays.fill(dist, -1); Queue<Integer> queue = new LinkedList<>(); queue.offer(u); dist[u] = 0; while(!queue.isEmpty()) { int cur = queue.poll(); for(int next: adjacencyList.get(cur)) { if(dist[next] == -1) { queue.offer(next); dist[next] = dist[cur]+1; } } } return dist; } public static void main(String[] args) throws IOException { //BufferedReader f = new BufferedReader(new FileReader("uva.in")); BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); //PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("cowjump.out"))); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); StringTokenizer st = new StringTokenizer(f.readLine()); n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); st = new StringTokenizer(f.readLine()); Integer[] a = new Integer[k]; for(int i = 0; i < k; i++) { a[i] = Integer.parseInt(st.nextToken())-1; } adjacencyList = new ArrayList<>(n); for(int i = 0; i < n; i++) { adjacencyList.add(new ArrayList<>()); } for(int i = 0; i < m; i++) { st = new StringTokenizer(f.readLine()); int u = Integer.parseInt(st.nextToken())-1; int v = Integer.parseInt(st.nextToken())-1; adjacencyList.get(u).add(v); adjacencyList.get(v).add(u); } int[] src = bfs(0); int[] dst = bfs(n-1); Arrays.sort(a, new Comparator<Integer>() { @Override public int compare(Integer integer, Integer t1) { return (src[t1]-dst[t1])-(src[integer]-dst[integer]); } }); int max = 0; int d = 0; for(int i = 1; i < k; i++) { d = Math.max(d, dst[a[i-1]]); max = Math.max(max, src[a[i]]+d+1); } out.println(Math.min(max, src[n-1])); f.close(); out.close(); } }
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.util.*; import java.io.*; public class LIS { public static void main(String[] args) throws Exception { FastIO in = new FastIO(); int t = in.nextInt(); for (int tc=0; tc<t; tc++) { int n = in.nextInt(); String s = in.next(); int[] min = new int[n]; int[] max = new int[n]; for (int i=0; i<n; i++) { max[i] = i+1; min[n-i-1] = i+1; } int start = -1; boolean prev = false; for (int i=0; i<n-1; i++) { if (s.charAt(i)=='>') { if (start<0) start = i; } else { if (start>=0) { reverse(max, start, i); start = -1; } } } if (start>=0) reverse(max, start, n-1); start = -1; // boolean prev = false; for (int i=0; i<n-1; i++) { if (s.charAt(i)=='<') { if (start<0) start = i; } else { // System.out.println(start+" "+i); if (start>=0) { reverse(min, start, i); start = -1; } } } if (start>=0) reverse(min, start, n-1); // reverse(min, 2, 3); for (int i: min) { System.out.print(i+" "); } System.out.println(); for (int i: max) { System.out.print(i+" "); } System.out.println(); } } public static void reverse(int[] arr, int l, int r) { for (int i=l; i<=(l+r)/2; i++) { int temp = arr[i]; arr[i] = arr[r-(i-l)]; arr[r-(i-l)] = temp; } } static class FastIO { BufferedReader br; StringTokenizer st; PrintWriter pr; public FastIO() throws IOException { br = new BufferedReader( new InputStreamReader(System.in)); pr = new PrintWriter(System.out); } public String next() throws IOException { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } public double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } public String nextLine() throws IOException { String str = br.readLine(); return str; } } }
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.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.HashSet; import java.util.List; import java.util.StringTokenizer; public class C1305F { public static void main(String[] args) { var scanner = new BufferedScanner(); var writer = new PrintWriter(new BufferedOutputStream(System.out)); var n = scanner.nextInt(); var a = new long[n]; for (int i = 0; i < a.length; i++) { a[i] = scanner.nextLong(); } // 为什么不能distinct的?因为被选取的概率变了 // var distinct = Arrays.stream(a).boxed().collect(Collectors.toList()); // Collections.shuffle(distinct); // var distinct = Arrays.stream(a).distinct().toArray(); var factors = new HashSet<Long>(); // for (int guess = 0; guess < 40 && guess < distinct.size(); guess++) { // for (int j = -1; j <= 1; j++) { // factors.addAll(factor(distinct.get(guess) + j)); // } // } for (int guess = 0; guess < 20; guess++) { var i = (int) (Math.random() * a.length); for (int j = -1; j <= 1; j++) { factors.addAll(factor(a[i] + j)); } } var ans = countOps(2, a, n); factors.remove(2L); for (var factor : factors) { var ops = countOps(factor, a, ans); ans = Math.min(ans, ops); } writer.println(ans); scanner.close(); writer.flush(); writer.close(); } private static long countOps(long factor, long[] a, long already) { var ans = 0L; for (var x : a) { if (x < factor) { ans += factor - x; } else { var remain = x % factor; ans += Math.min(remain, factor - remain); // if (remain < factor / 2) { // ans += remain; // } else { // ans += factor - remain; // } } if (ans >= already) { break; } } return ans; } private static List<Long> factor(long a) { if (a <= 1) { return List.of(); } var limit = (long) Math.sqrt(a); var ans = new ArrayList<Long>(); for (long i = 2; i <= limit; i++) { var count = 0; while (a % i == 0) { a /= i; count++; } if (count > 0) { ans.add(i); } } if (a > 1) { ans.add(a); } return ans; } 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
1300
A
A. Non-zerotime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas have an array aa of nn integers [a1,a2,…,ana1,a2,…,an]. In one step they can add 11 to any element of the array. Formally, in one step they can choose any integer index ii (1≤i≤n1≤i≤n) and do ai:=ai+1ai:=ai+1.If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and Thomas do not mind to do this operation one more time.What is the minimum number of steps they need to do to make both the sum and the product of all elements in the array different from zero? Formally, find the minimum number of steps to make a1+a2+a1+a2+ …… +an≠0+an≠0 and a1⋅a2⋅a1⋅a2⋅ …… ⋅an≠0⋅an≠0.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1031≤t≤103). The description of the test cases follows.The first line of each test case contains an integer nn (1≤n≤1001≤n≤100) — the size of the array.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−100≤ai≤100−100≤ai≤100) — elements of the array .OutputFor each test case, output the minimum number of steps required to make both sum and product of all elements in the array different from zero.ExampleInputCopy4 3 2 -1 -1 4 -1 0 0 1 2 -1 2 3 0 -2 1 OutputCopy1 2 0 2 NoteIn the first test case; the sum is 00. If we add 11 to the first element, the array will be [3,−1,−1][3,−1,−1], the sum will be equal to 11 and the product will be equal to 33.In the second test case, both product and sum are 00. If we add 11 to the second and the third element, the array will be [−1,1,1,1][−1,1,1,1], the sum will be equal to 22 and the product will be equal to −1−1. It can be shown that fewer steps can't be enough.In the third test case, both sum and product are non-zero, we don't need to do anything.In the fourth test case, after adding 11 twice to the first element the array will be [2,−2,1][2,−2,1], the sum will be 11 and the product will be −4−4.
[ "implementation", "math" ]
import java.util.*; import java.io.*; import java.lang.reflect.Array; public class codeforce { public static void main(String[] args) throws IOException { Scanner read = new Scanner(System.in); int t = read.nextInt(); for(int k=0;k<t;k++){ int n = read.nextInt(); int[] arr = new int[n]; int sum = 0; int ans = 0; for(int i=0;i<n;i++){ arr[i] = read.nextInt(); if(arr[i]==0){ arr[i]++; ans++; } sum+=arr[i]; } if(sum==0) ans++; System.out.println(ans); } read.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" ]
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(); //I invented a new word!Plagiarism! //Did you hear about the mathematician who’s afraid of negative numbers?He’ll stop at nothing to avoid them //What do Alexander the Great and Winnie the Pooh have in common? Same middle name. //I finally decided to sell my vacuum cleaner. All it was doing was gathering dust! //ArrayList<Integer> a=new ArrayList <Integer>(); //PriorityQueue<Integer> pq=new PriorityQueue<>(); //char[] a = s.toCharArray(); // char s[]=sc.next().toCharArray(); 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(); int tes=1; label:while(tes-->0) { int n=sc.nextInt(); int a=sc.nextInt(); int b=sc.nextInt(); int k=sc.nextInt(); int i,ans=0; int arr[]=new int[n]; for(i=0;i<n;i++) { int x=sc.nextInt(); x=x%(a+b); if(x==0) x=a+b; arr[i]=(int)Math.ceil((double)x/a)-1; } Arrays.sort(arr); for(int it:arr) { k-=it; if(k<0) break; ans++; } System.out.println(ans); } } 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
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.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.*; public class weird_algrithm { static BufferedWriter output = new BufferedWriter( new OutputStreamWriter(System.out)); static BufferedReader sc = new BufferedReader(new InputStreamReader(System.in)); static int mod = 1000000007; static String toReturn = ""; static int steps = Integer.MAX_VALUE; static int maxlen = 1000005; /*MATHEMATICS FUNCTIONS START HERE MATHS MATHS MATHS MATHS*/ static long gcd(long a, long b) { if(b == 0) return a; else return gcd(b, a % b); } static long powerMod(long x, long y, int mod) { if(y == 0) return 1; long temp = powerMod(x, y / 2, mod); temp = ((temp % mod) * (temp % mod)) % mod; if(y % 2 == 0) return temp; else return ((x % mod) * (temp % mod)) % mod; } static long modInverse(long n, int p) { return powerMod(n, p - 2, p); } static long nCr(int n, int r, int mod, long [] fact, long [] ifact) { return ((fact[n] % mod) * ((ifact[r] * ifact[n - r]) % mod)) % mod; } static boolean isPrime(long a) { if(a == 1) return false; else if(a == 2 || a == 3 || a== 5) return true; else if(a % 2 == 0 || a % 3 == 0) return false; for(int i = 5; i * i <= a; i = i + 6) { if(a % i == 0 || a % (i + 2) == 0) return false; } return true; } static int [] seive(int a) { int [] toReturn = new int [a + 1]; for(int i = 0; i < a; i++) toReturn[i] = 1; toReturn[0] = 0; toReturn[1] = 0; toReturn[2] = 1; for(int i = 2; i * i <= a; i++) { if(toReturn[i] == 0) continue; for(int j = 2 * i; j <= a; j += i) toReturn[j] = 0; } return toReturn; } static long [] fact(int a) { long [] arr = new long[a + 1]; arr[0] = 1; for(int i = 1; i < a + 1; i++) { arr[i] = (arr[i - 1] * i) % mod; } return arr; } static ArrayList<Long> divisors(long n) { ArrayList<Long> arr = new ArrayList<Long>(); for(long i = 2; i * i <= n; i++) { if(n % i == 0) { while(n % i == 0) { n /= i; } arr.add(i); } } if(n > 1) arr.add(n); return arr; } static int euler(int n) { int ans = n; for(int i = 2; i * i <= n; i++) { if(n % i == 0) { while(n % i == 0) { n /= i; } ans -= ans / i; } } if(n > 1) ans -= ans / n; return ans; } static long extendedEuclid(long a, long b, long [] arr) { if(b == 0) { arr[0] = 1; arr[1] = 0; return a; } long [] arr1 = new long[2]; long d = extendedEuclid(b, a % b, arr1); arr[0] = arr1[1]; arr[1] = arr1[0] - arr1[1] * (a / b); return d; } /*MATHS MATHS MATHS MATHS MATHEMATICS FUNCTIONS END HERE */ /*SWAP FUNCTION START HERE SWAP SWAP SWAP SWAP */ static void swap(int i, int j, long[] arr) { long temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static void swap(int i, int j, int[] arr) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static void swap(int i, int j, String [] arr) { String temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static void swap(int i, int j, char [] arr) { char temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } /*SWAP SWAP SWAP SWAP SWAP FUNCTION END HERE*/ /*BINARY SEARCH METHODS START HERE * BINARY SEARCH * BINARY SEARCH * BINARY SEARCH * BINARY SEARCH */ static boolean BinaryCheck(long test, long [] arr, long health) { for(int i = 0; i <= arr.length - 1; i++) { if(i == arr.length - 1) health -= test; else if(arr[i + 1] - arr[i] > test) { health = health - test; }else { health = health - (arr[i + 1] - arr[i]); } if(health <= 0) return true; } return false; } /*-4 -2 0 1 4 5 6*/ static int binarySearch(int start, int end, long [] arr, long tar) { while(start <= end) { int mid = (start + end) / 2; if(arr[mid] < tar) { start = mid + 1; }else if(arr[mid] == tar) { if(mid - 1 >= 0 && arr[mid - 1] == tar) { end = mid - 1; }else return mid; }else end = mid - 1; } return start; } static int upper(int start, int end, ArrayList<Integer> pairs, long val) { while(start < end) { int mid = (start + end) / 2; if(pairs.get(mid) <= val) start = mid + 1; else end = mid; } return start; } static int lower(int start, int end, ArrayList<Long> arr, long val) { while(start < end) { int mid = (start + end) / 2; if(arr.get(mid) >= val) end = mid; else start = mid + 1; } return start; } /*BINARY SEARCH * BINARY SEARCH * BINARY SEARCH * BINARY SEARCH * BINARY SEARCH BINARY SEARCH METHODS END HERE*/ /*RECURSIVE FUNCTION START HERE * RECURSIVE * RECURSIVE * RECURSIVE * RECURSIVE */ static int recurse(int x, int y, int n, int steps1, Integer [][] dp) { if(x > n || y > n) return 0; if(dp[x][y] != null) { return dp[x][y]; } else if(x == n || y == n) { return steps1; } return dp[x][y] = Math.max(recurse(x + y, y, n, steps1 + 1, dp), recurse(x, x + y, n, steps1 + 1, dp)); } /*RECURSIVE * RECURSIVE * RECURSIVE * RECURSIVE * RECURSIVE RECURSIVE FUNCTION END HERE*/ /*GRAPH FUNCTIONS START HERE * GRAPH * GRAPH * GRAPH * GRAPH * */ static class edge{ int from, to; long weight; public edge(int x, int y, long weight2) { this.from = x; this.to = y; this.weight = weight2; } } static class sort implements Comparator<TreeNode>{ @Override public int compare(TreeNode o1, TreeNode o2) { // TODO Auto-generated method stub if(o1.start >= o2.start) return -1; return 1; } } /* * static class sort1 implements Comparator<TreeNode>{ * * * @Override public int compare(TreeNode a, TreeNode b) { // TODO Auto-generated * method stub if(a.c.equals(b.c)) { return a.id - b.id; }else return * a.c.compareTo(b.c); } * } */ static void addEdge(ArrayList<ArrayList<edge>> graph, int from, int to, long weight) { edge temp = new edge(from, to, weight); edge temp1 = new edge(to, from, weight); graph.get(from).add(temp); //graph.get(to).add(temp1); } static int ans = 0; static void topoSort(ArrayList<ArrayList<Integer>> graph, int vertex, boolean [] visited, ArrayList<Integer> toReturn) { if(visited[vertex]) return; visited[vertex] = true; for(int i = 0; i < graph.get(vertex).size(); i++) { if(!visited[graph.get(vertex).get(i)]) topoSort(graph, graph.get(vertex).get(i), visited, toReturn); } toReturn.add(vertex); } static boolean isCyclicDirected(ArrayList<ArrayList<Integer>> graph, int vertex, boolean [] visited, boolean [] reStack) { if(reStack[vertex]) return true; if(visited[vertex]) return false; reStack[vertex] = true; visited[vertex] = true; for(int i = 0; i < graph.get(vertex).size(); i++) { if(isCyclicDirected(graph, graph.get(vertex).get(i), visited, reStack)) return true; } reStack[vertex] = false; return false; } static int e = 0; static long mst(PriorityQueue<edge> pq, int nodes) { long weight = 0; int [] size = new int[nodes + 1]; Arrays.fill(size, 1); while(!pq.isEmpty()) { edge temp = pq.poll(); int x = parent(parent, temp.to); int y = parent(parent, temp.from); if(x != y) { //System.out.println(temp.weight); union(x, y, rank, parent, size); weight += temp.weight; e++; } } return weight; } static void floyd(long [][] dist) { // to find min distance between two nodes for(int k = 0; k < dist.length; k++) { for(int i = 0; i < dist.length; i++) { for(int j = 0; j < dist.length; j++) { if(dist[i][j] > dist[i][k] + dist[k][j]) { dist[i][j] = dist[i][k] + dist[k][j]; } } } } } static void dijkstra(ArrayList<ArrayList<edge>> graph, long [] dist, int src) { for(int i = 0; i < dist.length; i++) dist[i] = Long.MAX_VALUE / 2; dist[src] = 0; boolean visited[] = new boolean[dist.length]; PriorityQueue<pair> pq = new PriorityQueue<>(); pq.add(new pair(src, 0)); while(!pq.isEmpty()) { pair temp = pq.poll(); int index = (int)temp.a; for(int i = 0; i < graph.get(index).size(); i++) { if(dist[graph.get(index).get(i).to] > dist[index] + graph.get(index).get(i).weight) { dist[graph.get(index).get(i).to] = dist[index] + graph.get(index).get(i).weight; pq.add(new pair(graph.get(index).get(i).to, graph.get(index).get(i).weight)); } } } } static int parent1 = -1; static boolean ford(ArrayList<ArrayList<edge>> graph1, ArrayList<edge> graph, long [] dist, int src, int [] parent) { for(int i = 0; i < dist.length; i++) dist[i] = Long.MIN_VALUE / 2; dist[src] = 0; boolean hasNeg = false; for(int i = 0; i < dist.length - 1; i++) { for(int j = 0; j < graph.size(); j++) { int from = graph.get(j).from; int to = graph.get(j).to; long weight = graph.get(j).weight; if(dist[to] < dist[from] + weight) { dist[to] = dist[from] + weight; parent[to] = from; } } } for(int i = 0; i < graph.size(); i++) { int from = graph.get(i).from; int to = graph.get(i).to; long weight = graph.get(i).weight; if(dist[to] < dist[from] + weight) { parent1 = from; hasNeg = true; /* * dfs(graph1, parent1, new boolean[dist.length], dist.length - 1); * //System.out.println(ans); dfs(graph1, 0, new boolean[dist.length], parent1); */ //System.out.println(ans); if(ans == 2) break; else ans = 0; } } return hasNeg; } /*GRAPH FUNCTIONS END HERE * GRAPH * GRAPH * GRAPH * GRAPH */ /*disjoint Set START HERE * disjoint Set * disjoint Set * disjoint Set * disjoint Set */ static int [] rank; static int [] parent; static int parent(int [] parent, int x) { if(parent[x] == x) return x; else return parent[x] = parent(parent, parent[x]); } static boolean union(int x, int y, int [] rank, int [] parent, int [] setSize) { if(parent(parent, x) == parent(parent, y)) { return true; } if (rank[x] > rank[y]) { parent[y] = x; setSize[x] += setSize[y]; } else { parent[x] = y; setSize[y] += setSize[x]; if (rank[x] == rank[y]) rank[y]++; } return false; } /*disjoint Set END HERE * disjoint Set * disjoint Set * disjoint Set * disjoint Set */ /*INPUT START HERE * INPUT * INPUT * INPUT * INPUT * INPUT */ static int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(sc.readLine()); } static long nextLong() throws NumberFormatException, IOException { return Long.parseLong(sc.readLine()); } static long [] inputLongArr() throws NumberFormatException, IOException{ String [] s = sc.readLine().split(" "); long [] toReturn = new long[s.length]; for(int i = 0; i < s.length; i++) { toReturn[i] = Long.parseLong(s[i]); } return toReturn; } static int max = 0; static int [] inputIntArr() throws NumberFormatException, IOException{ String [] s = sc.readLine().split(" "); //System.out.println(s.length); int [] toReturn = new int[s.length]; for(int i = 0; i < s.length; i++) { toReturn[i] = Integer.parseInt(s[i]); } return toReturn; } /*INPUT * INPUT * INPUT * INPUT * INPUT * INPUT END HERE */ static long [] preCompute(int level) { long [] toReturn = new long[level]; toReturn[0] = 1; toReturn[1] = 16; for(int i = 2; i < level; i++) { toReturn[i] = ((toReturn[i - 1] % mod) * (toReturn[i - 1] % mod)) % mod; } return toReturn; } static class pair{ long a; long b; long d; public pair(long in, long y) { this.a = in; this.b = y; this.d = 0; } } static int [] nextGreaterBack(char [] s) { Stack<Integer> stack = new Stack<>(); int [] toReturn = new int[s.length]; for(int i = 0; i < s.length; i++) { if(!stack.isEmpty() && s[stack.peek()] >= s[i]) { stack.pop(); } if(stack.isEmpty()) { stack.push(i); toReturn[i] = -1; }else { toReturn[i] = stack.peek(); stack.push(i); } } return toReturn; } static int [] nextGreaterFront(char [] s) { Stack<Integer> stack = new Stack<>(); int [] toReturn = new int[s.length]; for(int i = s.length - 1; i >= 0; i--) { if(!stack.isEmpty() && s[stack.peek()] >= s[i]) { stack.pop(); } if(stack.isEmpty()) { stack.push(i); toReturn[i] = -1; }else { toReturn[i] = stack.peek(); stack.push(i); } } return toReturn; } static int [] lps(String s) { int [] lps = new int[s.length()]; lps[0] = 0; int j = 0; for(int i = 1; i < lps.length; i++) { j = lps[i - 1]; while(j > 0 && s.charAt(i) != s.charAt(j)) j = lps[j - 1]; if(s.charAt(i) == s.charAt(j)) { lps[i] = j + 1; } } return lps; } static int [][] vectors = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; static String dir = "DRUL"; static boolean check(int i, int j, boolean [][] visited) { if(i >= visited.length || j >= visited[0].length) return false; if(i < 0 || j < 0) return false; return true; } static void selectionSort(long arr[], long [] arr1, ArrayList<ArrayList<Integer>> ans) { int n = arr.length; for (int i = 0; i < n-1; i++) { int min_idx = i; for (int j = i+1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; else if(arr[j] == arr[min_idx]) { if(arr1[j] < arr1[min_idx]) min_idx = j; } if(i == min_idx) { continue; } ArrayList<Integer> p = new ArrayList<Integer>(); p.add(min_idx + 1); p.add(i + 1); ans.add(new ArrayList<Integer>(p)); swap(i, min_idx, arr); swap(i, min_idx, arr1); } } static int saved = Integer.MAX_VALUE; static String ans1 = ""; public static boolean isValid(int x, int y, String [] mat) { if(x >= mat.length || x < 0) return false; if(y >= mat[0].length() || y < 0) return false; return true; } public static void recurse3(ArrayList<Character> arr, int index, String s, int max, ArrayList<String> toReturn) { if(s.length() == max) { toReturn.add(s); return; } if(index == arr.size()) return; recurse3(arr, index + 1, s + arr.get(index), max, toReturn); recurse3(arr, index + 1, s, max, toReturn); } /* if(arr[i] > q) return Math.max(f(i + 1, q - 1) + 1, f(i + 1, q); else return f(i + 1, q) + 1 */ static void dfsDP(ArrayList<ArrayList<Integer>> graph, int src, int [] dp1, int [] dp2, int parent) { int sum1 = 0; int sum2 = 0; for(int x : graph.get(src)) { if(x == parent) continue; dfsDP(graph, x, dp1, dp2, src); sum1 += Math.min(dp1[x], dp2[x]); sum2 += dp1[x]; } dp1[src] = 1 + sum1; dp2[src] = sum2; System.out.println(src + " " + dp1[src] + " " + dp2[src]); } static int balanced = 0; static void dfs(ArrayList<ArrayList<ArrayList<Long>>> graph, long src, int [] dist, long sum1, long sum2, long parent, ArrayList<Long> arr, int index) { index = 0;//binarySearch(index, arr.size() - 1, arr, sum1); if(index < arr.size() && arr.get(index) <= sum1) { dist[(int)src] = index + 1; } else dist[(int)src] = index; for(ArrayList<Long> x : graph.get((int)src)) { if(x.get(0) == parent) continue; if(arr.size() != 0) arr.add(arr.get(arr.size() - 1) + x.get(2)); else arr.add(x.get(2)); dfs(graph, x.get(0), dist, sum1 + x.get(1), sum2, src, arr, index); arr.remove(arr.size() - 1); } } static int compare(String s1, String s2) { Queue<Character> q1 = new LinkedList<>(); Queue<Character> q2 = new LinkedList<Character>(); for(int i = 0; i < s1.length(); i++) { q1.add(s1.charAt(i)); q2.add(s2.charAt(i)); } int k = 0; while(k < s1.length()) { if(q1.equals(q2)) { break; } q2.add(q2.poll()); k++; } return k; } static long pro = 0; public static int len(ArrayList<ArrayList<Integer>> graph, int src, boolean [] visited ) { visited[src] = true; int max = 0; for(int x : graph.get(src)) { if(!visited[x]) { visited[x] = true; int len = len(graph, x, visited) + 1; //System.out.println(len); pro = Math.max(max * (len - 1), pro); max = Math.max(len, max); } } return max; } public static void recurse(int l, int [] ans) { if(l < 0) return; int r = (int)Math.sqrt(l * 2); int s = r * r; r = s - l; recurse(r - 1, ans); while(r <= l) { ans[r] = l; ans[l] = r; r++; l--; } } static boolean isSmaller(String str1, String str2) { // Calculate lengths of both string int n1 = str1.length(), n2 = str2.length(); if (n1 < n2) return true; if (n2 < n1) return false; for (int i = 0; i < n1; i++) if (str1.charAt(i) < str2.charAt(i)) return true; else if (str1.charAt(i) > str2.charAt(i)) return false; return false; } // Function for find difference of larger numbers static String findDiff(String str1, String str2) { // Before proceeding further, make sure str1 // is not smaller if (isSmaller(str1, str2)) { String t = str1; str1 = str2; str2 = t; } // Take an empty string for storing result String str = ""; // Calculate length of both string int n1 = str1.length(), n2 = str2.length(); // Reverse both of strings str1 = new StringBuilder(str1).reverse().toString(); str2 = new StringBuilder(str2).reverse().toString(); int carry = 0; // Run loop till small string length // and subtract digit of str1 to str2 for (int i = 0; i < n2; i++) { // Do school mathematics, compute difference of // current digits int sub = ((int)(str1.charAt(i) - '0') - (int)(str2.charAt(i) - '0') - carry); // If subtraction is less than zero // we add then we add 10 into sub and // take carry as 1 for calculating next step if (sub < 0) { sub = sub + 10; carry = 1; } else carry = 0; str += (char)(sub + '0'); } // subtract remaining digits of larger number for (int i = n2; i < n1; i++) { int sub = ((int)(str1.charAt(i) - '0') - carry); // if the sub value is -ve, then make it // positive if (sub < 0) { sub = sub + 10; carry = 1; } else carry = 0; str += (char)(sub + '0'); } // reverse resultant string return new StringBuilder(str).reverse().toString(); } public static long check(long [] arr, long mid) { long cost = 0; for(int i = 0; i < arr.length; i++) { cost += Math.abs(arr[i] - mid); } return cost; } /* 4, 8, 15, 16, 23 */ static interactor test; static boolean query(int x) throws NumberFormatException, IOException { //System.out.println(x); String to = test.interact(x); if(to.equals("yes")) return true; return false; } static int len(char [] s, int c, char s1) { int j = 0; int count = 0; int max = 0; for(int i = 0; i < s.length; i++) { if(s[i] != s1) { count++; } while(count > c) { if(s[j] != s1) count--; j++; } max = Math.max(max, i - j + 1); } return max; } static long ways(int i, int m, int len, int n, Long [][] dp) { if(i == n) return 1; if(len == 2 * m) return 1; if(dp[i][len] != null) return dp[i][len]; return dp[i][len] = (ways(i, m, len + 1, n, dp) + ways(i + 1, m, len, n, dp)) % mod; } static void solve() throws IOException { int [] n = inputIntArr(); long [][] dp = new long[n[0]][2 * n[1] + 1]; for(int i = 0; i < dp.length; i++) dp[i][0] = 1; for(int i = 0; i < dp[0].length; i++) dp[0][i] = 1; for(int i = 1; i < dp.length; i++) { for(int j = 1; j < dp[0].length; j++) { dp[i][j] = (dp[i][j - 1] + dp[i - 1][j]) % mod; } } output.write(dp[dp.length - 1][dp[0].length - 1] + "\n"); } /*1 2 3 4 5 6*/ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub //int t = Integer.parseInt(sc.readLine()); for(int i = 0; i < t; i++) solve(); output.flush(); } } class interactor{ int [] arr; int min = 2; int max = 100; int n; public interactor() { n = (int)(Math.random()*(max-min+1)+min); } public String interact(int x) { if(n % x == 0) return "yes"; return "no"; } } class TreeNode { int start; int end; public TreeNode(int start, int end) { this.start = start; this.end = end; } public String toString() { return start + " " + end; } } /* 1 10 6 10 85 84 11 99 9 20 88 31 1 0 1 1 1 0 0 1 1 1 1 0 0 */
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.util.*; public class Solution { public static void main(String[] args) throws java.lang.Exception { Scanner in = new Scanner(System.in); int testcases = in.nextInt(); while (testcases-- > 0) { int n = in.nextInt(); int a = 0; int b = 0; int c = 0; a = factors(n, 2); b = factors(n / a, a + 1); c = n / (a * b); if (a >= 2 && b >= 2 && c >= 2 && a != b && b != c && c != a) { System.out.println("YES"); System.out.println(a + " " + b + " " + c); } else System.out.println("NO"); } in.close(); } static int factors(int N, int k) { for (int i = k; i < Math.sqrt(N); i++) { if (N % i == 0) return i; } return -1; } }
java
1141
G
G. Privatization of Roads in Treelandtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputTreeland consists of nn cities and n−1n−1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed kk and the number of companies taking part in the privatization is minimal.Choose the number of companies rr such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most kk. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal rr that there is such assignment to companies from 11 to rr that the number of cities which are not good doesn't exceed kk. The picture illustrates the first example (n=6,k=2n=6,k=2). The answer contains r=2r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 33) is not good. The number of such vertices (just one) doesn't exceed k=2k=2. It is impossible to have at most k=2k=2 not good cities in case of one company. InputThe first line contains two integers nn and kk (2≤n≤200000,0≤k≤n−12≤n≤200000,0≤k≤n−1) — the number of cities and the maximal number of cities which can have two or more roads belonging to one company.The following n−1n−1 lines contain roads, one road per line. Each line contains a pair of integers xixi, yiyi (1≤xi,yi≤n1≤xi,yi≤n), where xixi, yiyi are cities connected with the ii-th road.OutputIn the first line print the required rr (1≤r≤n−11≤r≤n−1). In the second line print n−1n−1 numbers c1,c2,…,cn−1c1,c2,…,cn−1 (1≤ci≤r1≤ci≤r), where cici is the company to own the ii-th road. If there are multiple answers, print any of them.ExamplesInputCopy6 2 1 4 4 3 3 5 3 6 5 2 OutputCopy2 1 2 1 1 2 InputCopy4 2 3 1 1 4 1 2 OutputCopy1 1 1 1 InputCopy10 2 10 3 1 2 1 3 1 4 2 5 2 6 2 7 3 8 3 9 OutputCopy3 1 1 2 3 2 3 1 3 1
[ "binary search", "constructive algorithms", "dfs and similar", "graphs", "greedy", "trees" ]
import java.io.*; import java.util.*; public class A{ static ArrayList<edge>[]adj; static int []col; static class edge { int v,idx; edge(int v,int idx){ this.v=v; this.idx=idx; } } static void dfs(int u,int max,int p,int colP) { int curr=1; for(edge a:adj[u]) { int v=a.v,idx=a.idx; if(v==p) continue; if(curr==colP) curr++; if(curr>max) curr=1; col[idx]=curr; dfs(v,max,u,curr); if(++curr>max) curr=1; } } public static void main(String[] args) throws IOException { Scanner sc=new Scanner(); PrintWriter out=new PrintWriter(System.out); int n=sc.nextInt(),k=sc.nextInt(); adj=new ArrayList[n]; for(int i=0;i<n;i++) adj[i]=new ArrayList(); for(int i=1;i<n;i++) { int u=sc.nextInt()-1,v=sc.nextInt()-1; adj[u].add(new edge(v, i)); adj[v].add(new edge(u, i)); } int ans=-1,lo=1,hi=n-1; while(lo<=hi) { int greater=0; int mid=lo+hi>>1; for(int i=0;i<n;i++) if(adj[i].size()>mid) greater++; if(greater<=k) { ans=mid; hi=mid-1; } else lo=mid+1; } col=new int [n]; out.println(ans); dfs(0, ans, -1, -1); for(int i=1;i<n;i++) out.println(col[i]); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner(){ br=new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException{ br=new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while(st==null || !st.hasMoreTokens()) st=new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException{ return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } } }
java
1300
B
B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3 1 1 1 3 6 5 4 1 2 3 5 13 4 20 13 2 5 8 3 17 16 OutputCopy0 1 5 NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference.
[ "greedy", "implementation", "sortings" ]
import java.util.*; public class HelloWorld { 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[2*n]; for(int i=0;i<2*n;i++) a[i]=sc.nextInt(); Arrays.sort(a); System.out.println(a[n]-a[n-1]); } } }
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 P13A { void go() { int n = Reader.nextInt(); long sum = 0; for(int i = 2; i < n; i++) { sum += digSum(n, i); } long gcd = gcd(sum, n - 2); Writer.println((sum / gcd) + "/" + ((n - 2) / gcd)); } private long digSum(int n, int base) { long sum = 0; while(n > 0) { sum += n % base; n /= base; } return sum; } private long gcd(long a, long b) { if(a == 0) { return b; } return gcd(b % a, a); } void solve() { go(); } void run() throws Exception { Reader.init(System.in); Writer.init(System.out); solve(); Writer.close(); } public static void main(String[] args) throws Exception { new P13A().run(); } public static class Reader { public static StringTokenizer st; public static BufferedReader br; public static void init(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(""); } public static String next() { while(!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new InputMismatchException(); } } return st.nextToken(); } public static int nextInt() { return Integer.parseInt(next()); } public static long nextLong() { return Long.parseLong(next()); } public static double nextDouble() { return Double.parseDouble(next()); } } public static class Writer { public static PrintWriter pw; public static void init(OutputStream os) { pw = new PrintWriter(new BufferedOutputStream(os)); } public static void print(String s) { pw.print(s); } public static void print(char c) { pw.print(c); } public static void print(int x) { pw.print(x); } public static void print(long x) { pw.print(x); } public static void println(String s) { pw.println(s); } public static void println(char c) { pw.println(c); } public static void println(int x) { pw.println(x); } public static void println(long x) { pw.println(x); } public static void flush() { pw.flush(); } public static void close() { pw.close(); } } }
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.*; import java.util.*; public class CF1307E extends PrintWriter { CF1307E() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1307E o = new CF1307E(); o.main(); o.flush(); } static final int MD = 1000000007; int cnt_; long sum; int n, m; int[] ss, ii, jj; int[] ll, rr, lr, w2; void update(int h, int x) { Arrays.fill(ll, 0); Arrays.fill(rr, 0); Arrays.fill(lr, 0); for (int h_ = 0; h_ < m; h_++) { if (h_ == h) continue; int s_ = ss[h_], i_ = ii[h_], j_ = jj[h_]; if (i_ < x) ll[s_]++; if (j_ > x) rr[s_]++; if (i_ < x && j_ > x) lr[s_]++; } int cnt; long ways; if (h == -1) { cnt = 0; ways = 1; for (int s = 0; s < n; s++) if (rr[s] > 0) { cnt++; ways = ways * rr[s] % MD; } } else { Arrays.fill(w2, 0); int s = ss[h]; for (int h_ = 0; h_ < m; h_++) { int s_ = ss[h_]; if (s_ == s) continue; int i_ = ii[h_], j_ = jj[h_]; if (i_ < x) { int r = rr[s_]; if (j_ > x) r--; if (r > 0) w2[s_] += r; } } cnt = rr[s] == 0 ? 1 : 2; ways = rr[s] == 0 ? 1 : rr[s]; for (int s_ = 0; s_ < n; s_++) { if (s_ == s) continue; if (w2[s_] > 0) { cnt += 2; ways = ways * w2[s_] % MD; } else if (ll[s_] + rr[s_] - lr[s_] > 0) { cnt++; ways = ways * (ll[s_] + rr[s_]) % MD; } } } if (cnt_ < cnt) { cnt_ = cnt; sum = ways; } else if (cnt_ == cnt) sum += ways; } void main() { n = sc.nextInt(); m = sc.nextInt(); int[] ss_ = new int[n]; for (int i = 0; i < n; i++) ss_[i] = sc.nextInt() - 1; ss = new int[m]; ii = new int[m]; jj = new int[m]; for (int h = 0; h < m; h++) { int s = sc.nextInt() - 1; int k = sc.nextInt(); int i, j, a; for (i = 0, a = 0; i < n; i++) if (ss_[i] == s && ++a == k) break; for (j = n - 1, a = 0; j >= 0; j--) if (ss_[j] == s && ++a == k) break; ss[h] = s; ii[h] = i; jj[h] = j; } ll = new int[n]; rr = new int[n]; lr = new int[n]; w2 = new int[n]; update(-1, -1); for (int h = 0; h < m; h++) if (ii[h] < n) update(h, ii[h]); sum %= MD; println(cnt_ + " " + sum); } }
java
1141
F1
F1. Same Sum Blocks (Easy)time limit per test2 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≤501≤n≤50) — 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
[ "greedy" ]
//package codeforces_464_div2; import java.util.*; import java.util.stream.Collectors; public class F { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); int[][] sub = new int[n][n]; for (int i = 0; i < n; i++) { sub[i][i] = arr[i]; for (int j = i + 1; j < n; j++) { sub[i][j] = sub[i][j - 1] + arr[j]; } } HashMap<Integer, List<P>> hm = new HashMap<>(); for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { if (hm.containsKey(sub[i][j])) { hm.get(sub[i][j]).add(new P(i, j)); } else { List<P> temp = new ArrayList<>(); temp.add(new P(i, j)); hm.put(sub[i][j], temp); } } } int ans = Integer.MIN_VALUE; /*for(Map.Entry it : hm.entrySet()) { int or = overlap(it.getValue()); ans = Math.max(ans, or); }*/ List<P> ansList = null; for (List<P> it : hm.values()) { int or = overlap(it); if(or>ans) { ans = or; ansList = it; } } List<P> processedList = extractOverlapping(ansList); System.out.println(ans); for(int i=0; i<processedList.size(); i++) { int A = processedList.get(i).a + 1; int B = processedList.get(i).b + 1; System.out.println(A + " " + B); } } public static int overlap(List<P> listOfPair) { List<P> sortedList = listOfPair.stream() .sorted((pair1, pair2) -> pair1.getB().compareTo(pair2.getB())) .collect(Collectors.toList()); int cnt = 0; int end = sortedList.get(0).b; for (int i = 1; i < sortedList.size(); i++) { if (sortedList.get(i).a <= end) { cnt++; } else { end = sortedList.get(i).b; } } return sortedList.size() - cnt; } public static List<P> extractOverlapping(List<P> ansList) { List<P> sortedList = ansList.stream() .sorted((pair1, pair2) -> pair1.getB().compareTo(pair2.getB())) .collect(Collectors.toList()); List<P> finalList = new ArrayList<>(); finalList.add(sortedList.get(0)); int end = sortedList.get(0).b; for (int i = 1; i < sortedList.size(); i++) { if (sortedList.get(i).a <= end) { continue; } else { finalList.add(sortedList.get(i)); end = sortedList.get(i).b; } } return finalList; } } class P implements Comparable<P> { Integer a; Integer b; public P(int a, int b) { this.a = a; this.b = b; } public Integer getA() { return a; } public Integer getB() { return b; } @Override public int compareTo(P that) { return this.b.compareTo(that.b); } }
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.*; import java.util.*; public class A { static int INF = (int) 1e9; static boolean solve(int[][] a) { int n = a.length; Arrays.sort(a, (x, y) -> x[0] - y[0]); int[] buildTree = new int[n]; for (int i = 0; i < n; i++) buildTree[i] = a[i][2]; SegmentTree max = new SegmentTree(buildTree); for (int i = 0; i < n; i++) buildTree[i] = -a[i][3]; SegmentTree min = new SegmentTree(buildTree); for (int i = 0; i < n; i++) { int lo = i, hi = n - 1; int intersect = i; while (lo <= hi) { int mid = lo + hi >> 1; if (a[mid][0] <= a[i][1]) { intersect = mid; lo = mid + 1; } else hi = mid - 1; } if (intersect == i) continue; int maxL = max.query(i + 1, intersect), minR = -min.query(i + 1, intersect); if (maxL > a[i][3] || minR < a[i][2]) return false; } return true; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); int[][] a = new int[n][4]; for (int i = 0; i < n; i++) for (int j = 0; j < 4; j++) a[i][j] = sc.nextInt(); boolean ans = solve(a); for (int i = 0; i < n; i++) { for (int j = 0; j < 2; j++) { int tmp = a[i][j]; a[i][j] = a[i][j + 2]; a[i][j + 2] = tmp; } } ans &= solve(a); out.println(ans ? "YES" : "NO"); out.close(); } static class SegmentTree { int n, a[], max[]; SegmentTree(int[] x) { a = x; n = a.length; max = new int[4 * n]; build(1, 0, n - 1); } void build(int node, int tl, int tr) { if (tl == tr) max[node] = a[tl]; else { int mid = tl + tr >> 1, left = node << 1, right = left | 1; build(left, tl, mid); build(right, mid + 1, tr); max[node] = Math.max(max[left], max[right]); } } int query(int l, int r) { return query(1, 0, n - 1, l, r); } int query(int node, int tl, int tr, int l, int r) { if (tr < l || r < tl) return -INF; if (tl >= l && tr <= r) return max[node]; int mid = tl + tr >> 1, left = node << 1, right = left | 1; return Math.max(query(left, tl, mid, l, r), query(right, mid + 1, tr, l, r)); } } static class Scanner { BufferedReader br; StringTokenizer st; Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); } Scanner(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { return br.readLine(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } boolean ready() throws IOException { return br.ready(); } } static void sort(int[] a) { shuffle(a); Arrays.sort(a); } static void shuffle(int[] a) { int n = a.length; Random rand = new Random(); for (int i = 0; i < n; i++) { int tmpIdx = rand.nextInt(n); int tmp = a[i]; a[i] = a[tmpIdx]; a[tmpIdx] = tmp; } } }
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.util.*; public class CF1291_A{ public static void main(String []args){ Scanner cs = new Scanner(System.in); int t = cs.nextInt(); int n; String str; String answer; boolean b; while(t-->0){ b = true; answer = ""; n = cs.nextInt(); str = cs.next(); for(int j =0; j < n; j++){ if(Character.getNumericValue(str.charAt(j)) % 2 != 0){ answer += str.charAt(j); } if(answer.length() == 2){ System.out.println(answer); b = false; break; } } if(b){ System.out.println(-1); } } } }
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.io.*; import java.util.StringTokenizer; public class ScoreDistribution { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); static StringTokenizer st; static int readInt() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return Integer.parseInt(st.nextToken()); } public static void main(String[] args) throws IOException { int n = readInt(); int m = readInt(); // n: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 // (n-1)/2: 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5 // n/2: 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6 // max: 0, 0, 1, 2, 4, 6, 9, 12, 16, 20, 25, 30 int max = ((n - 1) / 2) * (n / 2); if (m > max) { System.out.println(-1); return; } if (m == 0 ) { for (int i = n * n, limit = n * (n + n - 1); i <= limit; i += n) { pw.print(i + " "); } pw.close(); return; } // as long as it is no less than 2 * n; final int LARGE_INTEGER = 2 * n; int a = (int) Math.sqrt(m - 1); if (m <= a * (a + 1)) { for (int i = 1; i <= 2 * a + 1; i++) { pw.print(i + " "); } int delta = a * (a + 1) - m; pw.print((2 * a + 2 + 2 * delta) + " "); for (int i = LARGE_INTEGER * LARGE_INTEGER, limit = LARGE_INTEGER * (LARGE_INTEGER + n - 2 * a - 3); i <= limit; i += LARGE_INTEGER) { pw.print(i + " "); } } else { for (int i = 1; i <= 2 * a + 2; i++) { pw.print(i + " "); } int delta = (a + 1) * (a + 1) - m; pw.print((2 * a + 3 + 2 * delta) + " "); for (int i = LARGE_INTEGER * LARGE_INTEGER, limit = LARGE_INTEGER * (LARGE_INTEGER + n - 2 * a - 4); i <= limit; i += LARGE_INTEGER) { pw.print(i + " "); } } pw.close(); } }
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.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.sort; public class Round12 { public static void main(String[] args) { FastReader fastReader = new FastReader(); PrintWriter out = new PrintWriter(System.out); int t = fastReader.nextInt(); while (t-- > 0) { int n = fastReader.nextInt(); int m = fastReader.nextInt(); char c[] = fastReader.nextLine().toCharArray(); int ma[] = fastReader.ria(m); rsort(ma); long freq [] = new long[26]; for (int i = 0 ; i < n; i++){ int low = 0 , high = m-1; int index = -1; while (low <= high){ int mid = (low+high)/2; if (ma[mid] >= (i+1)){ high = mid-1; index = mid; }else{ low = mid+1; } } // out.println(index); if (index != -1){ int size = (m)-(index); freq[c[i]-'a']+=size; } freq[c[i] -'a']++; } StringBuilder ans = new StringBuilder(); for (int i = 0; i < 26; i++){ ans.append(freq[i]).append(" "); } out.println(ans); } out.close(); } // constants static final int IBIG = 1000000000; static final int IMAX = 2147483647; static final long LMAX = 92233720368547L; 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
1311
D
D. Three Integerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given three integers a≤b≤ca≤b≤c.In one move, you can add +1+1 or −1−1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positive numbers using such operations.You have to perform the minimum number of such operations in order to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB.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 tt lines describe test cases. Each test case is given on a separate line as three space-separated integers a,ba,b and cc (1≤a≤b≤c≤1041≤a≤b≤c≤104).OutputFor each test case, print the answer. In the first line print resres — the minimum number of operations you have to perform to obtain three integers A≤B≤CA≤B≤C such that BB is divisible by AA and CC is divisible by BB. On the second line print any suitable triple A,BA,B and CC.ExampleInputCopy8 1 2 3 123 321 456 5 10 15 15 18 21 100 100 101 1 22 29 3 19 38 6 30 46 OutputCopy1 1 1 3 102 114 228 456 4 4 8 16 6 18 18 18 1 100 100 100 7 1 22 22 2 1 19 38 8 6 24 48
[ "brute force", "math" ]
import java.io.*; import java.util.*; public class ThreeIntegers { public static void main(String[] args) throws Exception { FastIO in = new FastIO(); int t = in.nextInt(); for (int tc=0; tc<t; tc++) { int a = in.nextInt(); int b = in.nextInt(); int c = in.nextInt(); int min = Integer.MAX_VALUE; int[] ans = new int[3]; for (int checkA = 1; checkA<2*a; checkA++) { for (int checkB = checkA; checkB<2*b; checkB+=checkA) { int checkC1 = c/checkB * checkB; int checkC2 = c/checkB * checkB + checkB; if (checkB<=checkC1) { int operations = (Math.abs(checkA-a)+Math.abs(checkB-b)+Math.abs(checkC1-c)); if (operations<min) { min = operations; ans[0] = checkA; ans[1] = checkB; ans[2] = checkC1; } } if (checkB<=checkC2) { int operations = (Math.abs(checkA-a)+Math.abs(checkB-b)+Math.abs(checkC2-c)); if (operations<min) { min = operations; ans[0] = checkA; ans[1] = checkB; ans[2] = checkC2; } } } } System.out.println(min); for (int i: ans) System.out.print(i+" "); System.out.println(); } } static class FastIO { BufferedReader br; StringTokenizer st; public FastIO() throws IOException { br = new BufferedReader( new InputStreamReader(System.in)); } public String next() throws IOException { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } public double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } public String nextLine() throws IOException { String str = br.readLine(); return str; } } }
java
1303
E
E. Erase Subsequencestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. You can build new string pp from ss using the following operation no more than two times: choose any subsequence si1,si2,…,siksi1,si2,…,sik where 1≤i1<i2<⋯<ik≤|s|1≤i1<i2<⋯<ik≤|s|; erase the chosen subsequence from ss (ss can become empty); concatenate chosen subsequence to the right of the string pp (in other words, p=p+si1si2…sikp=p+si1si2…sik). Of course, initially the string pp is empty. For example, let s=ababcds=ababcd. At first, let's choose subsequence s1s4s5=abcs1s4s5=abc — we will get s=bads=bad and p=abcp=abc. At second, let's choose s1s2=bas1s2=ba — we will get s=ds=d and p=abcbap=abcba. So we can build abcbaabcba from ababcdababcd.Can you build a given string tt using the algorithm above?InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain test cases — two per test case. The first line contains string ss consisting of lowercase Latin letters (1≤|s|≤4001≤|s|≤400) — the initial string.The second line contains string tt consisting of lowercase Latin letters (1≤|t|≤|s|1≤|t|≤|s|) — the string you'd like to build.It's guaranteed that the total length of strings ss doesn't exceed 400400.OutputPrint TT answers — one per test case. Print YES (case insensitive) if it's possible to build tt and NO (case insensitive) otherwise.ExampleInputCopy4 ababcd abcba a b defi fed xyz x OutputCopyYES NO NO YES
[ "dp", "strings" ]
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Ribhav */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); EEraseSubsequences solver = new EEraseSubsequences(); solver.solve(1, in, out); out.close(); } static class EEraseSubsequences { short[][][] dp; int n; int m; char[] arr1; char[] arr2; public void solve(int testNumber, FastReader in, PrintWriter out) { int t1 = in.nextInt(); outer: while (t1-- > 0) { String str1 = in.nextString(); String str2 = in.nextString(); n = str1.length(); m = str2.length(); arr1 = str1.toCharArray(); arr2 = str2.toCharArray(); dp = new short[n][m + 1][m + 1]; for (int i = 0; i < n; i++) for (int j = 0; j <= m; j++) Arrays.fill(dp[i][j], (short) -2); for (int i = n - 1; i >= 0; i--) for (int j = m; j >= 0; j--) for (int k = m; k >= 0; k--) func(i, j, k); for (int i = 0; i < m; i++) { if (func(0, 0, i) >= i) { out.println("YES"); continue outer; } } out.println("NO"); } } private short func(int pos1, int pos2, int pos3) { if (pos1 == n) return (short) (pos3 == m ? pos2 : -1); if (pos2 == m && pos3 == m) return (short) pos2; if (dp[pos1][pos2][pos3] != -2) return dp[pos1][pos2][pos3]; short val = func(pos1 + 1, pos2, pos3); if (pos2 != m && arr1[pos1] == arr2[pos2]) val = max(val, func(pos1 + 1, pos2 + 1, pos3)); if (pos3 != m && arr1[pos1] == arr2[pos3]) val = max(val, func(pos1 + 1, pos2, pos3 + 1)); return dp[pos1][pos2][pos3] = val; } private short max(short a, short b) { return a > b ? a : b; } } static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastReader.SpaceCharFilter filter; public FastReader(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 interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
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 static java.lang.System.out; import static java.lang.Math.*; import static java.lang.System.*; import java.lang.reflect.Array; import java.util.*; import java.io.*; import java.math.*; public class Main { static FastReader sc; static long mod=((long)1e9)+7; // static FastWriter out; static FastWriter out; public static void main(String hi[]) throws IOException { // initializeIO(); out=new FastWriter(); sc=new FastReader(); long startTimeProg=System.currentTimeMillis(); long endTimeProg=Long.MAX_VALUE; int t=sc.nextInt(); // int t=1; // boolean[] seave=sieveOfEratosthenes((int)(1e5)); // int[] seave2=sieveOfEratosthenesInt((int)(1e5)); while(t--!=0) { int n=sc.nextInt(); String s=sc.next(); String res_s=s; int res=1; for(int i=0;i<n;i++){ int k=i+1; StringBuilder sb=new StringBuilder(); sb.append(s.substring(i,n)); if(n%2!=0){ if(k%2==0){ sb.append(s.substring(0,i)); }else{ sb.append(reverseString(s.substring(0,i))); } }else{ if(k%2==0){ sb.append(reverseString(s.substring(0,i))); }else{ sb.append(s.substring(0,i)); } } boolean done=false; for(int j=0;j<n;j++){ if(sb.charAt(j)<res_s.charAt(j)){ done=true; break; }else if(sb.charAt(j)>res_s.charAt(j)){ break; } } if(done){ res_s=sb.toString(); res=k; } } print(res_s+"\n"+res); // break; } endTimeProg=System.currentTimeMillis(); debug("[finished : "+(endTimeProg-startTimeProg)+".ms ]"); // System.out.println(String.format("%.9f", max)); } private static List<Long> factors2(long n){ List<Long> res=new ArrayList<>(); // res.add(n); for (long i=2; i*i<(n); i++){ if (n%i==0){ if(i%2!=0)res.add(i); if (n/i != i){ if((n/i)%2!=0)res.add(n/i); } } } return res; } public static boolean isNumeric(String strNum) { if (strNum == null) { return false; } try { double d = Double.parseDouble(strNum); } catch (NumberFormatException nfe) { return false; } return true; } private static boolean isSorted(List<Integer> li){ int n=li.size(); if(n<=1)return true; for(int i=0;i<n-1;i++){ if(li.get(i)>li.get(i+1))return false; } return true; } static boolean isPowerOfTwo(long x) { return x != 0 && ((x & (x - 1)) == 0); } private static boolean ispallindromeList(List<Integer> res){ int l=0,r=res.size()-1; while(l<r){ if(res.get(l)!=res.get(r))return false; l++; r--; } return true; } private static class Pair{ int first=0; int sec=0; int[] arr; char ch; String s; Map<Integer,Integer> map; Pair(int first,int sec){ this.first=first; this.sec=sec; } Pair(int[] arr){ this.map=new HashMap<>(); for(int x:arr) this.map.put(x,map.getOrDefault(x,0)+1); this.arr=arr; } Pair(char ch,int first){ this.ch=ch; this.first=first; } Pair(String s,int first){ this.s=s; this.first=first; } } private static int sizeOfSubstring(int st,int e){ int s=e-st+1; return (s*(s+1))/2; } private static Set<Long> factors(long n){ Set<Long> res=new HashSet<>(); // res.add(n); for (long i=1; i*i<=(n); i++){ if (n%i==0){ res.add(i); if (n/i != i){ res.add(n/i); } } } return res; } private static long fact(long n){ if(n<=2)return n; return n*fact(n-1); } private static long ncr(long n,long r){ return fact(n)/(fact(r)*fact(n-r)); } private static int lessThen(long[] nums,long val,boolean work,int l,int r){ int i=-1; if(work)i=0; while(l<=r){ int mid=l+((r-l)/2); if(nums[mid]<=val){ i=mid; l=mid+1; }else{ r=mid-1; } } return i; } private static int lessThen(List<Long> nums,long val,boolean work,int l,int r){ int i=-1; if(work)i=0; while(l<=r){ int mid=l+((r-l)/2); if(nums.get(mid)<=val){ i=mid; l=mid+1; }else{ r=mid-1; } } return i; } private static int lessThen(List<Integer> nums,int val,boolean work,int l,int r){ int i=-1; if(work)i=0; while(l<=r){ int mid=l+((r-l)/2); if(nums.get(mid)<=val){ i=mid; l=mid+1; }else{ r=mid-1; } } return i; } private static int greaterThen(List<Long> nums,long val,boolean work,int l,int r){ int i=-1; if(work)i=r; while(l<=r){ int mid=l+((r-l)/2); if(nums.get(mid)>=val){ i=mid; r=mid-1; }else{ l=mid+1; } } return i; } private static int greaterThen(List<Integer> nums,int val,boolean work){ int i=-1,l=0,r=nums.size()-1; if(work)i=r; while(l<=r){ int mid=l+((r-l)/2); if(nums.get(mid)>=val){ i=mid; r=mid-1; }else{ l=mid+1; } } return i; } private static int greaterThen(long[] nums,long val,boolean work,int l,int r){ int i=-1; if(work)i=r; while(l<=r){ int mid=l+((r-l)/2); if(nums[mid]>=val){ i=mid; r=mid-1; }else{ l=mid+1; } } return i; } private static long gcd(long[] arr){ long ans=0; for(long x:arr){ ans=gcd(x,ans); } return ans; } private static int gcd(int[] arr){ int ans=0; for(int x:arr){ ans=gcd(x,ans); } return ans; } private static long sumOfAp(long a,long n,long d){ long val=(n*( 2*a+((n-1)*d))); return val/2; } //geometrics private static double areaOftriangle(double x1,double y1,double x2,double y2,double x3,double y3){ double[] mid_point=midOfaLine(x1,y1,x2,y2); // debug(Arrays.toString(mid_point)+" "+x1+" "+y1+" "+x2+" "+y2+" "+x3+" "+" "+y3); double height=distanceBetweenPoints(mid_point[0],mid_point[1],x3,y3); double wight=distanceBetweenPoints(x1,y1,x2,y2); // debug(height+" "+wight); return (height*wight)/2; } private static double distanceBetweenPoints(double x1,double y1,double x2,double y2){ double x=x2-x1; double y=y2-y1; return (Math.pow(x,2)+Math.pow(y,2)); } public static boolean isPerfectSquareByUsingSqrt(long n) { if (n <= 0) { return false; } double squareRoot = Math.sqrt(n); long tst = (long)(squareRoot + 0.5); return tst*tst == n; } private static double[] midOfaLine(double x1,double y1,double x2,double y2){ double[] mid=new double[2]; mid[0]=(x1+x2)/2; mid[1]=(y1+y2)/2; return mid; } private static long sumOfN(long n){ return (n*(n+1))/2; } private static long power(long x,long y,long p){ long res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p if (x == 0) return 0; // In case x is divisible by p; while (y > 0){ // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } /* Function to calculate x raised to the power y in O(logn)*/ static long power(long x, long y){ long temp; if( y == 0) return 1l; temp = power(x, y / 2); if (y % 2 == 0) return (temp*temp); else return (x*temp*temp); } private static StringBuilder reverseString(String s){ StringBuilder sb=new StringBuilder(s); int l=0,r=sb.length()-1; while(l<=r){ char ch=sb.charAt(l); sb.setCharAt(l,sb.charAt(r)); sb.setCharAt(r,ch); l++; r--; } return sb; } private static void swap(List<Integer> li,int i,int j){ int t=li.get(i); li.set(i,li.get(j)); li.set(j,t); } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } static long lcm(long a, long b){ return (a / gcd(a, b)) * b; } private static String decimalToString(int x){ return Integer.toBinaryString(x); } private static String decimalToString(long x){ return Long.toBinaryString(x); } private static boolean isPallindrome(String s,int l,int r){ while(l<r){ if(s.charAt(l)!=s.charAt(r))return false; l++; r--; } return true; } private static boolean isSubsequence(String s, String t) { if (s == null || t == null) return false; Map<Character, List<Integer>> map = new HashMap<>(); //<character, index> //preprocess t for (int i = 0; i < t.length(); i++) { char curr = t.charAt(i); if (!map.containsKey(curr)) { map.put(curr, new ArrayList<Integer>()); } map.get(curr).add(i); } int prev = -1; //index of previous character for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (map.get(c) == null) { return false; } else { List<Integer> list = map.get(c); prev = lessThen( list, prev,false,0,list.size()-1); if (prev == -1) { return false; } prev++; } } return true; } private static StringBuilder removeLeadingZero(StringBuilder sb){ int i=0; while(i<sb.length()&&sb.charAt(i)=='0')i++; // debug("remove "+i); if(i==sb.length())return new StringBuilder(); return new StringBuilder(sb.substring(i,sb.length())); } private static StringBuilder removeEndingZero(StringBuilder sb){ int i=sb.length()-1; while(i>=0&&sb.charAt(i)=='0')i--; // debug("remove "+i); if(i<0)return new StringBuilder(); return new StringBuilder(sb.substring(0,i+1)); } private static int stringToDecimal(String binaryString){ // debug(decimalToString(n<<1)); return Integer.parseInt(binaryString,2); } private static int stringToInt(String s){ return Integer.parseInt(s); } private static String toString(long val){ return String.valueOf(val); } private static void debug(int[][] arr){ for(int i=0;i<arr.length;i++){ err.println(Arrays.toString(arr[i])); } } private static void debug(long[][] arr){ for(int i=0;i<arr.length;i++){ err.println(Arrays.toString(arr[i])); } } private static void debug(List<int[]> arr){ for(int[] a:arr){ err.println(Arrays.toString(a)); } } private static void debug(float[][] arr){ for(int i=0;i<arr.length;i++){ err.println(Arrays.toString(arr[i])); } } private static void debug(double[][] arr){ for(int i=0;i<arr.length;i++){ err.println(Arrays.toString(arr[i])); } } private static void debug(boolean[][] arr){ for(int i=0;i<arr.length;i++){ err.println(Arrays.toString(arr[i])); } } private static void print(String s)throws IOException { out.println(s); } private static void debug(String s)throws IOException { err.println(s); } private static int charToIntS(char c){ return ((((int)(c-'0'))%48)); } private static void print(double s)throws IOException { out.println(s); } private static void print(float s)throws IOException { out.println(s); } private static void print(long s)throws IOException { out.println(s); } private static void print(int s)throws IOException { out.println(s); } private static void debug(double s)throws IOException { err.println(s); } private static void debug(float s)throws IOException { err.println(s); } private static void debug(long s){ err.println(s); } private static void debug(int s){ err.println(s); } private static boolean isPrime(int n){ // Check if number is less than // equal to 1 if (n <= 1) return false; // Check if number is 2 else if (n == 2) return true; // Check if n is a multiple of 2 else if (n % 2 == 0) return false; // If not, then just check the odds for (int i = 3; i <= Math.sqrt(n); i += 2) { if (n % i == 0) return false; } return true; } private static List<List<Integer>> readUndirectedGraph(int n){ List<List<Integer>> graph=new ArrayList<>(); for(int i=0;i<=n;i++){ graph.add(new ArrayList<>()); } for(int i=0;i<n;i++){ int x=sc.nextInt(); int y=sc.nextInt(); graph.get(x).add(y); graph.get(y).add(x); } return graph; } private static List<List<Integer>> readUndirectedGraph(int[][] intervals,int n){ List<List<Integer>> graph=new ArrayList<>(); for(int i=0;i<=n;i++){ graph.add(new ArrayList<>()); } for(int i=0;i<intervals.length;i++){ int x=intervals[i][0]; int y=intervals[i][1]; graph.get(x).add(y); graph.get(y).add(x); } return graph; } private static List<List<Integer>> readDirectedGraph(int[][] intervals,int n){ List<List<Integer>> graph=new ArrayList<>(); for(int i=0;i<=n;i++){ graph.add(new ArrayList<>()); } for(int i=0;i<intervals.length;i++){ int x=intervals[i][0]; int y=intervals[i][1]; graph.get(x).add(y); // graph.get(y).add(x); } return graph; } private static List<List<Integer>> readDirectedGraph(int n){ List<List<Integer>> graph=new ArrayList<>(); for(int i=0;i<=n;i++){ graph.add(new ArrayList<>()); } for(int i=0;i<n;i++){ int x=sc.nextInt(); int y=sc.nextInt(); graph.get(x).add(y); // graph.get(y).add(x); } return graph; } static String[] readStringArray(int n){ String[] arr=new String[n]; for(int i=0;i<n;i++){ arr[i]=sc.next(); } return arr; } private static Map<Character,Integer> freq(String s){ Map<Character,Integer> map=new HashMap<>(); for(char c:s.toCharArray()){ map.put(c,map.getOrDefault(c,0)+1); } return map; } private static Map<Long,Integer> freq(long[] arr){ Map<Long,Integer> map=new HashMap<>(); for(long x:arr){ map.put(x,map.getOrDefault(x,0)+1); } return map; } private static Map<Integer,Integer> freq(int[] arr){ Map<Integer,Integer> map=new HashMap<>(); for(int x:arr){ map.put(x,map.getOrDefault(x,0)+1); } return map; } static boolean[] sieveOfEratosthenes(long n){ boolean prime[] = new boolean[(int)n + 1]; for (int i = 2; 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; } } return prime; } static int[] sieveOfEratosthenesInt(long n){ boolean prime[] = new boolean[(int)n + 1]; Set<Integer> li=new HashSet<>(); for (int i = 1; i <= n; i++){ prime[i] = true; li.add(i); } for (int p = 2; p * p <= n; p++) { if (prime[p] == true){ for (int i = p * p; i <= n; i += p){ li.remove(i); prime[i] = false; } } } int[] arr=new int[li.size()]; int i=0; for(int x:li){ arr[i++]=x; } return arr; } public static long Kadens(List<Long> prices) { long sofar=0; long max_v=0; for(int i=0;i<prices.size();i++){ sofar+=prices.get(i); if (sofar<0) { sofar=0; } max_v=Math.max(max_v,sofar); } return max_v; } public static int Kadens(int[] prices) { int sofar=0; int max_v=0; for(int i=0;i<prices.length;i++){ sofar+=prices[i]; if (sofar<0) { sofar=0; } max_v=Math.max(max_v,sofar); } return max_v; } static boolean isMemberAC(int a, int d, int x){ // If difference is 0, then x must // be same as a. if (d == 0) return (x == a); // Else difference between x and a // must be divisible by d. return ((x - a) % d == 0 && (x - a) / d >= 0); } static boolean isMemberAC(long a, long d, long x){ // If difference is 0, then x must // be same as a. if (d == 0) return (x == a); // Else difference between x and a // must be divisible by d. return ((x - a) % d == 0 && (x - a) / d >= 0); } private static void sort(int[] arr){ int n=arr.length; List<Integer> li=new ArrayList<>(); for(int x:arr){ li.add(x); } Collections.sort(li); for (int i=0;i<n;i++) { arr[i]=li.get(i); } } private static void sortReverse(int[] arr){ int n=arr.length; List<Integer> li=new ArrayList<>(); for(int x:arr){ li.add(x); } Collections.sort(li,Collections.reverseOrder()); for (int i=0;i<n;i++) { arr[i]=li.get(i); } } private static void sort(double[] arr){ int n=arr.length; List<Double> li=new ArrayList<>(); for(double x:arr){ li.add(x); } Collections.sort(li); for (int i=0;i<n;i++) { arr[i]=li.get(i); } } private static void sortReverse(double[] arr){ int n=arr.length; List<Double> li=new ArrayList<>(); for(double x:arr){ li.add(x); } Collections.sort(li,Collections.reverseOrder()); for (int i=0;i<n;i++) { arr[i]=li.get(i); } } private static void sortReverse(long[] arr){ int n=arr.length; List<Long> li=new ArrayList<>(); for(long x:arr){ li.add(x); } Collections.sort(li,Collections.reverseOrder()); for (int i=0;i<n;i++) { arr[i]=li.get(i); } } private static void sort(long[] arr){ int n=arr.length; List<Long> li=new ArrayList<>(); for(long x:arr){ li.add(x); } Collections.sort(li); for (int i=0;i<n;i++) { arr[i]=li.get(i); } } private static long sum(int[] arr){ long sum=0; for(int x:arr){ sum+=x; } return sum; } private static long sum(long[] arr){ long sum=0; for(long x:arr){ sum+=x; } return sum; } private static long evenSumFibo(long n){ long l1=0,l2=2; long sum=0; while (l2<n) { long l3=(4*l2)+l1; sum+=l2; if(l3>n)break; l1=l2; l2=l3; } return sum; } private static void initializeIO(){ try { System.setIn(new FileInputStream("input")); System.setOut(new PrintStream(new FileOutputStream("output.txt"))); System.setErr(new PrintStream(new FileOutputStream("error.txt"))); } catch (Exception e) { System.err.println(e.getMessage()); } } private static int maxOfArray(int[] arr){ int max=Integer.MIN_VALUE; for(int x:arr){ max=Math.max(max,x); } return max; } private static long maxOfArray(long[] arr){ long max=Long.MIN_VALUE; for(long x:arr){ max=Math.max(max,x); } return max; } private static int[][] readIntIntervals(int n,int m){ int[][] arr=new int[n][m]; for(int j=0;j<n;j++){ for(int i=0;i<m;i++){ arr[j][i]=sc.nextInt(); } } return arr; } private static long gcd(long a,long b){ if(b==0)return a; return gcd(b,a%b); } private static int gcd(int a,int b){ if(b==0)return a; return gcd(b,a%b); } private static int[] readIntArray(int n){ int[] arr=new int[n]; for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); } return arr; } private static double[] readDoubleArray(int n){ double[] arr=new double[n]; for(int i=0;i<n;i++){ arr[i]=sc.nextDouble(); } return arr; } private static long[] readLongArray(int n){ long[] arr=new long[n]; for(int i=0;i<n;i++){ arr[i]=sc.nextLong(); } return arr; } private static void print(int[] arr)throws IOException { out.println(Arrays.toString(arr)); } private static void print(long[] arr)throws IOException { out.println(Arrays.toString(arr)); } private static void print(String[] arr)throws IOException { out.println(Arrays.toString(arr)); } private static void print(double[] arr)throws IOException { out.println(Arrays.toString(arr)); } private static void debug(String[] arr){ err.println(Arrays.toString(arr)); } private static void debug(Boolean[][] arr){ for(int i=0;i<arr.length;i++)err.println(Arrays.toString(arr[i])); } private static void debug(int[] arr){ err.println(Arrays.toString(arr)); } private static void debug(long[] arr){ err.println(Arrays.toString(arr)); } static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br=new BufferedReader(new InputStreamReader(System.in)); } String next(){ while(st==null || !st.hasMoreTokens()){ try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } long nextLong(){ return Long.parseLong(next()); } double nextDouble(){ return Double.parseDouble(next()); } String nextLine(){ String str=""; try { str=br.readLine().trim(); } catch (Exception e) { e.printStackTrace(); } return str; } } static class FastWriter { BufferedWriter bw; List<String> list = new ArrayList<>(); Set<String> set = new HashSet<>(); FastWriter() { bw = new BufferedWriter(new OutputStreamWriter(System.out)); } <T> void print(T obj) throws IOException { bw.write(obj.toString()); bw.flush(); } void println() throws IOException { print("\n"); } <T> void println(T obj) throws IOException { print(obj.toString() + "\n"); } void print(int[] arr)throws IOException { for(int x:arr){ print(x+" "); } println(); } void print(long[] arr)throws IOException { for(long x:arr){ print(x+" "); } println(); } void print(double[] arr)throws IOException { for(double x:arr){ print(x+" "); } println(); } void printCharN(char c, int n) throws IOException { for (int i = 0; i < n; i++) { print(c); } } } static class Dsu { int[] parent, size; Dsu(int n) { parent = new int[n + 1]; size = new int[n + 1]; for (int i = 0; i <= n; i++) { parent[i] = i; size[i] = 1; } } private int findParent(int u) { if (parent[u] == u) return u; return parent[u] = findParent(parent[u]); } private boolean union(int u, int v) { // System.out.println("uf "+u+" "+v); int pu = findParent(u); // System.out.println("uf2 "+pu+" "+v); int pv = findParent(v); // System.out.println("uf3 " + u + " " + pv); if (pu == pv) return false; if (size[pu] <= size[pv]) { parent[pu] = pv; size[pv] += size[pu]; } else { parent[pv] = pu; size[pu] += size[pv]; } return true; } } }
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.ArrayList; import java.util.List; import java.util.Scanner; public class _1323A { public static void main(String[] args) { Scanner input = new Scanner(System.in); int t = input.nextInt(); for (int i = 0; i < t; i++) { int n = input.nextInt(); int[] a = new int[n]; List<Integer> indexes = new ArrayList<>(); for (int j = 0; j < n; j++) { a[j] = input.nextInt(); } for (int j = 0; j < n; j++) { if (a[j] % 2 == 0) { indexes.clear(); indexes.add(j + 1); break; } else { if (indexes.size() < 2) { indexes.add(j + 1); } else { break; } } } int count = indexes.size(); if (count < 2 && a[indexes.get(count - 1) - 1] % 2 != 0) { System.out.println("-1"); } else { StringBuilder answer = new StringBuilder(); answer.append(String.format("%d%n", count)); for (int j = 0; j < count - 1; j++) { answer.append(String.format("%d ", indexes.get(j))); } answer.append(indexes.get(count - 1)); System.out.println(answer); } } } }
java
1296
E1
E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2001≤n≤200) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9 abacbecfd OutputCopyYES 001010101 InputCopy8 aaabbcbb OutputCopyYES 01011011 InputCopy7 abcdedc OutputCopyNO InputCopy5 abcde OutputCopyYES 00000
[ "constructive algorithms", "dp", "graphs", "greedy", "sortings" ]
/* It's always like another kick for me to make sure I get what I want to get done, because honestly you never know. */ import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main extends PrintWriter { Main() { super(System.out); } static boolean cases = false; // Solution void solve() { int n = sc.nextInt(); char a[] = sc.readCharArray(n); char ans[] = new char[n]; Arrays.fill(ans, '0'); List<Integer>[] al = new ArrayList[26]; boolean done[] = new boolean[n]; for (int i = 0; i < 26; i++) al[i] = new ArrayList<>(); for (int i = 0; i < n; i++) { boolean ch = false; for (int j = 25; j > (a[i] - 'a'); j--) { for (int k : al[j]) { if (k >= i) break; if (ans[k] == '0' && done[k]) { System.out.println("NO"); return; } ch = true; ans[k] = '1'; done[k] = true; } } if (ch) done[i] = true; al[a[i] - 'a'].add(i); } System.out.println("YES"); System.out.println(new String(ans)); } void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } public static void main(String[] args) { Main obj = new Main(); int c = 1; for (int t = (cases ? sc.nextInt() : 0); t > 1; t--, c++) obj.solve(); obj.solve(); obj.flush(); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } char[] readCharArray(int n) { char a[] = new char[n]; String s = sc.next(); for (int i = 0; i < n; i++) { a[i] = s.charAt(i); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } final int ima = Integer.MAX_VALUE; final int imi = Integer.MIN_VALUE; final long lma = Long.MAX_VALUE; final long lmi = Long.MIN_VALUE; static final long mod = (long) 1e9 + 7; private static final FastScanner sc = new FastScanner(); private PrintWriter out = new PrintWriter(System.out); }
java
1287
A
A. Angry Studentstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt's a walking tour day in SIS.Winter; so tt groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": "A" corresponds to an angry student "P" corresponds to a patient student Such string describes the row from the last to the first student.Every minute every angry student throws a snowball at the next student. Formally, if an angry student corresponds to the character with index ii in the string describing a group then they will throw a snowball at the student that corresponds to the character with index i+1i+1 (students are given from the last to the first student). If the target student was not angry yet, they become angry. Even if the first (the rightmost in the string) student is angry, they don't throw a snowball since there is no one in front of them.Let's look at the first example test. The row initially looks like this: PPAP. Then, after a minute the only single angry student will throw a snowball at the student in front of them, and they also become angry: PPAA. After that, no more students will become angry.Your task is to help SIS.Winter teachers to determine the last moment a student becomes angry for every group.InputThe first line contains a single integer tt — the number of groups of students (1≤t≤1001≤t≤100). The following 2t2t lines contain descriptions of groups of students.The description of the group starts with an integer kiki (1≤ki≤1001≤ki≤100) — the number of students in the group, followed by a string sisi, consisting of kiki letters "A" and "P", which describes the ii-th group of students.OutputFor every group output single integer — the last moment a student becomes angry.ExamplesInputCopy1 4 PPAP OutputCopy1 InputCopy3 12 APPAPPPAPPPP 3 AAP 3 PPA OutputCopy4 1 0 NoteIn the first test; after 11 minute the state of students becomes PPAA. After that, no new angry students will appear.In the second tets, state of students in the first group is: after 11 minute — AAPAAPPAAPPP after 22 minutes — AAAAAAPAAAPP after 33 minutes — AAAAAAAAAAAP after 44 minutes all 1212 students are angry In the second group after 11 minute, all students are angry.
[ "greedy", "implementation" ]
// don't place package name! import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { Scanner op= new Scanner(System.in); int t = op.nextInt(); while(t-->0){ int n = op.nextInt(); String s = op.next(); int count=0; boolean A = false; int max=0; for(int i =0;i<n;i++){ if(s.charAt(i)=='A'){ A = true; if(max<count){ max=count; } count=0; } if(s.charAt(i)=='P'&& A!=false){ count++; } } if(count>max && A!=false){ max=count; } System.out.println(max); } } }
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.PrintWriter; import java.io.BufferedWriter; import java.io.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in Actual solution is at the top * * @author ilyakor */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } static class TaskC { long[] a; public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); a = new long[n]; for (int i = 0; i < n; ++i) { a[i] = in.nextInt(); if (i > 0) { a[i] += a[i - 1]; } } int[] st = new int[n + 10]; int ss = 0; for (int i = 0; i < n; ++i) { while (ss > 0 && cmp(i, st[ss - 1], ss == 1 ? -1 : st[ss - 2])) { --ss; } st[ss++] = i; } int prev = -1; for (int i = 0; i < ss; ++i) { int pos = st[i]; double x = a[pos]; if (prev >= 0) { x -= a[prev]; } x /= (pos - prev); String s = String.format("%.11f", x); for (int j = 0; j < pos - prev; ++j) { out.printLine(s); } prev = pos; } } private boolean cmp(int i, int j, int k) { long yi = a[i], yj = a[j]; long dx1 = i - j, dy1 = yi - yj; long dx2, dy2; if (k == -1) { dx2 = j + 1; dy2 = yj; } else { dx2 = j - k; dy2 = a[j] - a[k]; } return dx1 * dy2 - dx2 * dy1 >= 0; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } static class InputReader { private InputStream stream; private byte[] buffer = new byte[10000]; private int cur; private int count; public InputReader(InputStream stream) { this.stream = stream; } public static boolean isSpace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int read() { if (count == -1) { throw new InputMismatchException(); } try { if (cur >= count) { cur = 0; count = stream.read(buffer); if (count <= 0) { return -1; } } } catch (IOException e) { throw new InputMismatchException(); } return buffer[cur++]; } public int readSkipSpace() { int c; do { c = read(); } while (isSpace(c)); return c; } public int nextInt() { int sgn = 1; int c = readSkipSpace(); if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res = res * 10 + c - '0'; c = read(); } while (!isSpace(c)); res *= sgn; return res; } } }
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.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); int testCases = input.nextInt(); for(int index = 0; index < testCases; index++) { int totalNums = input.nextInt(); int[] nums = new int[totalNums]; for(int counter = 0; counter < totalNums; counter++) { nums[counter] = input.nextInt(); } Arrays.sort(nums); for(int counter = nums.length-1; counter >= 0; counter--) { System.out.print(nums[counter] + " "); } System.out.println(); } } }
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.*; import java.io.*; import java.lang.*; import java.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.StringTokenizer; import java.math.BigInteger; import static java.lang.Math.max; public class HelloWorld { public static void main(String[] args) throws IOException { Scanner input=new Scanner(System.in); //static FastReader input=new FastReader(); //static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int t=input.nextInt(); while(t>0) { int n,i,m,j,k,f; long count=0,a,b,x,y,s1,s2,s3,s4,s; a=input.nextInt(); b=input.nextInt(); x=input.nextInt(); y=input.nextInt(); x++; y++; //ArrayList<Long>ara= new ArrayList<>(); //long ara[]=new long[i]; //Collections.sort(ara1); s1=(x-1)*b; s2=a*(y-1); s3=(a-x)*b; s4=a*(b-y); s=max(s4,max(s3,max(s2,s1))); System.out.println(s); //System.out.println(s1+" "+s2+" "+s3+" "+s4); t--; } input.close(); System.out.close(); } /*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()); } int[] readIntArray(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; } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }*/ }
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 c1311; // // Codeforces Round #624 (Div. 3) 2020-02-24 06:35 // E. Construct the Binary Tree // https://codeforces.com/contest/1311/problem/E // time limit per test 2 seconds; memory limit per test 256 megabytes // public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*' // // You are given two integers n and d. You need to construct a rooted binary tree consisting of n // vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d. // // A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A // parent of a vertex v is the last different from v vertex on the path from the root to the vertex // v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of // vertex v are all vertices for which v is the parent. The binary tree is such a tree that no // vertex has more than 2 children. // // You have to answer t independent test cases. // // Input // // The first line of the input contains one integer t (1 <= t <= 1000) -- the number of test cases. // // The only line of each test case contains two integers n and d (2 <= 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 n and the sum of d both does not exceed 5000 (\sum n <= 5000, // \sum d <= 5000). // // Output // // For 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-1 integers p_2, p_3, ..., p_n in the // second line, where p_i is the parent of the vertex i. Note that the sequence of parents you print // should describe some binary tree. // // Example /* input: 3 5 7 10 19 10 18 output: YES 1 2 1 3 YES 1 2 3 3 9 9 2 1 6 NO */ // Note // // Pictures corresponding to the first and the second test cases of the example: // // https://espresso.codeforces.com/94d2346ee349d5dcb535dcd106cfbaa389c1b21c.png // // https://espresso.codeforces.com/c6a4bb4f01e3c79a7c34c54ab163323733690f43.png // import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Random; import java.util.StringTokenizer; public class C1311E { static final int MOD = 998244353; static final Random RAND = new Random(); static int[] solve(int n, int d) { int[] ans = new int[n-1]; // compute the minimal possible value // 0 1 1 2 2 2 2 3 3 3 3 3 3 3 3 4 4 ... int h = 0; int min = 0; int m = 1; while ((1 << (h + 1)) - 1 < n) { h++; min += (1 << h) * h; m += (1 << h); } min -= (m - n) * h; int max = n * (n-1) / 2; if (test) System.out.format("n:%d d:%d h:%d m:%d min:%d max:%d\n", n, d, h, m, min, max); if (d < min || d > max) { return null; } Node[] nodes = new Node[n+1]; Node root = new Node(1); Queue<Node> q = new LinkedList<>(); q.add(root); nodes[1] = root; int id = 1; while (!q.isEmpty()) { Node v = q.poll(); if (id < n) { Node x = new Node(++id, v); nodes[x.v] = x; v.left = x; q.add(x); } if (id < n) { Node x = new Node(++id, v); nodes[x.v] = x; v.right = x; q.add(x); } } dfsSubCnt(root); List<Node>[] levels = new ArrayList[n]; for (int i = 0; i < n; i++) { levels[i] = new ArrayList<>(); } int maxd = refreshLevels(root, levels); int ib = 1; int sum = sumDepth(root); int offset = 1; while (sum < d) { // System.out.format(" sum:%d ib:%d\n", sum, ib); while (levels[ib].size() <= offset) { ib++; } Node x = levels[ib].get(offset); // look for new parent of x Node p = null; int gain = -1; for (int ie = maxd - 1; ie >= ib; ie--) { myAssert(levels[ie].get(0).depth == ie); gain = (ie - x.p.depth) * x.subcnt; if (sum + gain > d) { continue; } for (Node v : levels[ie]) { if (v.v != x.v && (v.left == null || v.right == null)) { // v must not be a descendant of x boolean ok = true; Node y = v; while (y != null) { if (y.v == x.v) { ok = false; break; } y = y.p; } if (ok) { p = v; break; } } } if (p != null) { break; } } if (p == null) { ib++; continue; } if (test) System.out.format(" sum:%d ib:%d x:%s p:%s gain:%d\n", sum, ib, x, p, gain); // if we move x under p, we gain total depth of: myAssert(gain > 0); myAssert(sum + gain <= d); myAssert(p.depth >= x.depth); Node y = x.p; while (y != null) { y.subcnt -= x.subcnt; y = y.p; } if (x.p.left != null && x.p.left.v == x.v) { x.p.left = null; } else { x.p.right = null; } x.p = p; x.depth = p.depth + 1; if (p.left == null) { p.left = x; } else { p.right = x; } y = p; while (y != null) { y.subcnt += x.subcnt; y = y.p; } sum += gain; maxd = refreshLevels(root, levels); dfsSubCnt(root); } for (int v = 2; v <= n; v++) { ans[v-2] = nodes[v].p.v; } return ans; } static int refreshLevels(Node root, List<Node>[] levels) { Queue<Node> q = new LinkedList<>(); q.add(root); int depth = 0; while (!q.isEmpty()) { int size = q.size(); levels[depth].clear(); for (int i = 0; i < size; i++) { Node v = q.poll(); // correct v's depth v.depth = depth; levels[v.depth].add(v); if (v.left != null) { q.add(v.left); } if (v.right != null) { q.add(v.right); } } depth++; } if (depth < levels.length) { levels[depth].clear(); } for (int i = 0; i < depth; i++) { if (!levels[i].isEmpty()) { if (test) System.out.format(" depth:%d %s\n", i, levels[i].toString()); } } return depth; } static int sumDepth(Node root) { Queue<Node> q = new LinkedList<>(); q.add(root); int sum = 0; int depth = 0; while (!q.isEmpty()) { int size = q.size(); for (int i = 0; i < size; i++) { Node v = q.poll(); myAssert(v.depth == depth); sum += depth; if (v.left != null) { q.add(v.left); } if (v.right != null) { q.add(v.right); } } depth++; } return sum; } static void dfsSubCnt(Node root) { if (root == null) { return; } dfsSubCnt(root.left); dfsSubCnt(root.right); root.subcnt = 1 + (root.left == null ? 0 : root.left.subcnt) + (root.right == null ? 0 : root.right.subcnt); } static class Node { int v; Node p; Node left; Node right; // depth of v in the tree int depth; // number of node in the subtree rooted at v (inclusive) int subcnt; public Node(int v) { this.v = v; this.subcnt = 1; } public Node(int v, Node p) { this.v = v; this.p = p; this.depth = p.depth + 1; this.subcnt = 1; } @Override public String toString() { return Integer.toString(v); } } static void test(int n, int d) { int[] ans = solve(n, d); if (ans == null) { System.out.format(" %d %d => NO\n", n, d); } else { StringBuilder sb = new StringBuilder(); for (int v : ans) { sb.append(v); sb.append(' '); } System.out.format(" %d %d => YES %s\n", n, d, sb.toString()); } } static boolean test = false; static void doTest() { if (!test) { return; } long t0 = System.currentTimeMillis(); test(36, 165); for (int t = 0; t < 20000; t++) { int n = 2 + RAND.nextInt(50); int d = 2 + RAND.nextInt(5000); test(n, d); } /* test(11, 27); test(12, 32); test(11, 39); test(12, 24); test(12, 55); test(11, 23); test(5, 6); test(11, 51); test(12, 25); test(11, 30); test(9, 20); test(9, 16); test(10, 37); */ System.out.format("%d msec\n", System.currentTimeMillis() - t0); System.exit(0); } public static void main(String[] args) { doTest(); MyScanner in = new MyScanner(); int T = in.nextInt(); for (int t = 1; t <= T; t++) { int n = in.nextInt(); int d = in.nextInt(); int[] ans = solve(n, d); output(ans); } } static void output(int[] a) { if (a == null) { System.out.println("NO"); return; } StringBuilder sb = new StringBuilder(); sb.append("YES\n"); for (int v : a) { sb.append(v); sb.append(' '); if (sb.length() > 4000) { System.out.print(sb.toString()); sb.setLength(0); } } System.out.println(sb.toString()); } static void myAssert(boolean cond) { if (!cond) { throw new RuntimeException("Unexpected"); } } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { try { final String USERDIR = System.getProperty("user.dir"); String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", ""); cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname; final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in"); br = new BufferedReader(new InputStreamReader(fin.exists() ? new FileInputStream(fin) : System.in)); } catch (Exception e) { br = new BufferedReader(new InputStreamReader(System.in)); } } public String next() { try { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
java
1294
D
D. MEX maximizingtime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputRecall that MEX of an array is a minimum non-negative integer that does not belong to the array. Examples: for the array [0,0,1,0,2][0,0,1,0,2] MEX equals to 33 because numbers 0,10,1 and 22 are presented in the array and 33 is the minimum non-negative integer not presented in the array; for the array [1,2,3,4][1,2,3,4] MEX equals to 00 because 00 is the minimum non-negative integer not presented in the array; for the array [0,1,4,3][0,1,4,3] MEX equals to 22 because 22 is the minimum non-negative integer not presented in the array. You are given an empty array a=[]a=[] (in other words, a zero-length array). You are also given a positive integer xx.You are also given qq queries. The jj-th query consists of one integer yjyj and means that you have to append one element yjyj to the array. The array length increases by 11 after a query.In one move, you can choose any index ii and set ai:=ai+xai:=ai+x or ai:=ai−xai:=ai−x (i.e. increase or decrease any element of the array by xx). The only restriction is that aiai cannot become negative. Since initially the array is empty, you can perform moves only after the first query.You have to maximize the MEX (minimum excluded) of the array if you can perform any number of such operations (you can even perform the operation multiple times with one element).You have to find the answer after each of qq queries (i.e. the jj-th answer corresponds to the array of length jj).Operations are discarded before each query. I.e. the array aa after the jj-th query equals to [y1,y2,…,yj][y1,y2,…,yj].InputThe first line of the input contains two integers q,xq,x (1≤q,x≤4⋅1051≤q,x≤4⋅105) — the number of queries and the value of xx.The next qq lines describe queries. The jj-th query consists of one integer yjyj (0≤yj≤1090≤yj≤109) and means that you have to append one element yjyj to the array.OutputPrint the answer to the initial problem after each query — for the query jj print the maximum value of MEX after first jj queries. Note that queries are dependent (the array changes after each query) but operations are independent between queries.ExamplesInputCopy7 3 0 1 2 2 0 0 10 OutputCopy1 2 3 3 4 4 7 InputCopy4 3 1 2 1 2 OutputCopy0 0 0 0 NoteIn the first example: After the first query; the array is a=[0]a=[0]: you don't need to perform any operations, maximum possible MEX is 11. After the second query, the array is a=[0,1]a=[0,1]: you don't need to perform any operations, maximum possible MEX is 22. After the third query, the array is a=[0,1,2]a=[0,1,2]: you don't need to perform any operations, maximum possible MEX is 33. After the fourth query, the array is a=[0,1,2,2]a=[0,1,2,2]: you don't need to perform any operations, maximum possible MEX is 33 (you can't make it greater with operations). After the fifth query, the array is a=[0,1,2,2,0]a=[0,1,2,2,0]: you can perform a[4]:=a[4]+3=3a[4]:=a[4]+3=3. The array changes to be a=[0,1,2,2,3]a=[0,1,2,2,3]. Now MEX is maximum possible and equals to 44. After the sixth query, the array is a=[0,1,2,2,0,0]a=[0,1,2,2,0,0]: you can perform a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3. The array changes to be a=[0,1,2,2,3,0]a=[0,1,2,2,3,0]. Now MEX is maximum possible and equals to 44. After the seventh query, the array is a=[0,1,2,2,0,0,10]a=[0,1,2,2,0,0,10]. You can perform the following operations: a[3]:=a[3]+3=2+3=5a[3]:=a[3]+3=2+3=5, a[4]:=a[4]+3=0+3=3a[4]:=a[4]+3=0+3=3, a[5]:=a[5]+3=0+3=3a[5]:=a[5]+3=0+3=3, a[5]:=a[5]+3=3+3=6a[5]:=a[5]+3=3+3=6, a[6]:=a[6]−3=10−3=7a[6]:=a[6]−3=10−3=7, a[6]:=a[6]−3=7−3=4a[6]:=a[6]−3=7−3=4. The resulting array will be a=[0,1,2,5,3,6,4]a=[0,1,2,5,3,6,4]. Now MEX is maximum possible and equals to 77.
[ "data structures", "greedy", "implementation", "math" ]
import 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 D_MEX_maximizing { static long mod = Long.MAX_VALUE; static OutputStream outputStream = System.out; static PrintWriter out = new PrintWriter(outputStream); static FastReader f = new FastReader(); public static void main(String[] args) { int t = 1; while(t-- > 0){ solve(); } out.close(); } public static void solve() { int q = f.nextInt(); int x = f.nextInt(); int freq[] = new int[x]; int mex = 0; for(int i = 0; i < q; i++) { int num = f.nextInt(); int key = num%x; freq[key]++; int req = mex%x; while(freq[req] > 0) { freq[req]--; mex++; req = mex%x; } out.println(mex); } } // Sort an array public static void sort(int arr[]) { ArrayList<Integer> al = new ArrayList<>(); for(int i: arr) { al.add(i); } Collections.sort(al); for(int i = 0; i < arr.length; i++) { arr[i] = al.get(i); } } // Find all divisors of n public static void allDivisors(int n) { for(int i = 1; i*i <= n; i++) { if(n%i == 0) { System.out.println(i + " "); if(i != n/i) { System.out.println(n/i + " "); } } } } // Check if n is prime or not public static boolean isPrime(int n) { if(n < 1) return false; if(n == 2 || n == 3) return true; if(n % 2 == 0 || n % 3 == 0) return false; for(int i = 5; i*i <= n; i += 6) { if(n % i == 0 || n % (i+2) == 0) { return false; } } return true; } // Find gcd of a and b public static long gcd(long a, long b) { long dividend = a > b ? a : b; long divisor = a < b ? a : b; while(divisor > 0) { long reminder = dividend % divisor; dividend = divisor; divisor = reminder; } return dividend; } // Find lcm of a and b public static long lcm(long a, long b) { long lcm = gcd(a, b); long hcf = (a * b) / lcm; return hcf; } // Find factorial in O(n) time public static long fact(int n) { long res = 1; for(int i = 2; i <= n; i++) { res = res * i; } return res; } // Find power in O(logb) time public static long power(long a, long b) { long res = 1; while(b > 0) { if((b&1) == 1) { res = (res * a)%mod; } a = (a * a)%mod; b >>= 1; } return res; } // Find nCr public static long nCr(int n, int r) { if(r < 0 || r > n) { return 0; } long ans = fact(n) / (fact(r) * fact(n-r)); return ans; } // Find nPr public static long nPr(int n, int r) { if(r < 0 || r > n) { return 0; } long ans = fact(n) / fact(r); return ans; } // sort all characters of a string public static String sortString(String inputString) { char tempArray[] = inputString.toCharArray(); Arrays.sort(tempArray); return new String(tempArray); } // User defined class for fast I/O static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } boolean hasNext() { if (st != null && st.hasMoreTokens()) { return true; } String tmp; try { br.mark(1000); tmp = br.readLine(); if (tmp == null) { return false; } br.reset(); } catch (IOException e) { return false; } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } boolean nextBoolean() { return Boolean.parseBoolean(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextArray(int n) { int[] a = new int[n]; for(int i=0; i<n; i++) { a[i] = nextInt(); } return a; } } } /** Dec Char Dec Char Dec Char Dec Char --------- --------- --------- ---------- 0 NUL (null) 32 SPACE 64 @ 96 ` 1 SOH (start of heading) 33 ! 65 A 97 a 2 STX (start of text) 34 " 66 B 98 b 3 ETX (end of text) 35 # 67 C 99 c 4 EOT (end of transmission) 36 $ 68 D 100 d 5 ENQ (enquiry) 37 % 69 E 101 e 6 ACK (acknowledge) 38 & 70 F 102 f 7 BEL (bell) 39 ' 71 G 103 g 8 BS (backspace) 40 ( 72 H 104 h 9 TAB (horizontal tab) 41 ) 73 I 105 i 10 LF (NL line feed, new line) 42 * 74 J 106 j 11 VT (vertical tab) 43 + 75 K 107 k 12 FF (NP form feed, new page) 44 , 76 L 108 l 13 CR (carriage return) 45 - 77 M 109 m 14 SO (shift out) 46 . 78 N 110 n 15 SI (shift in) 47 / 79 O 111 o 16 DLE (data link escape) 48 0 80 P 112 p 17 DC1 (device control 1) 49 1 81 Q 113 q 18 DC2 (device control 2) 50 2 82 R 114 r 19 DC3 (device control 3) 51 3 83 S 115 s 20 DC4 (device control 4) 52 4 84 T 116 t 21 NAK (negative acknowledge) 53 5 85 U 117 u 22 SYN (synchronous idle) 54 6 86 V 118 v 23 ETB (end of trans. block) 55 7 87 W 119 w 24 CAN (cancel) 56 8 88 X 120 x 25 EM (end of medium) 57 9 89 Y 121 y 26 SUB (substitute) 58 : 90 Z 122 z 27 ESC (escape) 59 ; 91 [ 123 { 28 FS (file separator) 60 < 92 \ 124 | 29 GS (group separator) 61 = 93 ] 125 } 30 RS (record separator) 62 > 94 ^ 126 ~ 31 US (unit separator) 63 ? 95 _ 127 DEL */ // (a/b)%mod == (a * moduloInverse(b)) % mod; // moduloInverse(b) = power(b, mod-2);
java
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.*; import java.math.*; import java.util.*; public class Main { static PrintWriter pw; static Scanner sc; static long ceildiv(long x, long y) { return (x+y-1)/y; } static int mod(long x, int m) { return (int)((x%m+m)%m); } static void put(HashMap<Integer, Integer> map, Integer p){if(map.containsKey(p)) map.replace(p, map.get(p)+1); else map.put(p, 1); } static void rem(HashMap<Integer, Integer> map, Integer p){ if(map.get(p)==1) map.remove(p);else map.replace(p, map.get(p)-1); } static void printf(double x, int dig){ String s="%."+dig+"f"; pw.printf(s, x); } static int Int(boolean x){ return x?1:0; } static final int inf=(int)1e9, mod=998244353; static final long infL=inf*1l*inf; static final double eps=1e-9; public static long gcd(long x, long y) { return y==0? x: gcd(y, x%y); } public static void main(String[] args) throws Exception{ sc=new Scanner(System.in); pw=new PrintWriter(System.out); int t=sc.nextInt(); while(t-->0) testcase(); pw.close(); } static void testcase() throws IOException{ long x=sc.nextLong(); int n=sc.nextInt(), cnt[]=new int[63]; double log2=Math.log(2); for (int i = 0; i < n; i++) cnt[round(Math.log(sc.nextInt())/log2)]++; int ans=0; for (int i = 0; i < 63; i++) { long bit=(1l<<i)&x; if(less(bit, cnt, i)) continue; int cost=more(bit, cnt, i); if(cost==-1){ ans=-1; break; } ans+=cost; cnt[i]--; } pw.println(ans); } static boolean less(long x, int[] cnt, int idx){ if(x==0) return true; for (int i = idx; i >=0 && x>0; i--) { long bit=1l<<i, need=x/bit, min=Math.min(need, cnt[i]); cnt[i]-=(int)min; x-=min*bit; } return x==0; } static int more(long x, int[] cnt, int idx){ int ans=0; for (int i = idx+1; i < 63; i++) { if(cnt[i]>0){ for (int j = i-1; j >= idx; j--) { cnt[j+1]--; cnt[j]+=2; ans++; } break; } } return ans>0 ? ans : -1; } static int round(double x){ if(x%1>0.9) return (int) x+1; return (int) x; } static void printArr(int[] arr) { for (int i = 0; i < arr.length; i++) pw.print(arr[i] + " "); pw.println(); } static void printArr(long[] arr) { for (int i = 0; i < arr.length; i++) pw.print(arr[i] + " "); pw.println(); } static void printArr(double[] arr) { for (int i = 0; i < arr.length; i++) pw.print(arr[i] + " "); pw.println(); } static void printArr(Integer[] arr) { for (int i = 0; i < arr.length; i++) pw.print(arr[i] + " "); pw.println(); } static void printArr(ArrayList list) { for (int i = 0; i < list.size(); i++) pw.print(list.get(i)+" "); pw.println(); } static void printArr(boolean[] arr) { StringBuilder sb=new StringBuilder(); for(boolean b: arr) sb.append(Int(b)); pw.println(sb); } 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 { return Double.parseDouble(next()); } public int[] nextDigits() throws IOException{ String s=nextLine(); int[] arr=new int[s.length()]; for(int i=0; i<arr.length; i++) arr[i]=s.charAt(i)-'0'; return arr; } public int[] nextArr(int n) throws IOException { int[] arr = new int[n]; for (int i = 0; i < arr.length; i++) arr[i] = nextInt(); return arr; } public Integer[] nextsort(int n) throws IOException{ Integer[] arr=new Integer[n]; for(int i=0; i<n; i++) arr[i]=nextInt(); return arr; } public Pair nextPair() throws IOException{ return new Pair(nextInt(), nextInt()); } public long[] nextLongArr(int n) throws IOException{ long[] arr=new long[n]; for (int i = 0; i < n; i++) arr[i]=sc.nextLong(); return arr; } public Pair[] nextPairArr(int n) throws IOException{ Pair[] arr=new Pair[n]; for(int i=0; i<n; i++) arr[i]=nextPair(); return arr; } public boolean ready() throws IOException { return br.ready(); } } static class Pair implements Comparable<Pair>{ int x; int y; public Pair(int x, int y) { this.x=x; this.y=y; } public boolean contains(int a){ return x==a || y==a; } public int hashCode() { return (this.x*1000000000+this.y); } public int compareTo(Pair p){ if(x==p.x) return y-p.y; return x-p.x; } public boolean equals(Object obj) { if (obj == null) { return false; } if (this.getClass() != obj.getClass()) { return false; } Pair p = (Pair) obj; return this.x==p.x && this.y==p.y; } public Pair clone(){ return new Pair(x, y); } public String toString(){ return this.x+" "+this.y; } public void add(Pair p){ x+=p.x; y+=p.y; } public Pair negative(){ return new Pair(-x, -y); } } static class LP implements Comparable<LP>{ long x, y; public LP(long a, long b){ x=a; y=b; } public void add(LP p){ x+=p.x; y+=p.y; } public boolean equals(LP p){ return p.x==x && y==p.y; } public String toString(){ return this.x+" "+this.y; } public int compareTo(LP p){ int a=Long.compare(x, p.x); if(a!=0) return a; return Long.compare(y, p.y); } } static class Triple implements Comparable<Triple>{ int x, y, z; public Triple(int a, int b, int c){ x=a; y=b; z=c; } public int compareTo(Triple t){ if(this.y!=t.y) return y-t.y; return x-t.x; } public String toString(){ return x+" "+y+" "+z; } } // static class MaxSegmentTree{ // int n; // long[] tree; // public MaxSegmentTree(int len, long[] arr){ // n=len; // build(0, 0, n-1, arr); // } // public void build(int i, int l, int r, long[] arr){ // if(l==r){ // tree[i]=arr[l]; // return; // } // int mid=(l+r)/2, left=2*i+1, right=2*i+2; // build(left, l, mid, arr); // build(right, mid+1, r, arr); // tree[i]=Math.max(left, right); // } // public int query(int i){ // return query(0, 0, n-1, 0, i); // } // public int query(int node, int i, int j, int l, int r){ // if(l>j || r<i) // return -1; // // } // } static class SegmentTree { int n, size[]; long[] tree; public SegmentTree(int len) { n = len; tree=new long[2*n-1]; size=new int[2*n-1]; } public void set(int i, long x){ i+=n-1; tree[i]=x; size[i]++; i=(i-1)/2; while(true){ size[i]++; tree[i]=tree[i*2+1] + tree[i*2+2]; if(i==0) break; i=(i-1)/2; } } public long query(int x){ return query(0, 0, n-1, x+1, n-1); } public long query(int node, int i, int j, int l, int r){ if(j<l || i>r) return 0; if(i>=l && j<=r) return tree[node]; int mid=(i+j)/2, left=node*2+1, right=node*2+2; return query(left, i, mid, l, r) + query(right, mid+1, j, l, r); } public int size(int idx){ return size(0, 0, n-1, idx+1, n-1); } public int size(int node, int i, int j, int l, int r){ if(i>r || j<l) return 0; if(i>=l && j<=r) return size[node]; int mid=(i+j)/2, left=node*2+1, right=node*2+2; return size(left, i, mid, l, r)+size(right, mid+1, j, l, r); } } }
java
1301
D
D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to: in the case 'U' to the cell (i−1,j)(i−1,j); in the case 'D' to the cell (i+1,j)(i+1,j); in the case 'L' to the cell (i,j−1)(i,j−1); in the case 'R' to the cell (i,j+1)(i,j+1); He wants to run exactly kk kilometers, so he wants to make exactly kk moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4 OutputCopyYES 2 2 R 2 L InputCopy3 3 1000000000 OutputCopyNO InputCopy3 3 8 OutputCopyYES 3 2 R 2 D 1 LLRR InputCopy4 4 9 OutputCopyYES 1 3 RLD InputCopy3 4 16 OutputCopyYES 8 3 R 3 L 1 D 3 R 1 D 1 U 3 L 1 D NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
[ "constructive algorithms", "graphs", "implementation" ]
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); if (k > (4 * n * m - 2 * n - 2 * m)) { out.println("NO"); return; } out.println("YES"); int cr = 0, st = 0; StringBuilder sb = new StringBuilder(); if (n == 1) { if (k < m) { out.println("1\n" + k + " R"); } out.println("2\n" + (m - 1) + " R"); out.println(k - (m - 1) + " L"); return; } if (k < n) { out.println(1); out.println(k + " D\n"); return; } sb.append((n - 1) + " D\n"); if (k <= 2 * (n - 1)) { out.println(2); out.println((n - 1) + " D"); out.println(k - n + 1 + " U"); return; } sb.append((n - 1) + " U\n"); k -= 2 * (n - 1); st = 2; for (int i = 1; i < m; ++i) { if (3 * (n - 1) >= k) { if (k / 3 > 0) { sb.append(k / 3 + " RDL\n"); st += 1; k -= k / 3 * 3; } if (k > 0) { st++; k--; sb.append("1 R\n"); } if (k > 0) { st++; k--; sb.append("1 D\n"); } break; } st++; sb.append((n - 1) + " RDL\n"); k -= 3 * (n - 1); st++; k--; sb.append("1 R\n"); if (k == 0) { break; } st++; if (k < n) { sb.append(k + " U\n"); k = 0; break; } sb.append(n - 1 + " U\n"); k -= n - 1; } if (k > 0) { st++; sb.append(k + " L\n"); } out.println(st); out.println(sb.toString()); } } }
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 static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; public class B_String_Modification { static long mod = Long.MAX_VALUE; public static void main(String[] args) { OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); FastReader f = new FastReader(); int t = f.nextInt(); while(t-- > 0){ solve(f, out); } out.close(); } public static void solve(FastReader f, PrintWriter out) { int n = f.nextInt(); String s = f.nextLine(); StringBuilder ansString = new StringBuilder(s); int ansK = 1; for(int i = 2; i <= n; i++) { StringBuilder curr = new StringBuilder(); curr.append(s.substring(i-1)); if((n-i+1)%2 == 0) { curr.append(s.substring(0, i-1)); } else { curr.append(new StringBuilder(s.substring(0, i-1)).reverse()); } if(curr.compareTo(ansString) < 0) { ansString = curr; ansK = i; } } out.println(ansString); out.println(ansK); } // Sort an array public static void sort(int arr[]) { ArrayList<Integer> al = new ArrayList<>(); for(int i: arr) { al.add(i); } Collections.sort(al); for(int i = 0; i < arr.length; i++) { arr[i] = al.get(i); } } // Find all divisors of n public static void allDivisors(int n) { for(int i = 1; i*i <= n; i++) { if(n%i == 0) { System.out.println(i + " "); if(i != n/i) { System.out.println(n/i + " "); } } } } // Check if n is prime or not public static boolean isPrime(int n) { if(n < 1) return false; if(n == 2 || n == 3) return true; if(n % 2 == 0 || n % 3 == 0) return false; for(int i = 5; i*i <= n; i += 6) { if(n % i == 0 || n % (i+2) == 0) { return false; } } return true; } // Find gcd of a and b public static long gcd(long a, long b) { long dividend = a > b ? a : b; long divisor = a < b ? a : b; while(divisor > 0) { long reminder = dividend % divisor; dividend = divisor; divisor = reminder; } return dividend; } // Find lcm of a and b public static long lcm(long a, long b) { long lcm = gcd(a, b); long hcf = (a * b) / lcm; return hcf; } // Find factorial in O(n) time public static long fact(int n) { long res = 1; for(int i = 2; i <= n; i++) { res = res * i; } return res; } // Find power in O(logb) time public static long power(long a, long b) { long res = 1; while(b > 0) { if((b&1) == 1) { res = (res * a)%mod; } a = (a * a)%mod; b >>= 1; } return res; } // Find nCr public static long nCr(int n, int r) { if(r < 0 || r > n) { return 0; } long ans = fact(n) / (fact(r) * fact(n-r)); return ans; } // Find nPr public static long nPr(int n, int r) { if(r < 0 || r > n) { return 0; } long ans = fact(n) / fact(r); return ans; } // sort all characters of a string public static String sortString(String inputString) { char tempArray[] = inputString.toCharArray(); Arrays.sort(tempArray); return new String(tempArray); } // User defined class for fast I/O static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } boolean hasNext() { if (st != null && st.hasMoreTokens()) { return true; } String tmp; try { br.mark(1000); tmp = br.readLine(); if (tmp == null) { return false; } br.reset(); } catch (IOException e) { return false; } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } boolean nextBoolean() { return Boolean.parseBoolean(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextArray(int n) { int[] a = new int[n]; for(int i=0; i<n; i++) { a[i] = nextInt(); } return a; } } } /** Dec Char Dec Char Dec Char Dec Char --------- --------- --------- ---------- 0 NUL (null) 32 SPACE 64 @ 96 ` 1 SOH (start of heading) 33 ! 65 A 97 a 2 STX (start of text) 34 " 66 B 98 b 3 ETX (end of text) 35 # 67 C 99 c 4 EOT (end of transmission) 36 $ 68 D 100 d 5 ENQ (enquiry) 37 % 69 E 101 e 6 ACK (acknowledge) 38 & 70 F 102 f 7 BEL (bell) 39 ' 71 G 103 g 8 BS (backspace) 40 ( 72 H 104 h 9 TAB (horizontal tab) 41 ) 73 I 105 i 10 LF (NL line feed, new line) 42 * 74 J 106 j 11 VT (vertical tab) 43 + 75 K 107 k 12 FF (NP form feed, new page) 44 , 76 L 108 l 13 CR (carriage return) 45 - 77 M 109 m 14 SO (shift out) 46 . 78 N 110 n 15 SI (shift in) 47 / 79 O 111 o 16 DLE (data link escape) 48 0 80 P 112 p 17 DC1 (device control 1) 49 1 81 Q 113 q 18 DC2 (device control 2) 50 2 82 R 114 r 19 DC3 (device control 3) 51 3 83 S 115 s 20 DC4 (device control 4) 52 4 84 T 116 t 21 NAK (negative acknowledge) 53 5 85 U 117 u 22 SYN (synchronous idle) 54 6 86 V 118 v 23 ETB (end of trans. block) 55 7 87 W 119 w 24 CAN (cancel) 56 8 88 X 120 x 25 EM (end of medium) 57 9 89 Y 121 y 26 SUB (substitute) 58 : 90 Z 122 z 27 ESC (escape) 59 ; 91 [ 123 { 28 FS (file separator) 60 < 92 \ 124 | 29 GS (group separator) 61 = 93 ] 125 } 30 RS (record separator) 62 > 94 ^ 126 ~ 31 US (unit separator) 63 ? 95 _ 127 DEL */ // (a/b)%mod == (a * moduloInverse(b)) % mod; // moduloInverse(b) = power(b, mod-2);
java
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 static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; public class B_Count_Subrectangles { static long mod = Long.MAX_VALUE; public static void main(String[] args) { OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); FastReader f = new FastReader(); int t = 1; while(t-- > 0){ solve(f, out); } out.close(); } public static void solve(FastReader f, PrintWriter out) { int n = f.nextInt(); int m = f.nextInt(); int k = f.nextInt(); int a[] = f.nextArray(n); int b[] = f.nextArray(m); int freqA[] = freqArr(a); int freqB[] = freqArr(b); ArrayList<Pair> arrli = allDivisors(n, m, k); long ans = 0; for(int i = 0; i < arrli.size(); i++) { // ans += func(a, arrli.get(i).row) * func(b, arrli.get(i).col); ans += freqA[arrli.get(i).row] * freqB[arrli.get(i).col]; } out.println(ans); } static class Pair { int row; int col; public Pair(int row, int col) { this.row = row; this.col = col; } } public static int[] freqArr(int arr[]) { int n = arr.length; int freq[] = new int[n+1]; int count1 = 0; for(int i = 0; i < n; i++) { if(arr[i] == 1) { count1++; } else { for(int j = 1; j <= count1; j++) { freq[j] += (count1-j+1); } count1 = 0; } } for(int j = 1; j <= count1; j++) { freq[j] += (count1-j+1); } return freq; } // public static int func(int arr[], int x) { // int n = arr.length; // int ans = 0; // int count1 = 0; // for(int i = 0; i < x; i++) { // if(arr[i] == 1) { // count1++; // } // } // if(count1 == x) { // ans++; // } // for(int i = x; i < n; i++) { // count1 += arr[i]; // count1 -= arr[i-x]; // if(count1 == x) { // ans++; // } // } // return ans; // } // Sort an array public static void sort(int arr[]) { ArrayList<Integer> al = new ArrayList<>(); for(int i: arr) { al.add(i); } Collections.sort(al); for(int i = 0; i < arr.length; i++) { arr[i] = al.get(i); } } // Find all divisors of n public static ArrayList<Pair> allDivisors(int n, int m, int k) { ArrayList<Pair> arrli = new ArrayList<>(); for(int i = 1; i*i <= k; i++) { if(k%i == 0) { if(i <= n && k/i <= m) { arrli.add(new Pair(i, k/i)); } if(i != k/i && k/i <= n && i <= m) { arrli.add(new Pair(k/i, i)); } } } return arrli; } // Check if n is prime or not public static boolean isPrime(int n) { if(n < 1) return false; if(n == 2 || n == 3) return true; if(n % 2 == 0 || n % 3 == 0) return false; for(int i = 5; i*i <= n; i += 6) { if(n % i == 0 || n % (i+2) == 0) { return false; } } return true; } // Find gcd of a and b public static long gcd(long a, long b) { long dividend = a > b ? a : b; long divisor = a < b ? a : b; while(divisor > 0) { long reminder = dividend % divisor; dividend = divisor; divisor = reminder; } return dividend; } // Find lcm of a and b public static long lcm(long a, long b) { long lcm = gcd(a, b); long hcf = (a * b) / lcm; return hcf; } // Find factorial in O(n) time public static long fact(int n) { long res = 1; for(int i = 2; i <= n; i++) { res = res * i; } return res; } // Find power in O(logb) time public static long power(long a, long b) { long res = 1; while(b > 0) { if((b&1) == 1) { res = (res * a)%mod; } a = (a * a)%mod; b >>= 1; } return res; } // Find nCr public static long nCr(int n, int r) { if(r < 0 || r > n) { return 0; } long ans = fact(n) / (fact(r) * fact(n-r)); return ans; } // Find nPr public static long nPr(int n, int r) { if(r < 0 || r > n) { return 0; } long ans = fact(n) / fact(r); return ans; } // sort all characters of a string public static String sortString(String inputString) { char tempArray[] = inputString.toCharArray(); Arrays.sort(tempArray); return new String(tempArray); } // User defined class for fast I/O static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } boolean hasNext() { if (st != null && st.hasMoreTokens()) { return true; } String tmp; try { br.mark(1000); tmp = br.readLine(); if (tmp == null) { return false; } br.reset(); } catch (IOException e) { return false; } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } boolean nextBoolean() { return Boolean.parseBoolean(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextArray(int n) { int[] a = new int[n]; for(int i=0; i<n; i++) { a[i] = nextInt(); } return a; } } } /** Dec Char Dec Char Dec Char Dec Char --------- --------- --------- ---------- 0 NUL (null) 32 SPACE 64 @ 96 ` 1 SOH (start of heading) 33 ! 65 A 97 a 2 STX (start of text) 34 " 66 B 98 b 3 ETX (end of text) 35 # 67 C 99 c 4 EOT (end of transmission) 36 $ 68 D 100 d 5 ENQ (enquiry) 37 % 69 E 101 e 6 ACK (acknowledge) 38 & 70 F 102 f 7 BEL (bell) 39 ' 71 G 103 g 8 BS (backspace) 40 ( 72 H 104 h 9 TAB (horizontal tab) 41 ) 73 I 105 i 10 LF (NL line feed, new line) 42 * 74 J 106 j 11 VT (vertical tab) 43 + 75 K 107 k 12 FF (NP form feed, new page) 44 , 76 L 108 l 13 CR (carriage return) 45 - 77 M 109 m 14 SO (shift out) 46 . 78 N 110 n 15 SI (shift in) 47 / 79 O 111 o 16 DLE (data link escape) 48 0 80 P 112 p 17 DC1 (device control 1) 49 1 81 Q 113 q 18 DC2 (device control 2) 50 2 82 R 114 r 19 DC3 (device control 3) 51 3 83 S 115 s 20 DC4 (device control 4) 52 4 84 T 116 t 21 NAK (negative acknowledge) 53 5 85 U 117 u 22 SYN (synchronous idle) 54 6 86 V 118 v 23 ETB (end of trans. block) 55 7 87 W 119 w 24 CAN (cancel) 56 8 88 X 120 x 25 EM (end of medium) 57 9 89 Y 121 y 26 SUB (substitute) 58 : 90 Z 122 z 27 ESC (escape) 59 ; 91 [ 123 { 28 FS (file separator) 60 < 92 \ 124 | 29 GS (group separator) 61 = 93 ] 125 } 30 RS (record separator) 62 > 94 ^ 126 ~ 31 US (unit separator) 63 ? 95 _ 127 DEL */ // (a/b)%mod == (a * moduloInverse(b)) % mod; // moduloInverse(b) = power(b, mod-2);
java
1284
A
A. New Year and Namingtime limit per test1 secondmemory limit per test1024 megabytesinputstandard inputoutputstandard outputHappy new year! The year 2020 is also known as Year Gyeongja (경자년; gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years.There are two sequences of nn strings s1,s2,s3,…,sns1,s2,s3,…,sn and mm strings t1,t2,t3,…,tmt1,t2,t3,…,tm. These strings contain only lowercase letters. There might be duplicates among these strings.Let's call a concatenation of strings xx and yy as the string that is obtained by writing down strings xx and yy one right after another without changing the order. For example, the concatenation of the strings "code" and "forces" is the string "codeforces".The year 1 has a name which is the concatenation of the two strings s1s1 and t1t1. When the year increases by one, we concatenate the next two strings in order from each of the respective sequences. If the string that is currently being used is at the end of its sequence, we go back to the first string in that sequence.For example, if n=3,m=4,s=n=3,m=4,s={"a", "b", "c"}, t=t= {"d", "e", "f", "g"}, the following table denotes the resulting year names. Note that the names of the years may repeat. You are given two sequences of strings of size nn and mm and also qq queries. For each query, you will be given the current year. Could you find the name corresponding to the given year, according to the Gapja system?InputThe first line contains two integers n,mn,m (1≤n,m≤201≤n,m≤20).The next line contains nn strings s1,s2,…,sns1,s2,…,sn. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.The next line contains mm strings t1,t2,…,tmt1,t2,…,tm. Each string contains only lowercase letters, and they are separated by spaces. The length of each string is at least 11 and at most 1010.Among the given n+mn+m strings may be duplicates (that is, they are not necessarily all different).The next line contains a single integer qq (1≤q≤20201≤q≤2020).In the next qq lines, an integer yy (1≤y≤1091≤y≤109) is given, denoting the year we want to know the name for.OutputPrint qq lines. For each line, print the name of the year as per the rule described above.ExampleInputCopy10 12 sin im gye gap eul byeong jeong mu gi gyeong yu sul hae ja chuk in myo jin sa o mi sin 14 1 2 3 4 10 11 12 13 73 2016 2017 2018 2019 2020 OutputCopysinyu imsul gyehae gapja gyeongo sinmi imsin gyeyu gyeyu byeongsin jeongyu musul gihae gyeongja NoteThe first example denotes the actual names used in the Gapja system. These strings usually are either a number or the name of some animal.
[ "implementation", "strings" ]
import java.util.*; public class Solution{ public static void main(String[] args) { Scanner in=new Scanner(System.in); int n=in.nextInt(); int m=in.nextInt(); in.nextLine(); String s1=in.nextLine(); String s2=in.nextLine(); String[] str1=s1.split(" "); String[] str2=s2.split(" "); int q=in.nextInt(); for(int c=0;c<q;c++) { int x=in.nextInt(); x=x-1; int i= x%n; int j=x%m; System.out.println(str1[i]+str2[j]); } } }
java
1313
B
B. Different Rulestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputNikolay has only recently started in competitive programming; but already qualified to the finals of one prestigious olympiad. There going to be nn participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest number of problems wins, the organizers came up with different rules.Suppose in the first round participant A took xx-th place and in the second round — yy-th place. Then the total score of the participant A is sum x+yx+y. The overall place of the participant A is the number of participants (including A) having their total score less than or equal to the total score of A. Note, that some participants may end up having a common overall place. It is also important to note, that in both the first and the second round there were no two participants tying at a common place. In other words, for every ii from 11 to nn exactly one participant took ii-th place in first round and exactly one participant took ii-th place in second round.Right after the end of the Olympiad, Nikolay was informed that he got xx-th place in first round and yy-th place in the second round. Nikolay doesn't know the results of other participants, yet he wonders what is the minimum and maximum place he can take, if we consider the most favorable and unfavorable outcome for him. Please help Nikolay to find the answer to this question.InputThe first line contains an integer tt (1≤t≤1001≤t≤100) — the number of test cases to solve.Each of the following tt lines contains integers nn, xx, yy (1≤n≤1091≤n≤109, 1≤x,y≤n1≤x,y≤n) — the number of participants in the olympiad, the place that Nikolay took in the first round and the place that Nikolay took in the second round.OutputPrint two integers — the minimum and maximum possible overall place Nikolay could take.ExamplesInputCopy15 1 3OutputCopy1 3InputCopy16 3 4OutputCopy2 6NoteExplanation for the first example:Suppose there were 5 participants A-E. Let's denote Nikolay as A. The the most favorable results for Nikolay could look as follows: However, the results of the Olympiad could also look like this: In the first case Nikolay would have taken first place, and in the second — third place.
[ "constructive algorithms", "greedy", "implementation", "math" ]
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author wilso */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class codeforces { static final long MOD2 = 998_244_353; static final long X = 10000000000L; public static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); // Scanner sc = new Scanner(System.in); int tc = sc.ni(); // int tc = 1; for (int rep = 0; rep < tc; rep++) { long N = sc.nl(); long X = sc.nl(); long Y = sc.nl(); long miny = 1; if (X+Y - N > 0) miny = X+Y-N+1; miny = Math.min(miny, N); long maxy = Math.min(N, X+Y-1); pw.println(miny + " " + maxy); } pw.close(); } static long solve(long[][] LR, long[][] UD, int N, int M, int K, int i, int j) { // cache = new Long[N][M][K]; return 0L; } static int[] reduce(int[] temp) { int[] frac = new int[] {temp[0], temp[1]}; int curr = gcd(frac[0], frac[1]); while (curr != 1) { frac[0] /= curr; frac[1] /= curr; curr = gcd(frac[0], frac[1]); } return frac; } static int summation(int x) { return x * (x+1) / 2; } static long pow(long num, long exp, long mod){ long ans=1; for(int i=1;i<=exp;i++){ ans=(ans*num)%mod; } return ans; } static boolean isPrime(int n) { if (n <= 1) return false; else if (n == 2) return true; else if (n % 2 == 0) return false; for (int i = 3; i <= Math.sqrt(n); i += 2) { if (n % i == 0) return false; } return true; } 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; } public static void sort(int[] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int r = rgen.nextInt(arr.length); int temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; } Arrays.sort(arr); } public static void sort(long[] arr) { Random rgen = new Random(); for (int i = 0; i < arr.length; i++) { int r = rgen.nextInt(arr.length); long temp = arr[i]; arr[i] = arr[r]; arr[r] = temp; } Arrays.sort(arr); } static int charint(char c) { return Integer.parseInt(String.valueOf(c)); } /* */ //printing methods /* */ //WOW! /* */ public static void printArr(PrintWriter pw, int[] arr) { StringBuilder sb = new StringBuilder(); for (int x : arr) { sb.append(x + ""); } sb.setLength(sb.length() - 1); pw.println(sb.toString()); } public static void printArr2d(PrintWriter pw, int[][] arr) { StringBuilder sb = new StringBuilder(); for (int[] row : arr) { for (int x : row) { sb.append(x + " "); } sb.setLength(sb.length() - 1); sb.append("\n"); } pw.println(sb.toString()); } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in), 32768); st = null; } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } int[] intArray(int N) { int[] ret = new int[N]; for (int i = 0; i < N; i++) ret[i] = ni(); return ret; } long nl() { return Long.parseLong(next()); } long[] longArray(int N) { long[] ret = new long[N]; for (int i = 0; i < N; i++) ret[i] = nl(); return ret; } double nd() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } class MultiSet { TreeMap<Long, Integer> map = new TreeMap<>(); private int size = 0; public MultiSet() { } public void add(Long val) { map.put(val, map.getOrDefault(val, 0) + 1); size++; } public void remove(Long val) { map.put(val, map.get(val) - 1); if (map.get(val) == 0) { map.remove(val); } size--; } public int size() { return size; } public Long higher(Long val) { return map.higherKey(val); } public Long lower(Long val) { return map.lowerKey(val); } public Long ceiling(Long val) { return map.ceilingKey(val); } public Long floor(Long val) { return map.floorKey(val); } public Long first() { return map.firstKey(); } public Long last() { return map.lastKey(); } public boolean isEmpty() { return map.isEmpty(); } }
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 hello{ public static void main(String []args){ Scanner inp =new Scanner(System.in); int t=inp.nextInt(); while(t-->0){ int n=inp.nextInt(); int []arr=new int[n]; for(int i=0;i<n;i++){ arr[i]=inp.nextInt(); } Arrays.sort(arr); int uni=1; for(int i=0;i<n-1;i++){ if(arr[i]!=arr[i+1]) uni++; } System.out.println(uni); } } }
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 java.util.Scanner; import java.util.Spliterator; public class Book { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); while (n-- > 0) { int a = scan.nextInt(), b = scan.nextInt(), c = scan.nextInt(), s = scan.nextInt(); int v = Math.max(a,b); int d = Math.max(v,c); int m = s-((d-a)+(d-b)+(d-c)); if(m>=0) System.out.println((m%3==0)?"YES":"NO"); else System.out.println("NO"); } } }
java
1285
A
A. Mezo Playing Zomatime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Mezo is playing a game. Zoma, a character in that game, is initially at position x=0x=0. Mezo starts sending nn commands to Zoma. There are two possible commands: 'L' (Left) sets the position x:=x−1x:=x−1; 'R' (Right) sets the position x:=x+1x:=x+1. Unfortunately, Mezo's controller malfunctions sometimes. Some commands are sent successfully and some are ignored. If the command is ignored then the position xx doesn't change and Mezo simply proceeds to the next command.For example, if Mezo sends commands "LRLR", then here are some possible outcomes (underlined commands are sent successfully): "LRLR" — Zoma moves to the left, to the right, to the left again and to the right for the final time, ending up at position 00; "LRLR" — Zoma recieves no commands, doesn't move at all and ends up at position 00 as well; "LRLR" — Zoma moves to the left, then to the left again and ends up in position −2−2. Mezo doesn't know which commands will be sent successfully beforehand. Thus, he wants to know how many different positions may Zoma end up at.InputThe first line contains nn (1≤n≤105)(1≤n≤105) — the number of commands Mezo sends.The second line contains a string ss of nn commands, each either 'L' (Left) or 'R' (Right).OutputPrint one integer — the number of different positions Zoma may end up at.ExampleInputCopy4 LRLR OutputCopy5 NoteIn the example; Zoma may end up anywhere between −2−2 and 22.
[ "math" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; // import java.util.Scanner; import java.util.StringTokenizer; public class mezo { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader s=new FastReader(); int n = s.nextInt(); String str = s.nextLine(); System.out.println(n+1); } }
java
1304
A
A. Two Rabbitstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBeing tired of participating in too many Codeforces rounds; Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position xx, and the shorter rabbit is currently on position yy (x<yx<y). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by aa, and the shorter rabbit hops to the negative direction by bb. For example, let's say x=0x=0, y=10y=10, a=2a=2, and b=3b=3. At the 11-st second, each rabbit will be at position 22 and 77. At the 22-nd second, both rabbits will be at position 44.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤10001≤t≤1000).Each test case contains exactly one line. The line consists of four integers xx, yy, aa, bb (0≤x<y≤1090≤x<y≤109, 1≤a,b≤1091≤a,b≤109) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.OutputFor each test case, print the single integer: number of seconds the two rabbits will take to be at the same position.If the two rabbits will never be at the same position simultaneously, print −1−1.ExampleInputCopy5 0 10 2 3 0 10 3 3 900000000 1000000000 1 9999999 1 2 1 1 1 3 1 1 OutputCopy2 -1 10 -1 1 NoteThe first case is explained in the description.In the second case; each rabbit will be at position 33 and 77 respectively at the 11-st second. But in the 22-nd second they will be at 66 and 44 respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward.
[ "math" ]
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { int x = sc.nextInt(); int y = sc.nextInt(); int a = sc.nextInt(); int b = sc.nextInt(); int count = 0; int d = y - x; if (d % (a + b) == 0) { System.out.println(d / (a + b)); } else { System.out.println("-1"); } } } }
java
1288
A
A. Deadlinetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAdilbek was assigned to a special project. For Adilbek it means that he has nn days to run a special program and provide its results. But there is a problem: the program needs to run for dd days to calculate the results.Fortunately, Adilbek can optimize the program. If he spends xx (xx is a non-negative integer) days optimizing the program, he will make the program run in ⌈dx+1⌉⌈dx+1⌉ days (⌈a⌉⌈a⌉ is the ceiling function: ⌈2.4⌉=3⌈2.4⌉=3, ⌈2⌉=2⌈2⌉=2). The program cannot be run and optimized simultaneously, so the total number of days he will spend is equal to x+⌈dx+1⌉x+⌈dx+1⌉.Will Adilbek be able to provide the generated results in no more than nn days?InputThe first line contains a single integer TT (1≤T≤501≤T≤50) — the number of test cases.The next TT lines contain test cases – one per line. Each line contains two integers nn and dd (1≤n≤1091≤n≤109, 1≤d≤1091≤d≤109) — the number of days before the deadline and the number of days the program runs.OutputPrint TT answers — one per test case. For each test case print YES (case insensitive) if Adilbek can fit in nn days or NO (case insensitive) otherwise.ExampleInputCopy3 1 1 4 5 5 11 OutputCopyYES YES NO NoteIn the first test case; Adilbek decides not to optimize the program at all; since d≤nd≤n.In the second test case, Adilbek can spend 11 day optimizing the program and it will run ⌈52⌉=3⌈52⌉=3 days. In total, he will spend 44 days and will fit in the limit.In the third test case, it's impossible to fit in the limit. For example, if Adilbek will optimize the program 22 days, it'll still work ⌈112+1⌉=4⌈112+1⌉=4 days.
[ "binary search", "brute force", "math", "ternary search" ]
import java.util.Arrays; import java.util.Scanner; public class Task1 { public static void main(String[] args) { process(new Scanner(System.in)); } private static void process(Scanner scanner) { int count = getValue(scanner); for (int z = 0; z < count; z++) { int[] values = getValues(scanner); int n = values[0]; int d = values[1]; int left = 0; int right = n; int middle = left + (right - left) / 2; while (left < right - 1) { middle = left + (right - left) / 2; int currentN = middle + (int)Math.ceil(d * 1.0 / (middle + 1)); if (currentN == n) break; if (currentN < n) { left = middle; } else { right = middle; } } middle = left + (right - left) / 2; System.out.println(n == middle + (int)Math.ceil(d * 1.0 / (middle + 1)) || n == d ? "YES" : "NO"); } } private static int getValue(Scanner scanner) { return Integer.parseInt(scanner.nextLine()); } private static int[] getValues(Scanner scanner) { return Arrays.stream(scanner.nextLine().split(" ")) .mapToInt(Integer::parseInt) .toArray(); } }
java
1312
A
A. Two Regular Polygonstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers nn and mm (m<nm<n). Consider a convex regular polygon of nn vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). Examples of convex regular polygons Your task is to say if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon.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 as two space-separated integers nn and mm (3≤m<n≤1003≤m<n≤100) — the number of vertices in the initial polygon and the number of vertices in the polygon you want to build.OutputFor each test case, print the answer — "YES" (without quotes), if it is possible to build another convex regular polygon with mm vertices such that its center coincides with the center of the initial polygon and each of its vertices is some vertex of the initial polygon and "NO" otherwise.ExampleInputCopy2 6 3 7 3 OutputCopyYES NO Note The first test case of the example It can be shown that the answer for the second test case of the example is "NO".
[ "geometry", "greedy", "math", "number theory" ]
import java.util.Scanner; public class Main { public static void main(String args[]) { Scanner s=new Scanner(System.in); int j=s.nextInt(); for(int k=0;k<j;k++) { int[] a=new int[2]; for(int i=0;i<a.length;i++) { a[i]=s.nextInt(); } if((a[0]%a[1])==0) { System.out.println("YES"); } else { System.out.println("NO"); } } } }
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.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Scanner; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); boolean flag = m == 0; if (n < 3 && !flag) { out.print(-1); return; } int maxTries = r(n); if (maxTries < m && !flag) { out.print(-1); return; } int[] a = new int[n]; if (maxTries == m) { for (int i = 0; i < a.length; i++) { a[i] = i + 1; } } else { int p = 1; int len = -1; for (int i = 3; i <= 5000; i++) { if (p <= m) { len = i; } else { break; } p = i / 2 + p; } for (int i = 0; i < len; i++) { a[i] = i + 1; } int countOf3 = m - r(len); if (len >= 0 && countOf3 != 0) { a[len] = a[len - countOf3] + a[len - countOf3 - 2]; len++; } if (len == -1) { a[0] = 1; if (n > 1) a[1] = 2; len = 1; } int chislo = 1000_000_000; int kones = n - 1; for (int k = len; k < n; k++) { a[kones] = chislo;//a[k - 1] + a[k - 2] + 1; chislo -= a[len - 1] + 1; kones--; } // m } for (int i = 0; i < a.length; i++) { out.print(a[i] + " "); } } int r(int n) { if (n < 3) { return -1; } if (n == 3) { return 1; } return r(n - 1) + (n - 1) / 2; } } }
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.util.*; import java.io.*; import java.lang.*; import java.math.BigInteger; import java.security.*; public class problem { static FastReader sc=new FastReader(); static long mod=(long) (1e9+7); public static int setbits(int n) { int count=0; while(n!=0) { n=n&(n-1); count++; } return count; } public static int LowerBoundorequaltox(int n,long tar,long[] arr) { int l=0,r=n-1,an=0; while(l<=r) { int mid=(l+r)/2; if(arr[mid]<=tar) { l=mid+1; an=mid; } else { r=mid-1; } } return an; } public static int mostsetgbit(int n) { int msbcount=0; while(n!=1) { n/=2; msbcount++; } return msbcount; } //Lower Bound static int lower_bound(long array[], int key) { int index = Arrays.binarySearch(array, key); // If key is not present in the array if (index < 0) { // Index specify the position of the key // when inserted in the sorted array // so the element currently present at // this position will be the lower bound return Math.abs(index) - 1; } // If key is present in the array // we move leftwards to find its first occurrence else { // Decrement the index to find the first // occurrence of the key while (index > 0) { // If previous value is same if (array[index - 1] == key) index--; // Previous value is different which means // current index is the first occurrence of // the key else return index; } return index; } } public static void main(String[] args) { int t=sc.nextInt(); while(t-->0) { String s=sc.next(); ArrayList <Integer> al=new ArrayList<Integer>(); al.add(-1); for(int i=0;i<s.length();i++) { if(s.charAt(i)=='R')al.add(i); } al.add(s.length()); int ans=0; for(int i=0;i<al.size()-1;i++) { int a=al.get(i+1)-al.get(i); ans=Math.max(a, ans); } System.out.println(ans); } } //INTEGER ARRAY INPUT SHORTCUT static int[] input(int n) { int A[]=new int[n]; for(int i=0;i<n;i++) { A[i]=sc.nextInt(); } return A; } //LONG ARRAY INPUT static long[] inputL(int n) { long A[]=new long[n]; for(int i=0;i<n;i++) { A[i]=sc.nextLong(); } return A; } //STRING ARRAY INPUT static String[] inputS(int n) { String A[]=new String[n]; for(int i=0;i<n;i++) { A[i]=sc.next(); } return A; } //SWAPPING TWO NUMBERS public static void swap(int a ,int b) { a=a^b; b=a^b; a=a^b; } //GCD public static int gcd(int p,int q) { if(q==0)return 1; else return gcd(q,q%p); } //Custom Input Reader 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
1305
E
E. Kuroni and the Score Distributiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputKuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done; and he is discussing with the team about the score distribution for the round.The round consists of nn problems, numbered from 11 to nn. The problems are ordered in increasing order of difficulty, no two problems have the same difficulty. A score distribution for the round can be denoted by an array a1,a2,…,ana1,a2,…,an, where aiai is the score of ii-th problem. Kuroni thinks that the score distribution should satisfy the following requirements: The score of each problem should be a positive integer not exceeding 109109. A harder problem should grant a strictly higher score than an easier problem. In other words, 1≤a1<a2<⋯<an≤1091≤a1<a2<⋯<an≤109. The balance of the score distribution, defined as the number of triples (i,j,k)(i,j,k) such that 1≤i<j<k≤n1≤i<j<k≤n and ai+aj=akai+aj=ak, should be exactly mm. Help the team find a score distribution that satisfies Kuroni's requirement. In case such a score distribution does not exist, output −1−1.InputThe first and single line contains two integers nn and mm (1≤n≤50001≤n≤5000, 0≤m≤1090≤m≤109) — the number of problems and the required balance.OutputIf there is no solution, print a single integer −1−1.Otherwise, print a line containing nn integers a1,a2,…,ana1,a2,…,an, representing a score distribution that satisfies all the requirements. If there are multiple answers, print any of them.ExamplesInputCopy5 3 OutputCopy4 5 9 13 18InputCopy8 0 OutputCopy10 11 12 13 14 15 16 17 InputCopy4 10 OutputCopy-1 NoteIn the first example; there are 33 triples (i,j,k)(i,j,k) that contribute to the balance of the score distribution. (1,2,3)(1,2,3) (1,3,4)(1,3,4) (2,4,5)(2,4,5)
[ "constructive algorithms", "greedy", "implementation", "math" ]
//package com.company; import java.io.*; import java.util.*; public class Main { public static class Task { public void solve(Scanner sc, PrintWriter pw) throws IOException { int n = sc.nextInt(); int k = sc.nextInt(); if (n <= 2) { if (n == 1) { if (k > 0) { pw.println(-1); } else { pw.println(1); } } else if (n == 2) { if (k > 0) { pw.println(-1); } else { pw.println(1 + " " + 2); } } return; } List<Integer> out = new ArrayList<>(); out.add(1); out.add(2); n -= 2; outer: while (n > 0 && k > 0) { int added = out.size() / 2; if (k >= added) { n--; out.add(out.size() + 1); k -= added; } else { for (int m = out.size() + 1; ; m++) { int t = out.size(); int earn = (t - (m - t) + 1) / 2; if (earn == k) { n--; out.add(m); k -= earn; break outer; } } } } if (n == 0 && k > 0) { pw.println(-1); return; } int z = out.size() + 10000; for (int i = 0; i < n; i++) { out.add(100000000 + i * z); } for (int x: out) pw.print(x + " "); pw.println(); } } static long TIME_START, TIME_END; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); // Scanner sc = new Scanner(new FileInputStream("input")); PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out)); // PrintWriter pw = new PrintWriter(new FileOutputStream("input")); Runtime runtime = Runtime.getRuntime(); long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory(); TIME_START = System.currentTimeMillis(); Task t = new Task(); t.solve(sc, pw); TIME_END = System.currentTimeMillis(); long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory(); pw.close(); System.err.println("Memory increased: " + (usedMemoryAfter - usedMemoryBefore) / 1000000); System.err.println("Time used: " + (TIME_END - TIME_START) + "."); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(FileReader s) throws FileNotFoundException { br = new BufferedReader(s); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } } }
java
1300
B
B. Assigning to Classestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputReminder: the median of the array [a1,a2,…,a2k+1][a1,a2,…,a2k+1] of odd number of elements is defined as follows: let [b1,b2,…,b2k+1][b1,b2,…,b2k+1] be the elements of the array in the sorted order. Then median of this array is equal to bk+1bk+1.There are 2n2n students, the ii-th student has skill level aiai. It's not guaranteed that all skill levels are distinct.Let's define skill level of a class as the median of skill levels of students of the class.As a principal of the school, you would like to assign each student to one of the 22 classes such that each class has odd number of students (not divisible by 22). The number of students in the classes may be equal or different, by your choice. Every student has to be assigned to exactly one class. Among such partitions, you want to choose one in which the absolute difference between skill levels of the classes is minimized.What is the minimum possible absolute difference you can achieve?InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤1051≤n≤105) — the number of students halved.The second line of each test case contains 2n2n integers a1,a2,…,a2na1,a2,…,a2n (1≤ai≤1091≤ai≤109) — skill levels of students.It is guaranteed that the sum of nn over all test cases does not exceed 105105.OutputFor each test case, output a single integer, the minimum possible absolute difference between skill levels of two classes of odd sizes.ExampleInputCopy3 1 1 1 3 6 5 4 1 2 3 5 13 4 20 13 2 5 8 3 17 16 OutputCopy0 1 5 NoteIn the first test; there is only one way to partition students — one in each class. The absolute difference of the skill levels will be |1−1|=0|1−1|=0.In the second test, one of the possible partitions is to make the first class of students with skill levels [6,4,2][6,4,2], so that the skill level of the first class will be 44, and second with [5,1,3][5,1,3], so that the skill level of the second class will be 33. Absolute difference will be |4−3|=1|4−3|=1.Note that you can't assign like [2,3][2,3], [6,5,4,1][6,5,4,1] or [][], [6,5,4,1,2,3][6,5,4,1,2,3] because classes have even number of students.[2][2], [1,3,4][1,3,4] is also not possible because students with skills 55 and 66 aren't assigned to a class.In the third test you can assign the students in the following way: [3,4,13,13,20],[2,5,8,16,17][3,4,13,13,20],[2,5,8,16,17] or [3,8,17],[2,4,5,13,13,16,20][3,8,17],[2,4,5,13,13,16,20]. Both divisions give minimal possible absolute difference.
[ "greedy", "implementation", "sortings" ]
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; import java.util.*; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; InputReader sc = new InputReader(inputStream); int i,n,t,j; t=sc.nextInt(); while(t-->0) { n=sc.nextInt(); int []arr=new int[2*n]; for(i=0;i<2*n;i++) { arr[i]=sc.nextInt(); } Arrays.sort(arr); System.out.println(Math.abs(arr[n-1]-arr[n])); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
java
1299
A
A. Anu Has a Functiontime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAnu has created her own function ff: f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers xx and yy value of f(x,y)f(x,y) is also nonnegative. She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.A value of an array [a1,a2,…,an][a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an)f(f(…f(f(a1,a2),a3),…an−1),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?InputThe first line contains a single integer nn (1≤n≤1051≤n≤105).The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109). Elements of the array are not guaranteed to be different.OutputOutput nn integers, the reordering of the array with maximum value. If there are multiple answers, print any.ExamplesInputCopy4 4 0 11 6 OutputCopy11 6 4 0InputCopy1 13 OutputCopy13 NoteIn the first testcase; value of the array [11,6,4,0][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.[11,4,0,6][11,4,0,6] is also a valid answer.
[ "brute force", "greedy", "math" ]
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[]arr=new int[n]; for(int i=0;i<n;i++)arr[i]=i(); int[]arr1=new int[32]; for(int i=0;i<n;i++){ int v=arr[i]; for(int j=0;j<32;j++){ int mask=(1<<j); if((mask&v)>0){ arr1[j]++; } } } int fans=0; int fe=0; for(int i=0;i<n;i++){ int v=arr[i]; for(int j=0;j<32;j++){ int mask=(1<<j); if(mask<0)continue; if((v&mask)>0){ if(arr1[j]>1){ v^=mask; } } } if(v>fans){ fe=i; fans=v; } } sb.append(arr[fe]+" "); for(int i=0;i<n;i++){ if(i!=fe)sb.append(arr[i]+" "); } } public static void main(String[] args) { sb = new StringBuilder(); int test = 1; while (test-- > 0) { solve(); } System.out.println(sb); } /* * fact=new long[(int)1e6+10]; fact[0]=fact[1]=1; for(int i=2;i<fact.length;i++) * { fact[i]=((long)(i%mod)1L(long)(fact[i-1]%mod))%mod; } */ //**************NCR%P****************** static long ncr(int n, int r) { if (r > n) return (long) 0; 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 x; long y; Pair(int x, long y) { this.x = x; this.y = y; } public int compareTo(Pair o) { return (int) (this.y - o.y); } } //****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
1292
A
A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1,1)(1,1) to the gate at (2,n)(2,n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only qq such moments: the ii-th moment toggles the state of cell (ri,ci)(ri,ci) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the qq moments, whether it is still possible to move from cell (1,1)(1,1) to cell (2,n)(2,n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers nn, qq (2≤n≤1052≤n≤105, 1≤q≤1051≤q≤105).The ii-th of qq following lines contains two integers riri, cici (1≤ri≤21≤ri≤2, 1≤ci≤n1≤ci≤n), denoting the coordinates of the cell to be flipped at the ii-th moment.It is guaranteed that cells (1,1)(1,1) and (2,n)(2,n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1,1)(1,1) to cell (2,n)(2,n), print "Yes", otherwise print "No". There should be exactly qq answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInputCopy5 5 2 3 1 4 2 4 2 3 1 4 OutputCopyYes No No No Yes NoteWe'll crack down the example test here: After the first query; the girl still able to reach the goal. One of the shortest path ways should be: (1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5)(1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5). After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1,3)(1,3). After the fourth query, the (2,3)(2,3) is not blocked, but now all the 44-th column is blocked, so she still can't reach the goal. After the fifth query, the column barrier has been lifted, thus she can go to the final goal again.
[ "data structures", "dsu", "implementation" ]
import java.io.*; import java.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 *********** 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;} 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 ***********************************/ 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"); // int T = sc.nextInt(); int T = 1; while (T-- > 0) { int n = sc.nextInt(); int q = sc.nextInt(); int totalBlock = 0; boolean[][] arr = new boolean[2][n]; for(int i = 0; i < q; i++){ int r = sc.nextInt()-1; int c = sc.nextInt()-1; // System.out.println(r +" " + c); int curBlocks = 0; arr[r][c] = !arr[r][c]; for (int rr = r - 1; rr <= r + 1; rr++) { for (int cc = c - 1; cc <= c + 1; cc++) { if (c == cc && r == rr) continue; if (r == rr || rr < 0 || rr >= 2 || cc < 0 || cc >= n) continue; if (arr[rr][cc]) curBlocks++; } } if(arr[r][c]) totalBlock += curBlocks; else totalBlock -= curBlocks; if(totalBlock == 0) System.out.println("YES"); else System.out.println("NO"); } } System.out.close(); } // public static long solve(StringBuilder s1, StringBuilder s2, int i, int[] dp){ // if(i == s1.length()){ // return 0; // } // if(dp[i] != -1) return dp[i]; // if(s2.charAt(i)=='0'){ // } // return res; // } 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
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 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int poolSize = Integer.parseInt(st.nextToken()); int teamSize = Integer.parseInt(st.nextToken()); int audSize = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); Pair[] audContrib = new Pair[poolSize]; for (int i = 0; i < poolSize; i++) { audContrib[i] = new Pair(i, Integer.parseInt(st.nextToken())); } Arrays.sort(audContrib); int[][] skill = new int[poolSize][teamSize]; for (int i = 0; i < poolSize; i++) { st = new StringTokenizer(br.readLine()); for (int j = 0; j < teamSize; j++) { skill[i][j] = Integer.parseInt(st.nextToken()); } } long[][] dp = new long[poolSize + 1][(1 << teamSize)]; for (int i = 0; i <= poolSize; i++) { Arrays.fill(dp[i], -1); } dp[0][0] = 0; for (int i = 1; i <= poolSize; i++) { int ind = audContrib[i - 1].idx; for (int m = 0; m < (1 << teamSize); m++) { int bits = Integer.bitCount(m); int numAud = i - 1 - bits; // Try adding the player to the audience if (numAud < audSize) { if (dp[i - 1][m] != -1) { dp[i][m] = dp[i - 1][m] + audContrib[i - 1].val; } } else { if (dp[i - 1][m] != -1) { dp[i][m] = dp[i - 1][m]; } } // Try adding the player to the team. for (int j = 0; j < teamSize; j++) { if ((m & (1 << j)) != 0 && (dp[i - 1][m ^ (1 << j)]) != -1) { dp[i][m] = Math.max( dp[i][m], dp[i - 1][m ^ (1 << j)] + skill[ind][j] ); } } } } System.out.println(dp[poolSize][(1 << teamSize) - 1]); } } class Pair implements Comparable<Pair> { int idx; int val; public Pair(int idx, int val) { this.idx = idx; this.val = val; } public int compareTo(Pair other) { return other.val - val; } }
java
1293
A
A. ConneR and the A.R.C. Markland-Ntime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputSakuzyo - ImprintingA.R.C. Markland-N is a tall building with nn floors numbered from 11 to nn. Between each two adjacent floors in the building, there is a staircase connecting them.It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location to enjoy his meal.ConneR's office is at floor ss of the building. On each floor (including floor ss, of course), there is a restaurant offering meals. However, due to renovations being in progress, kk of the restaurants are currently closed, and as a result, ConneR can't enjoy his lunch there.CooneR wants to reach a restaurant as quickly as possible to save time. What is the minimum number of staircases he needs to walk to reach a closest currently open restaurant.Please answer him quickly, and you might earn his praise and even enjoy the lunch with him in the elegant Neumanns' way!InputThe first line contains one integer tt (1≤t≤10001≤t≤1000) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first line of a test case contains three integers nn, ss and kk (2≤n≤1092≤n≤109, 1≤s≤n1≤s≤n, 1≤k≤min(n−1,1000)1≤k≤min(n−1,1000)) — respectively the number of floors of A.R.C. Markland-N, the floor where ConneR is in, and the number of closed restaurants.The second line of a test case contains kk distinct integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n) — the floor numbers of the currently closed restaurants.It is guaranteed that the sum of kk over all test cases does not exceed 10001000.OutputFor each test case print a single integer — the minimum number of staircases required for ConneR to walk from the floor ss to a floor with an open restaurant.ExampleInputCopy5 5 2 3 1 2 3 4 3 3 4 1 2 10 2 6 1 2 3 4 5 7 2 1 1 2 100 76 8 76 75 36 67 41 74 10 77 OutputCopy2 0 4 0 2 NoteIn the first example test case; the nearest floor with an open restaurant would be the floor 44.In the second example test case, the floor with ConneR's office still has an open restaurant, so Sensei won't have to go anywhere.In the third example test case, the closest open restaurant is on the 66-th floor.
[ "binary search", "brute force", "implementation" ]
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; import java.util.TreeSet; // ConneR and the A.R.C Markland-N public class ARCMarklandN { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int t = Integer.parseInt(br.readLine()); for (int i = 0; i < t; i++) { StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int curr = Integer.parseInt(st.nextToken()); int x = Integer.parseInt(st.nextToken()); TreeSet<Integer> set = new TreeSet<>(); st = new StringTokenizer(br.readLine()); boolean has = true; for (int j = 0; j < x; j++) { int block = Integer.parseInt(st.nextToken()); set.add(block); if (block == curr) has = false; } if (has) { pw.println(0); continue; } int left = curr, right = curr; boolean foundLeft = true, foundRight = true; while (left >= 1 && set.contains(left)) { left--; if (left < 1) { foundLeft = false; break; } } while (right <= n && set.contains(right)) { right++; if (right > n) { foundRight = false; break; } } if (!foundLeft) left = Integer.MAX_VALUE; if (!foundRight) right = Integer.MAX_VALUE; pw.println(Math.min(Math.abs(left - curr), Math.abs(right - curr))); } pw.close(); } }
java
1307
D
D. Cow and Fieldstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie is out grazing on the farm; which consists of nn fields connected by mm bidirectional roads. She is currently at field 11, and will return to her home at field nn at the end of the day.The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has kk special fields and he has decided to install the road between two different special fields. He may add the road between two special fields that already had a road directly connecting them.After the road is added, Bessie will return home on the shortest path from field 11 to field nn. Since Bessie needs more exercise, Farmer John must maximize the length of this shortest path. Help him!InputThe first line contains integers nn, mm, and kk (2≤n≤2⋅1052≤n≤2⋅105, n−1≤m≤2⋅105n−1≤m≤2⋅105, 2≤k≤n2≤k≤n)  — the number of fields on the farm, the number of roads, and the number of special fields. The second line contains kk integers a1,a2,…,aka1,a2,…,ak (1≤ai≤n1≤ai≤n)  — the special fields. All aiai are distinct.The ii-th of the following mm lines contains integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), representing a bidirectional road between fields xixi and yiyi. It is guaranteed that one can reach any field from every other field. It is also guaranteed that for any pair of fields there is at most one road connecting them.OutputOutput one integer, the maximum possible length of the shortest path from field 11 to nn after Farmer John installs one road optimally.ExamplesInputCopy5 5 3 1 3 5 1 2 2 3 3 4 3 5 2 4 OutputCopy3 InputCopy5 4 2 2 4 1 2 2 3 3 4 4 5 OutputCopy3 NoteThe graph for the first example is shown below. The special fields are denoted by red. It is optimal for Farmer John to add a road between fields 33 and 55, and the resulting shortest path from 11 to 55 is length 33. The graph for the second example is shown below. Farmer John must add a road between fields 22 and 44, and the resulting shortest path from 11 to 55 is length 33.
[ "binary search", "data structures", "dfs and similar", "graphs", "greedy", "shortest paths", "sortings" ]
import java.beans.Visibility; import java.io.*; import java.util.*; import java.math.BigInteger; /** __ __ ( _) ( _) / / \\ / /\_\_ / / \\ / / | \ \ / / \\ / / |\ \ \ / / , \ , / / /| \ \ / / |\_ /| / / / \ \_\ / / |\/ _ '_| \ / / / \ \\ | / |/ 0 \0\ / | | \ \\ | |\| \_\_ / / | \ \\ | | |/ \.\ o\o) / \ | \\ \ | /\\`v-v / | | \\ | \/ /_| \\_| / | | \ \\ | | /__/_ `-` / _____ | | \ \\ \| [__] \_/ |_________ \ | \ () / [___] ( \ \ |\ | | // | [___] |\| \| / |/ /| [____] \ |/\ / / || ( \ [____ / ) _\ \ \ \| | || \ \ [_____| / / __/ \ / / // | \ [_____/ / / \ | \/ // | / '----| /=\____ _/ | / // __ / / | / ___/ _/\ \ | || (/-(/-\) / \ (/\/\)/ | / | / (/\/\) / / // _________/ / / \____________/ ( @author NTUDragons-Reborn */ public class C{ public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } // main solver static class Task{ double eps= 0.00000001; static final int MAXN = 100005; static final int MOD= 1000000007; // stores smallest prime factor for every number static int spf[] = new int[MAXN]; static boolean[] prime; Map<Integer,Set<Integer>> dp= new HashMap<>(); // Calculating SPF (Smallest Prime Factor) for every // number till MAXN. // Time Complexity : O(nloglogn) public void sieve() { spf[1] = 1; for (int i=2; i<MAXN; i++) // marking smallest prime factor for every // number to be itself. spf[i] = i; // separately marking spf for every even // number as 2 for (int i=4; i<MAXN; i+=2) spf[i] = 2; for (int i=3; i*i<MAXN; i++) { // checking if i is prime if (spf[i] == i) { // marking SPF for all numbers divisible by i for (int j=i*i; j<MAXN; j+=i) // marking spf[j] if it is not // previously marked if (spf[j]==j) spf[j] = i; } } } 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. 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; } } } // A O(log n) function returning primefactorization // by dividing by smallest prime factor at every step public Set<Integer> getFactorization(int x) { if(dp.containsKey(x)) return dp.get(x); Set<Integer> ret = new HashSet<>(); while (x != 1) { if(spf[x]!=2) ret.add(spf[x]); x = x / spf[x]; } dp.put(x,ret); return ret; } // function to find first index >= x public int lowerIndex(List<Integer> arr, int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr.get(mid) >= x) h = mid - 1; else l = mid + 1; } return l; } public int lowerIndex(int[] arr, int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] >= x) h = mid - 1; else l = mid + 1; } return l; } // function to find last index <= y public int upperIndex(List<Integer> arr, int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr.get(mid) <= y) l = mid + 1; else h = mid - 1; } return h; } public int upperIndex(int[] arr, int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] <= y) l = mid + 1; else h = mid - 1; } return h; } // function to count elements within given range public int countInRange(List<Integer> arr, int n, int x, int y) { // initialize result int count = 0; count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1; return count; } public int _gcd(int a, int b) { if(b == 0) { return a; } else { return _gcd(b, a % b); } } public int add(int a, int b){ a+=b; if(a>=MOD) a-=MOD; else if(a<0) a+=MOD; return a; } public int mul(int a, int b){ long res= (long)a*(long)b; return (int)(res%MOD); } public int power(int a, int b) { int ans=1; while(b>0){ if((b&1)!=0) ans= mul(ans,a); b>>=1; a= mul(a,a); } return ans; } int[] fact= new int[MAXN]; int[] inv= new int[MAXN]; public int Ckn(int n, int k){ if(k<0 || n<0) return 0; return mul(mul(fact[n],inv[k]),inv[n-k]); } public int inverse(int a){ return power(a,MOD-2); } public void preprocess() { fact[0]=1; for(int i=1;i<MAXN;i++) fact[i]= mul(fact[i-1],i); inv[MAXN-1]= inverse(fact[MAXN-1]); for(int i=MAXN-2;i>=0;i--){ inv[i]= mul(inv[i+1],i+1); } } /** * return VALUE of lower bound for unsorted array */ public int lowerBoundNormalArray(int[] arr, int x){ TreeSet<Integer> set= new TreeSet<>(); for(int num: arr) set.add(num); return set.lower(x); } /** * return VALUE of upper bound for unsorted array */ public int upperBoundNormalArray(int[] arr, int x){ TreeSet<Integer> set= new TreeSet<>(); for(int num: arr) set.add(num); return set.higher(x); } public void debugArr(int[] arr){ for(int i: arr) out.print(i+" "); out.println(); } InputReader in; PrintWriter out; public void solve(InputReader in, PrintWriter out) { this.in=in; this.out=out; int t= 1; while(t-->0){ solveB(); } } int[] d1,d2; List[] adj; int n,m,k; public void solveB(){ n= in.nextInt(); m= in.nextInt(); k= in.nextInt(); int[] special= new int[k]; adj= new List[n]; for(int i=0;i<k;i++) special[i]= in.nextInt()-1; for(int i=0;i<n;i++) adj[i]= new ArrayList<>(); for(int i=0;i<m;i++){ int x= in.nextInt()-1, y= in.nextInt()-1; adj[x].add(y); adj[y].add(x); } d1= new int[n]; d2= new int[n]; bfs(0,true); bfs(n-1,false); assert d1[n-1]==d2[0]; List<Pair> p= new ArrayList<>(); for(int s: special){ p.add(new Pair(d1[s],d2[s])); } Collections.sort(p); int[] suf= new int[k]; suf[k-1]= p.get(k-1).y; for(int i=k-2;i>=0;i--){ suf[i]= Math.max(suf[i+1],p.get(i).y); } int res= -1; for(int i=0;i<k-1;i++){ res= Math.max(res, p.get(i).x+1+suf[i+1]); } res= Math.min(res,d1[n-1]); out.println(res); } private void bfs(int u, boolean useD1){ boolean[] visited= new boolean[n]; Queue<Integer> q= new LinkedList<>(); q.add(u); visited[u]=true; while(!q.isEmpty()){ int cur= q.poll(); for(int v: (List<Integer>) adj[cur]){ if(visited[v]) continue; visited[v]=true; if(useD1) d1[v] = d1[cur]+1; else d2[v]= d2[cur]+1; q.add(v); } } } } static class Venice{ public Map<Long,Long> m= new HashMap<>(); public long base=0; public long totalValue=0; private int M= 1000000007; private long addMod(long a, long b){ a+=b; if(a>=M) a-=M; return a; } public void reset(){ m= new HashMap<>(); base=0; totalValue=0; } public void update(long add){ base= base+ add; } public void add(long key, long val){ long newKey= key-base; m.put(newKey, addMod(m.getOrDefault(newKey,(long)0),val)); } } static class Tuple implements Comparable<Tuple>{ int x, y, z; public Tuple(int x, int y, int z){ this.x= x; this.y= y; this.z=z; } @Override public int compareTo(Tuple o){ int val1= this.x-this.y; int val2= o.x-o.y; return val1-val2; } } static class Pair implements Comparable<Pair>{ public int x; public int y; public Pair(int x, int y){ this.x= x; this.y= y; } @Override public int compareTo(Pair o) { int val1= this.x-this.y; int val2= o.x-o.y; return val1-val2; } } // public static class compareL implements Comparator<Tuple>{ // @Override // public int compare(Tuple t1, Tuple t2) { // return t2.l - t1.l; // } // } // fast input reader class; static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public String nextToken() { while (st == null || !st.hasMoreTokens()) { String line = null; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public double nextDouble(){ return Double.parseDouble(nextToken()); } public long nextLong(){ return Long.parseLong(nextToken()); } public int[] nextIntArr(int n){ int[] arr= new int[n]; for(int i=0;i<n;i++) arr[i]= nextInt(); return arr; } public long[] nextLongArr(int n){ long[] arr= new long[n]; for(int i=0;i<n;i++) arr[i]= nextLong(); return arr; } public List<Integer> nextIntList(int n){ List<Integer> arr= new ArrayList<>(); for(int i=0;i<n;i++) arr.add(nextInt()); return arr; } public int[][] nextIntMatArr(int n, int m){ int[][] mat= new int[n][m]; for(int i=0;i<n;i++) for(int j=0;j<m;j++) mat[i][j]= nextInt(); return mat; } public List<List<Integer>> nextIntMatList(int n, int m){ List<List<Integer>> mat= new ArrayList<>(); for(int i=0;i<n;i++){ List<Integer> temp= new ArrayList<>(); for(int j=0;j<m;j++) temp.add(nextInt()); mat.add(temp); } return mat; } public char[] nextStringCharArr(){ return nextToken().toCharArray(); } } }
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 com.sun.security.jgss.GSSUtil; import java.lang.reflect.Array; import java.util.*; import java.lang.*; import java.io.*; public class Solution { public static void main(String[] args) throws IOException { Reader.init(System.in); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); // int t = Reader.nextInt(); int t = 1; while(t-->0){ int n = Reader.nextInt(); long ans = 0; int x = n; ArrayList<int[]> arr = new ArrayList<>(); for(int i = 0;i<n;i++){ int size = Reader.nextInt(); int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; int min_so_far = Integer.MAX_VALUE; boolean flag = false; for(int j = 0;j<size;j++){ int num = Reader.nextInt(); max = Math.max(max,num); min = Math.min(min,num); if(num<min_so_far){ min_so_far = num; } else if(num>min_so_far){ flag = true; } } if(flag){ ans += 2L*x-1; x--; } else{ arr.add(new int[]{min,max}); } } arr.sort((n1,n2)->n1[1]-n2[1]); for(int i = 0;i<arr.size();i++){ int tar = arr.get(i)[0]; int l = 0, r = arr.size()-1; int curr = arr.size(); while(l<=r){ int mid = l + (r-l)/2; if(arr.get(mid)[1]>tar){ curr = mid; r = mid-1; } else{ l = mid+1; } } ans += arr.size()-curr; } System.out.println(ans); } // output.close(); } public static long[] factorial(int n){ long[] factorials = new long[n+1]; factorials[1] = 1; for(int i = 2;i<=n;i++){ factorials[i] = (factorials[i-1]*i)%998244353; } 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 int power(int x, int y, int p) { int 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 int modInverse(int n, int p) { return power(n, p - 2, p); } // Returns nCr % p using Fermat's // little theorem. public static int 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 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; } 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 int mergeSortAndCount(int[] arr, int l, int r) { int count = 0; if (l < r) { int m = (l + r) / 2; count += mergeSortAndCount(arr, l, m); count += mergeSortAndCount(arr, m + 1, r); count += mergeAndCount(arr, l, m, r); } return count; } public static int mergeAndCount(int[] arr, int l, int m, int r) { int[] left = Arrays.copyOfRange(arr, l, m + 1); int[] right = Arrays.copyOfRange(arr, m + 1, r + 1); int i = 0, j = 0, k = l, swaps = 0; while (i < left.length && j < right.length) { if (left[i] <= right[j]) arr[k++] = left[i++]; else { arr[k++] = right[j++]; swaps += (m + 1) - (l + i); } } while (i < left.length) arr[k++] = left[i++]; while (j < right.length) arr[k++] = right[j++]; return swaps; } 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() ); } }
java
1303
A
A. Erasing Zeroestime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a string ss. Each character is either 0 or 1.You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.You may erase some (possibly none) 0's from the string. What is the minimum number of 0's that you have to erase?InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Then tt lines follow, each representing a test case. Each line contains one string ss (1≤|s|≤1001≤|s|≤100); each character of ss is either 0 or 1.OutputPrint tt integers, where the ii-th integer is the answer to the ii-th testcase (the minimum number of 0's that you have to erase from ss).ExampleInputCopy3 010011 0 1111000 OutputCopy2 0 0 NoteIn the first test case you have to delete the third and forth symbols from string 010011 (it turns into 0111).
[ "implementation", "strings" ]
import java.io.*; import java.util.*; public class Main { public static void main(String args[]) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); while(t-->0){ String s=br.readLine(); int z=0,o=0; for(int i=0;i<s.length();i++) if(s.charAt(i)=='0')z++; else o++; int i=0,f=0; if(o==0)f=1; while(i<s.length() && s.charAt(i)=='0'){ i++; z--; } i=s.length()-1; while(i>=0 && s.charAt(i)=='0'){ i--; z--; } if(f==1) z=0; System.out.println(z); } } }
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.util.*; //import java.lang.*; import java.io.*; public class Solution { static long[] fac; static int m = (int)1e9+7; static int c = 1; // static int[] x = {1,-1,0,0}; // static int[] y = {0,0,1,-1}; // static int cycle_node; 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); // long[] fact = factorial((int)1e6); // int te = Reader.nextInt(); int te = 1; while(te-->0){ int n = Reader.nextInt(); int[] arr = new int[n]; for(int i = 0;i<n;i++) arr[i] = Reader.nextInt(); int[] ans = new int[n]; long maxSum = 0; for(int i = 0;i<n;i++){ int[] curr = new int[n]; long currSum = 0; curr[i] = arr[i]; int max = curr[i]; currSum += curr[i]; for(int j = i-1;j>=0;j--){ curr[j] = Math.min(max,arr[j]); max = curr[j]; currSum += curr[j]; } max = curr[i]; for(int j = i+1;j<n;j++){ curr[j] = Math.min(max,arr[j]); max = curr[j]; currSum += curr[j]; } if(currSum>maxSum){ ans = curr; maxSum = currSum; } } for(int i = 0;i<n;i++){ output.write(ans[i]+" "); } output.write("\n"); } output.close(); } // Recursive function to return (x ^ n) % m static long modexp(long x, long n) { if (n == 0) { return 1; } else if (n % 2 == 0) { return modexp((x * x) % m, n / 2); } else { return (x * modexp((x * x) % m, (n - 1) / 2) % m); } } // Function to return the fraction modulo mod static long getFractionModulo(long a, long b) { long c = gcd(a, b); a = a / c; b = b / c; // (b ^ m-2) % m long d = modexp(b, m - 2); // Final answer long ans = ((a % m) * (d % m)) % m; return ans; } public static boolean isP(String 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)%1000000007; } 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; } 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
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 + 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
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.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { FastScanner f = new FastScanner(); int t=1; t=f.nextInt(); PrintWriter out=new PrintWriter(System.out); for(int tt=0;tt<t;tt++) { long n =f.nextLong(); int m=f.nextInt(); int[] l=f.readArray(m); int[] c=new int[61]; long sum=0; for(int i:l) { sum+=i; int p=0; while(i!=1) { i/=2; p++; } c[p]++; } if(sum<n) { out.println(-1); continue; } int ans=0; for(int i=0; i<60; ++i) { if((n>>i&1)==1) { // System.out.println(i); if(c[i]==0) { int j=i+1; // System.out.println(j); while(j<61 && c[j]==0) j++; // System.out.println(j); c[j]--; while(--j>=i) { ++c[j]; ++ans; } ++c[i]; } --c[i]; } c[i+1]+=c[i]/2; } out.println(ans);; } out.close(); } static void sort(int[] p) { ArrayList<Integer> q = new ArrayList<>(); for (int i: p) q.add( i); Collections.sort(q); for (int i = 0; i < p.length; i++) p[i] = q.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } long[] readLongArray(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } } } //Some things to notice //Check for the overflow //Binary Search //Bitmask //runtime error most of the time is due to array index out of range
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" ]
// package CP; import java.util.*; import java.io.*; public class Main { 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 java.lang.Exception { FastReader sc = new FastReader(); BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out)); int t = 1; // t = sc.nextInt(); while (t-- != 0) { int n = sc.nextInt(); int m[] = new int[n]; int lr_nextSmaller[] = new int[n]; int rl_nextSmaller[] = new int[n]; for (int i = 0; i < n; i++) { m[i] = sc.nextInt(); } Stack<Integer> st = new Stack<>(); for (int i = n - 1; i >= 0; i--) { while (!st.isEmpty() && m[i] <= m[st.peek()]) { st.pop(); } if (st.isEmpty()) { lr_nextSmaller[i] = -1; } else { lr_nextSmaller[i] = st.peek(); } st.push(i); } st.clear(); for (int i = 0; i < n; i++) { while (!st.isEmpty() && m[i] <= m[st.peek()]) { st.pop(); } if (st.isEmpty()) { rl_nextSmaller[i] = -1; } else { rl_nextSmaller[i] = st.peek(); } st.push(i); } long leftdp[] = new long[n]; leftdp[0] = m[0]; for (int i = 1; i < n; i++) { if (m[i - 1] <= m[i]) { leftdp[i] = leftdp[i - 1] + m[i]; } else { int nextSmaller = rl_nextSmaller[i]; if (nextSmaller == -1) { leftdp[i] = m[i] * (i * 1L - (-1L)); } else { leftdp[i] = leftdp[nextSmaller] + m[i] * (i * 1L - nextSmaller); } } } long rightdp[] = new long[n]; rightdp[n - 1] = m[n - 1]; for (int i = n - 2; i >= 0; i--) { if (m[i + 1] <= m[i]) { rightdp[i] = rightdp[i + 1] + m[i]; } else { int nextSmaller = lr_nextSmaller[i]; if (nextSmaller == -1) { rightdp[i] = m[i] * (n * 1L - i * 1L); } else { rightdp[i] = rightdp[nextSmaller] + m[i] * (nextSmaller - i * 1L); } } } int max = 0; for (int i = 0; i < n; i++) { if ((leftdp[max] + rightdp[max] - m[max]) < (leftdp[i] + rightdp[i] - m[i])) { max = i; } } for (int i = max + 1; i < n; i++) { m[i] = Math.min(m[i - 1], m[i]); } for (int i = max - 1; i >= 0; i--) { m[i] = Math.min(m[i + 1], m[i]); } for (int i = 0; i < n; i++) { w.write(m[i] + "\n"); } } w.flush(); w.close(); } }
java
1288
B
B. Yet Another Meme Problemtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two integers AA and BB, calculate the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true; conc(a,b)conc(a,b) is the concatenation of aa and bb (for example, conc(12,23)=1223conc(12,23)=1223, conc(100,11)=10011conc(100,11)=10011). aa and bb should not contain leading zeroes.InputThe first line contains tt (1≤t≤1001≤t≤100) — the number of test cases.Each test case contains two integers AA and BB (1≤A,B≤109)(1≤A,B≤109).OutputPrint one integer — the number of pairs (a,b)(a,b) such that 1≤a≤A1≤a≤A, 1≤b≤B1≤b≤B, and the equation a⋅b+a+b=conc(a,b)a⋅b+a+b=conc(a,b) is true.ExampleInputCopy31 114 2191 31415926OutputCopy1 0 1337 NoteThere is only one suitable pair in the first test case: a=1a=1; b=9b=9 (1+9+1⋅9=191+9+1⋅9=19).
[ "math" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { static long M = (long) (1e9 + 7); static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { if (st.hasMoreTokens()) { str = st.nextToken("\n"); } else { str = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } return str; } } public static void heapify(int arr[], int n, int i) { int largest = i; int l = 2 * i + 1; int r = 2 * i + 2; if (l < n && arr[l] > arr[largest]) largest = l; if (r < n && arr[r] > arr[largest]) largest = r; if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; heapify(arr, n, largest); } } public static void swap(int[] a, int i, int j) { int temp = (int) a[i]; a[i] = a[j]; a[j] = temp; } public static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } public static int lcm(int a, int b) { return (a * b / gcd(a, b)); } public static String sortString(String inputString) { // Converting input string to character array char[] tempArray = inputString.toCharArray(); // Sorting temp array using Arrays.sort(tempArray); // Returning new sorted string return new String(tempArray); } static boolean isSquare(int n) { int v = (int) Math.sqrt(n); return v * v == n; } static boolean PowerOfTwo(int n) { if (n == 0) return false; return (int) (Math.ceil((Math.log(n) / Math.log(2)))) == (int) (Math.floor(((Math.log(n) / Math.log(2))))); } static int power(long a, long b) { long res = 1; while (b > 0) { if (b % 2 == 1) { res = (res * a) % M; } a = ((a * a) % M); b = b / 2; } return (int) res; } public static boolean isPrime(int n) { for (int i = 2; i * i <= n; i++) if (n % i == 0) { return false; } return true; } static int pown(long n) { if (n == 0) return 1; if (n == 1) return 1; if ((n & (~(n - 1))) == n) return 0; return 1; } static long computeXOR(long n) { // If n is a multiple of 4 if (n % 4 == 0) return n; // If n%4 gives remainder 1 if (n % 4 == 1) return 1; // If n%4 gives remainder 2 if (n % 4 == 2) return n + 1; // If n%4 gives remainder 3 return 0; } static long binaryToInteger(String binary) { char[] numbers = binary.toCharArray(); long result = 0; for (int i = numbers.length - 1; i >= 0; i--) if (numbers[i] == '1') result += Math.pow(2, (numbers.length - i - 1)); return result; } static String reverseString(String str) { char ch[] = str.toCharArray(); String rev = ""; for (int i = ch.length - 1; i >= 0; i--) { rev += ch[i]; } return rev; } static int countFreq(int[] arr, int n) { HashMap<Integer, Integer> map = new HashMap<>(); int x = 0; for (int i = 0; i < n; i++) { map.put(arr[i], map.getOrDefault(arr[i], 0) + 1); } for (int i = 0; i < n; i++) { if (map.get(arr[i]) == 1) x++; } return x; } static boolean symm(String str){ if(str.length()==1|| str.length()==0) return true; if (str.substring(0, (str.length() / 2)).equals(str.substring(str.length() / 2))) return symm(str.substring(0,(str.length()/2))); return false; } public static void main(String[] args) throws Exception { FastReader sc = new FastReader(); int t = sc.nextInt(); while (t-- != 0) { long a=sc.nextLong(); long b=sc.nextLong(); System.out.println(a*(long)Math.log10(b+1)); } } }
java
1285
B
B. Just Eat It!time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputToday; Yasser and Adel are at the shop buying cupcakes. There are nn cupcake types, arranged from 11 to nn on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type ii is an integer aiai. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.Yasser, of course, wants to try them all, so he will buy exactly one cupcake of each type.On the other hand, Adel will choose some segment [l,r][l,r] (1≤l≤r≤n)(1≤l≤r≤n) that does not include all of cupcakes (he can't choose [l,r]=[1,n][l,r]=[1,n]) and buy exactly one cupcake of each of types l,l+1,…,rl,l+1,…,r.After that they will compare the total tastiness of the cupcakes each of them have bought. Yasser will be happy if the total tastiness of cupcakes he buys is strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice.For example, let the tastinesses of the cupcakes be [7,4,−1][7,4,−1]. Yasser will buy all of them, the total tastiness will be 7+4−1=107+4−1=10. Adel can choose segments [7],[4],[−1],[7,4][7],[4],[−1],[7,4] or [4,−1][4,−1], their total tastinesses are 7,4,−1,117,4,−1,11 and 33, respectively. Adel can choose segment with tastiness 1111, and as 1010 is not strictly greater than 1111, Yasser won't be happy :(Find out if Yasser will be happy after visiting the shop.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 nn (2≤n≤1052≤n≤105).The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−109≤ai≤109−109≤ai≤109), where aiai represents the tastiness of the ii-th type of cupcake.It is guaranteed that the sum of nn over all test cases doesn't exceed 105105.OutputFor each test case, print "YES", if the total tastiness of cupcakes Yasser buys will always be strictly greater than the total tastiness of cupcakes Adel buys regardless of Adel's choice. Otherwise, print "NO".ExampleInputCopy3 4 1 2 3 4 3 7 4 -1 3 5 -5 5 OutputCopyYES NO NO NoteIn the first example; the total tastiness of any segment Adel can choose is less than the total tastiness of all cupcakes.In the second example; Adel will choose the segment [1,2][1,2] with total tastiness 1111, which is not less than the total tastiness of all cupcakes, which is 1010.In the third example, Adel can choose the segment [3,3][3,3] with total tastiness of 55. Note that Yasser's cupcakes' total tastiness is also 55, so in that case, the total tastiness of Yasser's cupcakes isn't strictly greater than the total tastiness of Adel's cupcakes.
[ "dp", "greedy", "implementation" ]
import java.math.BigInteger; import java.util.*; import static java.lang.Math.*; public class Main{ public static void main(String args[]){ Scanner sc=new Scanner(System.in); int testcase=sc.nextInt(); for(int tc=1;tc<=testcase;tc++){ //System.out.print("Case #"+tc+": "); int n = sc.nextInt(); int a[] = new int[n]; long sum = 0, max = 0; for(int i=0;i<n;i++){ a[i] = sc.nextInt(); sum += a[i]; } int b[] = Arrays.copyOf(a, n); int c[] = Arrays.copyOf(a, n); b[0] = 0; c[n-1] = 0; max = Math.max(maxSubArraySum(b), maxSubArraySum(c)); if(sum > max) System.out.println("YES"); else System.out.println("NO"); } sc.close(); } static long maxSubArraySum(int a[]) { int size = a.length; long max_so_far = Long.MIN_VALUE, max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } return max_so_far; } static long fact(long n) { // single line to find factorial return (n == 1 || n == 0) ? 1 : n * fact(n - 1); } static boolean isSorted(int a[]){ for(int i=1;i<a.length;i++){ if(a[i] < a[i-1]) return false; } return true; } static int gcd(int a, int 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 int upper_bound(int[] arr, int key, int i) { if(Arrays.binarySearch(arr, key) >= 0) return Arrays.binarySearch(arr, key); int mid, N = arr.length; // Initialise starting index and // ending index int low = 0; int high = i; // Till low is less than high while (low < high && low != N) { // Find the index of the middle element mid = low + (high - low) / 2; // If key is greater than or equal // to arr[mid], then find in // right subarray if (key >= arr[mid]) { low = mid + 1; } // If key is less than arr[mid] // then find in left subarray else { high = mid; } } return low; } static int lower_bound(int[] arr, int key, int i) { if(Arrays.binarySearch(arr, key) >= 0) return Arrays.binarySearch(arr, key); // Initialize starting index and // ending index int low = 0, high = i; int mid; // Till high does not crosses low while (low < high) { // Find the index of the middle element mid = low + (high - low) / 2; // If key is less than or equal // to array[mid], then find in // left subarray if (key <= arr[mid]) { high = mid; } // If key is greater than array[mid], // then find in right subarray else { low = mid + 1; } } return low; } static boolean palin(int arr[], int i, int j){ while(i < j){ if(arr[i] != arr[j]) return false; i++; j--; } return true; } static boolean palin(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; } static long minSum(int arr[], int n, int k) { // k must be smaller than n if (n < k) { // System.out.println("Invalid"); return -1; } // Compute sum of first window of size k long res = 0; for (int i=0; i<k; i++) res += arr[i]; // Compute sums of remaining windows by // removing first element of previous // window and adding last element of // current window. long curr_sum = res; for (int i=k; i<n; i++) { curr_sum += arr[i] - arr[i-k]; res = Math.min(res, curr_sum); } return res; } static int nextIndex(int a[], int x){ int n=a.length; for(int i=x;i<n-1;i++){ if(a[i]>a[i+1]){ return i; } } return n; } static void rev(int a[], int i, int j){ while(i<j){ int t=a[i]; a[i]=a[j]; a[j]=t; i++; j--; } } static int sorted(int arr[], int n) { // Array has one or no element or the // rest are already checked and approved. if (n == 1 || n == 0) return 1; // Unsorted pair found (Equal values allowed) if (arr[n - 1] < arr[n - 2]) return 0; // Last pair was sorted // Keep on checking return sorted(arr, n - 1); } static void sieveOfEratosthenes(int n, int a[]) { for(int i=2;i<=n;i++){ a[i]=1; } for(int i=2;i<=1000;i++){ for(int j=2*i;j<=n;j+=i){ a[j]=0; } } } static boolean isPowerOfTwo(int n) { return (int)(Math.ceil((Math.log(n) / Math.log(2)))) == (int)(Math.floor(((Math.log(n) / Math.log(2))))); } static int countBits(int number) { // log function in base 2 // take only integer part return (int)(Math.log(number) / Math.log(2) + 1); } public static void swap(int ans[], int i, int j) { int temp=ans[i]; ans[i]=ans[j]; ans[j]=temp; } static int power(int x, int y, int p) { int res = 1; // Initialize result x = x % p; // Update x if it is more than or // equal to p if (x == 0) return 0; // In case x is divisible by p; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0) res = (res * x) % p; // y must be even now y = y >> 1; // y = y/2 x = (x * x) % p; } return res; } }
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) { lo=mid+1; } else { if(sum>right) hi=mid-1; else{ ans=mid; 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) { lo=mid+1; } else { if(sum>right) hi=mid-1; else{ ans=mid; lo=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; int tmp[]=new int[n]; for(int b=0;b<26;b++) { 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
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.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.sort; public class Round12 { public static void main(String[] args) { FastReader fastReader = new FastReader(); PrintWriter out = new PrintWriter(System.out); int t = fastReader.nextInt(); while (t-- > 0) { int n = fastReader.nextInt(); int a[] = fastReader.ria(n); int i; int pos = 0; for (i = 0; i < n; ++i) { if (a[i] > -1) ++pos; } if(pos == 0) { out.println(0 + " " + 1); continue; } int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; for (i = 0; i < n; ++i) { if (a[i] != -1 && ((i - 1 >= 0 && a[i - 1] == -1) || (i + 1 < n && a[i + 1] == -1))) { max = Math.max(max, a[i]); min = Math.min(min, a[i]); } } int k1 = (max + min) / 2; for (i = 0; i < n; ++i) if (a[i] == -1) a[i] = k1; int m1 = 0; for (i = 1; i < n; ++i) m1 = Math.max(m1, Math.abs(a[i] - a[i - 1])); int m = m1; out.println(m + " " + k1); } out.close(); } // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final long LMAX = 92233720368547L; 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
1304
B
B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has nn distinct strings of equal length mm. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers nn and mm (1≤n≤1001≤n≤100, 1≤m≤501≤m≤50) — the number of strings and the length of each string.Next nn lines contain a string of length mm each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInputCopy3 3 tab one bat OutputCopy6 tabbat InputCopy4 2 oo ox xo xx OutputCopy6 oxxxxo InputCopy3 5 hello codef orces OutputCopy0 InputCopy9 4 abab baba abcd bcde cdef defg wxyz zyxw ijji OutputCopy20 ababwxyzijjizyxwbaba NoteIn the first example; "battab" is also a valid answer.In the second example; there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example; the empty string is the only valid palindrome string.
[ "brute force", "constructive algorithms", "greedy", "implementation", "strings" ]
import java.util.*; import java.io.*; public class Practice { static boolean multipleTC = false; final static int mod = 1000000007; final static int mod2 = 998244353; final double E = 2.7182818284590452354; final double PI = 3.14159265358979323846; int MAX = 10000005; void pre() throws Exception { } // All the best void solve(int TC) throws Exception { int n = ni(), m = ni(); String arr[] = new String[n]; for (int i = 0; i < n; i++) { arr[i] = nln(); } boolean picked[] = new boolean[n]; ArrayList<pair> res = new ArrayList<>(); outer: for (int i = 0; i < n; i++) { if (picked[i]) continue; inner: for (int j = i + 1; j < n; j++) { if (picked[i]) continue inner; if (ok(arr[i], arr[j])) { picked[i] = true; picked[j] = true; res.add(new pair(i, j)); continue outer; } } } StringBuilder ans = new StringBuilder(); outer: for (int i = 0; i < n; i++) { if (!picked[i]) { for (int k = 0; k < m; k++) { if (arr[i].charAt(k) != arr[i].charAt(m - k - 1)) { continue outer; } } ans.append(arr[i]); break; } } for (pair p : res) { ans.append(arr[p.x]); ans.insert(0, arr[p.y]); } pn(ans.length()); pn(ans); } class pair { int x, y; pair(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { return "(" + x + "," + y + ")"; } } boolean ok(String s1, String s2) { char a1[] = s1.toCharArray(); char a2[] = s2.toCharArray(); int n = s1.length(); for (int i = 0; i < n; i++) { if (a1[i] != a2[n - i - 1]) { return false; } } return true; } void leftRotatebyOne(int arr[], int n) { int temp = arr[0], i; for (i = 0; i < n - 1; i++) arr[i] = arr[i + 1]; arr[n - 1] = temp; } boolean isFibo(int arr[]) { int n = arr.length; for (int i = 0; i + 2 < n; i++) { if (arr[i] + arr[i + 1] == arr[i + 2]) { return true; } } return false; } public void permute(int[] arr) { permuteHelper(arr, 0); } ArrayList<int[]> perm = new ArrayList<>(); private void permuteHelper(int[] arr, int index) { if (index >= arr.length - 1) { perm.add(arr.clone()); return; } if (perm.size() > 3 * arr.length) { return; } for (int i = index; i < arr.length; i++) { int t = arr[index]; arr[index] = arr[i]; arr[i] = t; permuteHelper(arr, index + 1); t = arr[index]; arr[index] = arr[i]; arr[i] = t; } } int[] readArr(int n) throws Exception { int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = ni(); } return arr; } void sort(int arr[], int left, int right) { ArrayList<Integer> list = new ArrayList<>(); for (int i = left; i <= right; i++) list.add(arr[i]); Collections.sort(list); for (int i = left; i <= right; i++) arr[i] = list.get(i - left); } void sort(int arr[]) { ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < arr.length; i++) list.add(arr[i]); Collections.sort(list); for (int i = 0; i < arr.length; i++) arr[i] = list.get(i); } public long max(long... arr) { long max = arr[0]; for (long itr : arr) max = Math.max(max, itr); return max; } public int max(int... arr) { int max = arr[0]; for (int itr : arr) max = Math.max(max, itr); return max; } public long min(long... arr) { long min = arr[0]; for (long itr : arr) min = Math.min(min, itr); return min; } public int min(int... arr) { int min = arr[0]; for (int itr : arr) min = Math.min(min, itr); return min; } public long sum(long... arr) { long sum = 0; for (long itr : arr) sum += itr; return sum; } public long sum(int... arr) { long sum = 0; for (int itr : arr) sum += itr; return sum; } String bin(long n) { return Long.toBinaryString(n); } String bin(int n) { return Integer.toBinaryString(n); } static int bitCount(int x) { return x == 0 ? 0 : (1 + bitCount(x & (x - 1))); } static void dbg(Object... o) { System.err.println(Arrays.deepToString(o)); } int bit(long n) { return (n == 0) ? 0 : (1 + bit(n & (n - 1))); } int abs(int a) { return (a < 0) ? -a : a; } long abs(long a) { return (a < 0) ? -a : a; } void p(Object o) { out.print(o); } void pn(Object o) { out.println(o); } void pni(Object o) { out.println(o); out.flush(); } String n() throws Exception { return in.next(); } String nln() throws Exception { return in.nextLine(); } int ni() throws Exception { return Integer.parseInt(in.next()); } long nl() throws Exception { return Long.parseLong(in.next()); } double nd() throws Exception { return Double.parseDouble(in.next()); } public static void main(String[] args) throws Exception { new Practice().run(); } FastReader in; PrintWriter out; void run() throws Exception { in = new FastReader(); out = new PrintWriter(System.out); int T = (multipleTC) ? ni() : 1; pre(); for (int t = 1; t <= T; t++) solve(t); out.flush(); out.close(); } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws Exception { br = new BufferedReader(new FileReader(s)); } String next() throws Exception { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new Exception(e.toString()); } } return st.nextToken(); } String nextLine() throws Exception { String str = ""; try { str = br.readLine(); } catch (IOException e) { throw new Exception(e.toString()); } return str; } } }
java
1295
E
E. Permutation Separationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a permutation p1,p2,…,pnp1,p2,…,pn (an array where each integer from 11 to nn appears exactly once). The weight of the ii-th element of this permutation is aiai.At first, you separate your permutation into two non-empty sets — prefix and suffix. More formally, the first set contains elements p1,p2,…,pkp1,p2,…,pk, the second — pk+1,pk+2,…,pnpk+1,pk+2,…,pn, where 1≤k<n1≤k<n.After that, you may move elements between sets. The operation you are allowed to do is to choose some element of the first set and move it to the second set, or vice versa (move from the second set to the first). You have to pay aiai dollars to move the element pipi.Your goal is to make it so that each element of the first set is less than each element of the second set. Note that if one of the sets is empty, this condition is met.For example, if p=[3,1,2]p=[3,1,2] and a=[7,1,4]a=[7,1,4], then the optimal strategy is: separate pp into two parts [3,1][3,1] and [2][2] and then move the 22-element into first set (it costs 44). And if p=[3,5,1,6,2,4]p=[3,5,1,6,2,4], a=[9,1,9,9,1,9]a=[9,1,9,9,1,9], then the optimal strategy is: separate pp into two parts [3,5,1][3,5,1] and [6,2,4][6,2,4], and then move the 22-element into first set (it costs 11), and 55-element into second set (it also costs 11).Calculate the minimum number of dollars you have to spend.InputThe first line contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of permutation.The second line contains nn integers p1,p2,…,pnp1,p2,…,pn (1≤pi≤n1≤pi≤n). It's guaranteed that this sequence contains each element from 11 to nn exactly once.The third line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109).OutputPrint one integer — the minimum number of dollars you have to spend.ExamplesInputCopy3 3 1 2 7 1 4 OutputCopy4 InputCopy4 2 4 1 3 5 9 8 3 OutputCopy3 InputCopy6 3 5 1 6 2 4 9 1 9 9 1 9 OutputCopy2
[ "data structures", "divide and conquer" ]
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ work(); out.flush(); } long mod=998244353; long gcd(long a,long b) { return a==0?b:gcd(b%a,a); } void work() { int n=ni(); int[] A=nia(n); long[] W=na(n); long[] sum=new long[n]; for(int i=0;i<n;i++) { sum[A[i]]=W[i]; } for(int i=1;i<n;i++) { sum[i]+=sum[i-1]; } Node root=new Node(); for(int i=0;i<n;i++) { update(root,0,n-1,i,i,sum[i]); } long ret=Long.MAX_VALUE; long s=0; for(int i=0;i<n-1;i++) { int node=A[i]; long w=W[i]; s+=w;//前缀空集 update(root,0,n-1,node,n-1,-w); if(node!=0)update(root,0,n-1,0,node-1,w); ret=Math.min(ret, root.min); ret=Math.min(ret, s); } out.println(ret); } void u2(Node node,long v) { node.min+=v; node.lazy+=v; } void updatelazy(Node node) { u2(getLnode(node),node.lazy); u2(getRnode(node),node.lazy); node.lazy=0; } private void update(Node node, int l, int r, int s,int e,long v) { if(l>=s&&r<=e) { node.min+=v; node.lazy+=v; return; } updatelazy(node); int m=l+(r-l)/2; if(m>=s) { update(getLnode(node),l,m,s,e,v); } if(m+1<=e) { update(getRnode(node),m+1,r,s,e,v); } node.min=Math.min(getLnode(node).min,getRnode(node).min);//左右节点可能有lazy标记 } private Node getLnode(Node node) { if(node.lnode==null)node.lnode=new Node(); return node.lnode; } private Node getRnode(Node node) { if(node.rnode==null)node.rnode=new Node(); return node.rnode; } class Node{ Node lnode,rnode; long lazy; long min; } //input private ArrayList<Integer>[] ng(int n, int m) { ArrayList<Integer>[] graph=(ArrayList<Integer>[])new ArrayList[n]; for(int i=0;i<n;i++) { graph[i]=new ArrayList<>(); } for(int i=1;i<=m;i++) { int s=in.nextInt()-1,e=in.nextInt()-1; graph[s].add(e); graph[e].add(s); } return graph; } private int ni() { return in.nextInt(); } private long nl() { return in.nextLong(); } private long[] na(int n) { long[] A=new long[n]; for(int i=0;i<n;i++) { A[i]=in.nextLong(); } return A; } private int[] nia(int n) { int[] A=new int[n]; for(int i=0;i<n;i++) { A[i]=in.nextInt()-1;// } return A; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { while(st==null || !st.hasMoreElements())//回车,空行情况 { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
java
1320
B
B. Navigation Systemtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe map of Bertown can be represented as a set of nn intersections, numbered from 11 to nn and connected by mm one-way roads. It is possible to move along the roads from any intersection to any other intersection. The length of some path from one intersection to another is the number of roads that one has to traverse along the path. The shortest path from one intersection vv to another intersection uu is the path that starts in vv, ends in uu and has the minimum length among all such paths.Polycarp lives near the intersection ss and works in a building near the intersection tt. Every day he gets from ss to tt by car. Today he has chosen the following path to his workplace: p1p1, p2p2, ..., pkpk, where p1=sp1=s, pk=tpk=t, and all other elements of this sequence are the intermediate intersections, listed in the order Polycarp arrived at them. Polycarp never arrived at the same intersection twice, so all elements of this sequence are pairwise distinct. Note that you know Polycarp's path beforehand (it is fixed), and it is not necessarily one of the shortest paths from ss to tt.Polycarp's car has a complex navigation system installed in it. Let's describe how it works. When Polycarp starts his journey at the intersection ss, the system chooses some shortest path from ss to tt and shows it to Polycarp. Let's denote the next intersection in the chosen path as vv. If Polycarp chooses to drive along the road from ss to vv, then the navigator shows him the same shortest path (obviously, starting from vv as soon as he arrives at this intersection). However, if Polycarp chooses to drive to another intersection ww instead, the navigator rebuilds the path: as soon as Polycarp arrives at ww, the navigation system chooses some shortest path from ww to tt and shows it to Polycarp. The same process continues until Polycarp arrives at tt: if Polycarp moves along the road recommended by the system, it maintains the shortest path it has already built; but if Polycarp chooses some other path, the system rebuilds the path by the same rules.Here is an example. Suppose the map of Bertown looks as follows, and Polycarp drives along the path [1,2,3,4][1,2,3,4] (s=1s=1, t=4t=4): Check the picture by the link http://tk.codeforces.com/a.png When Polycarp starts at 11, the system chooses some shortest path from 11 to 44. There is only one such path, it is [1,5,4][1,5,4]; Polycarp chooses to drive to 22, which is not along the path chosen by the system. When Polycarp arrives at 22, the navigator rebuilds the path by choosing some shortest path from 22 to 44, for example, [2,6,4][2,6,4] (note that it could choose [2,3,4][2,3,4]); Polycarp chooses to drive to 33, which is not along the path chosen by the system. When Polycarp arrives at 33, the navigator rebuilds the path by choosing the only shortest path from 33 to 44, which is [3,4][3,4]; Polycarp arrives at 44 along the road chosen by the navigator, so the system does not have to rebuild anything. Overall, we get 22 rebuilds in this scenario. Note that if the system chose [2,3,4][2,3,4] instead of [2,6,4][2,6,4] during the second step, there would be only 11 rebuild (since Polycarp goes along the path, so the system maintains the path [3,4][3,4] during the third step).The example shows us that the number of rebuilds can differ even if the map of Bertown and the path chosen by Polycarp stays the same. Given this information (the map and Polycarp's path), can you determine the minimum and the maximum number of rebuilds that could have happened during the journey?InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105) — the number of intersections and one-way roads in Bertown, respectively.Then mm lines follow, each describing a road. Each line contains two integers uu and vv (1≤u,v≤n1≤u,v≤n, u≠vu≠v) denoting a road from intersection uu to intersection vv. All roads in Bertown are pairwise distinct, which means that each ordered pair (u,v)(u,v) appears at most once in these mm lines (but if there is a road (u,v)(u,v), the road (v,u)(v,u) can also appear).The following line contains one integer kk (2≤k≤n2≤k≤n) — the number of intersections in Polycarp's path from home to his workplace.The last line contains kk integers p1p1, p2p2, ..., pkpk (1≤pi≤n1≤pi≤n, all these integers are pairwise distinct) — the intersections along Polycarp's path in the order he arrived at them. p1p1 is the intersection where Polycarp lives (s=p1s=p1), and pkpk is the intersection where Polycarp's workplace is situated (t=pkt=pk). It is guaranteed that for every i∈[1,k−1]i∈[1,k−1] the road from pipi to pi+1pi+1 exists, so the path goes along the roads of Bertown. OutputPrint two integers: the minimum and the maximum number of rebuilds that could have happened during the journey.ExamplesInputCopy6 9 1 5 5 4 1 2 2 3 3 4 4 1 2 6 6 4 4 2 4 1 2 3 4 OutputCopy1 2 InputCopy7 7 1 2 2 3 3 4 4 5 5 6 6 7 7 1 7 1 2 3 4 5 6 7 OutputCopy0 0 InputCopy8 13 8 7 8 6 7 5 7 4 6 5 6 4 5 3 5 2 4 3 4 2 3 1 2 1 1 8 5 8 7 5 2 1 OutputCopy0 3
[ "dfs and similar", "graphs", "shortest paths" ]
import java.util.*; public class Main { static int N = 200005; public static void main(String[] args) { int[]d = new int[N]; int n,m,k; Scanner sc = new Scanner(System.in); n = sc.nextInt(); m = sc.nextInt(); List<List<Integer>> e = g(n + 1); List<List<Integer>> re = g(n + 1); for (int i = 0; i < m; i++) { int f = sc.nextInt(); int t = sc.nextInt(); e.get(f).add(t); re.get(t).add(f); } k = sc.nextInt(); ArrayList<Integer>p = new ArrayList<>(); p.add(0); for (int i = 0; i < k; i++) { p.add(sc.nextInt()); } Queue<Integer> queue = new LinkedList<>(); queue.add(p.get(k)); d[p.get(k)] = 1; while (!queue.isEmpty()){ Integer x = queue.poll(); for(int i : re.get(x)){ if(d[i] == 0){ d[i] = d[x] + 1; queue.add(i); } } } int ans1 = 0,ans2 = 0; for(int i = 1;i < k;i++){ if(d[p.get(i)] < d[p.get(i + 1)] + 1){ ans1++; } boolean add = false; for(int y : e.get(p.get(i))){ if(y != p.get(i + 1) && d[p.get(i)] == d[y] + 1) add = true; } ans2 += add ? 1 : 0; } System.out.println(ans1 + " " + ans2); } private static List<List<Integer>> g(int len){ List<List<Integer>>g = new ArrayList<>(); for (int i = 0; i < len; i++) { g.add(new ArrayList<>()); } return g; } }
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" ]
// practice with rainboy import java.io.*; import java.util.*; public class CF1288E extends PrintWriter { CF1288E() { super(System.out); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1288E o = new CF1288E(); o.main(); o.flush(); } int[] ft; void update(int i, int n, int x) { while (i < n) { ft[i] += x; i |= i + 1; } } int query(int i) { int x = 0; while (i >= 0) { x += ft[i]; i &= i + 1; i--; } return x; } void main() { int n = sc.nextInt(); int m = sc.nextInt(); int[] ii = new int[m]; for (int h = 0; h < m; h++) ii[h] = sc.nextInt() - 1; int[] imin = new int[n]; int[] imax = new int[n]; for (int i = 0; i < n; i++) imin[i] = imax[i] = i; for (int h = 0; h < m; h++) imin[ii[h]] = 0; int[] hh = new int[n]; Arrays.fill(hh, m); for (int h = m - 1; h >= 0; h--) hh[ii[h]] = h; ft = new int[m]; for (int i = n - 1; i >= 0; i--) { imax[i] += query(hh[i] - 1); update(hh[i], m, 1); } Arrays.fill(ft, 0); Arrays.fill(hh, m); for (int h = m - 1; h >= 0; h--) { int i = ii[h]; imax[i] = Math.max(imax[i], query(hh[i] - 1)); update(hh[i], m, -1); hh[i] = h; update(hh[i], m, 1); } for (int i = 0; i < n; i++) println((imin[i] + 1) + " " + (imax[i] + 1)); } }
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.util.Scanner; public class EvenButNotEven { public static void main(String[] args) { Scanner in = new Scanner(System.in); int t = in.nextInt(); for ( int p = 0; p < t; p++){ int n = in.nextInt(); StringBuilder s = new StringBuilder(in.next()); int count = 0; for ( int i = 0; i < n; i++){ if (s.charAt(i) % 2 != 0){ count++; } } if ( count == 0 || count == 1){ System.out.println("-1"); } if(count % 2 == 0 && count!=0){ while(s.charAt(s.length()-1) % 2 == 0){ s.replace(s.length()-1,s.length(),""); } System.out.println(s); } else if (count != 1 && count % 2 != 0){ while(s.charAt(s.length()-1) % 2 == 0){ s.replace(s.length()-1,s.length(),""); } s.replace(s.length()-1,s.length(),""); while(s.charAt(s.length()-1) % 2 == 0){ s.replace(s.length()-1,s.length(),""); } if(s.length() == 0){ System.out.println("-1"); } else{ System.out.println(s); } } } } }
java
1296
C
C. Yet Another Walking Robottime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere is a robot on a coordinate plane. Initially; the robot is located at the point (0,0)(0,0). Its path is described as a string ss of length nn consisting of characters 'L', 'R', 'U', 'D'.Each of these characters corresponds to some move: 'L' (left): means that the robot moves from the point (x,y)(x,y) to the point (x−1,y)(x−1,y); 'R' (right): means that the robot moves from the point (x,y)(x,y) to the point (x+1,y)(x+1,y); 'U' (up): means that the robot moves from the point (x,y)(x,y) to the point (x,y+1)(x,y+1); 'D' (down): means that the robot moves from the point (x,y)(x,y) to the point (x,y−1)(x,y−1). The company that created this robot asked you to optimize the path of the robot somehow. To do this, you can remove any non-empty substring of the path. But this company doesn't want their customers to notice the change in the robot behavior. It means that if before the optimization the robot ended its path at the point (xe,ye)(xe,ye), then after optimization (i.e. removing some single substring from ss) the robot also ends its path at the point (xe,ye)(xe,ye).This optimization is a low-budget project so you need to remove the shortest possible non-empty substring to optimize the robot's path such that the endpoint of his path doesn't change. It is possible that you can't optimize the path. Also, it is possible that after the optimization the target path is an empty string (i.e. deleted substring is the whole string ss).Recall that the substring of ss is such string that can be obtained from ss by removing some amount of characters (possibly, zero) from the prefix and some amount of characters (possibly, zero) from the suffix. For example, the substrings of "LURLLR" are "LU", "LR", "LURLLR", "URL", but not "RR" and "UL".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 next 2t2t lines describe test cases. Each test case is given on two lines. The first line of the test case contains one integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the robot's path. The second line of the test case contains one string ss consisting of nn characters 'L', 'R', 'U', 'D' — the robot's path.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105 (∑n≤2⋅105∑n≤2⋅105).OutputFor each test case, print the answer on it. If you cannot remove such non-empty substring that the endpoint of the robot's path doesn't change, print -1. Otherwise, print two integers ll and rr such that 1≤l≤r≤n1≤l≤r≤n — endpoints of the substring you remove. The value r−l+1r−l+1 should be minimum possible. If there are several answers, print any of them.ExampleInputCopy4 4 LRUD 4 LURD 5 RRUDU 5 LLDDR OutputCopy1 2 1 4 3 4 -1
[ "data structures", "implementation" ]
/* It's always like another kick for me to make sure I get what I want to get done, because honestly you never know. */ import java.util.*; import java.io.*; import static java.lang.Math.*; public class Main extends PrintWriter { Main() { super(System.out); } static boolean cases = true; // Solution void solve() { int n = sc.nextInt(); char a[] = sc.readCharArray(n); HashMap<String, Integer> map = new HashMap<>(); int ans[] = { 0, 0 }; int c[] = { 0, 0 }; map.put(0 + " " + 0, -1); boolean f = false; for (int i = 0; i < n; i++) { char ch = a[i]; if (ch == 'L') c[0]--; else if (ch == 'R') c[0]++; else if (ch == 'U') c[1]++; else if (ch == 'D') c[1]--; if (map.containsKey(c[0] + " " + c[1])) { int s = map.get(c[0] + " " + c[1]); int e = i; if (!f || ((ans[1] - ans[0] + 1) > (e - s + 1))) { ans[0] = s + 2; ans[1] = e + 1; f = true; } } map.put(c[0] + " " + c[1], i); } System.out.println(!f ? -1 : (ans[0] + " " + ans[1])); } void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } public static void main(String[] args) { Main obj = new Main(); int c = 1; for (int t = (cases ? sc.nextInt() : 0); t > 1; t--, c++) obj.solve(); obj.solve(); obj.flush(); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } char[] readCharArray(int n) { char a[] = new char[n]; String s = sc.next(); for (int i = 0; i < n; i++) { a[i] = s.charAt(i); } return a; } long[] readLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } final int ima = Integer.MAX_VALUE; final int imi = Integer.MIN_VALUE; final long lma = Long.MAX_VALUE; final long lmi = Long.MIN_VALUE; static final long mod = (long) 1e9 + 7; private static final FastScanner sc = new FastScanner(); private PrintWriter out = new PrintWriter(System.out); }
java
1305
C
C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10 8 5 OutputCopy3InputCopy3 12 1 4 5 OutputCopy0InputCopy3 7 1 4 9 OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7.
[ "brute force", "combinatorics", "math", "number theory" ]
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class JaiShreeRam{ static Scanner in=new Scanner(); static long systemTime; static long mod = 1000000007; static ArrayList<ArrayList<Integer>> adj; static int seive[]=new int[1000001]; static long C[][]; static int fen[]=new int[4*100005]; static long nt=0; static ArrayList<Integer> ans=new ArrayList<>(); public static void main(String[] args) throws Exception{ int z=1; for(int test=1;test<=z;test++) { //setTime(); solve(); //printTime(); //printMemory(); } } static void solve() { int n=in.readInt(); long m=in.readInt(); long a[]=nla(n); if(n>m) { print(0); return; } long product=1; for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++){ product*=Math.abs(a[i]-a[j]); product%=m; } } print(product); } static long pow(long n, long m) { if(m==0) return 1; else if(m==1) return n; else { long r=pow(n,m/2); if(m%2==0) return (r*r); else return (r*r*n); } } static long maxsumsub(ArrayList<Long> al) { long max=0; long sum=0; for(int i=0;i<al.size();i++) { sum+=al.get(i); if(sum<0) { sum=0; } max=Math.max(max,sum); } return max; } static long abs(long a) { return Math.abs(a); } static void ncr(int n, int k){ C= new long[n + 1][k + 1]; int i, j; for (i = 0; i <= n; i++) { for (j = 0; j <= Math.min(i, k); j++) { if (j == 0 || j == i) C[i][j] = 1; else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } } static boolean isPalin(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; } static int knapsack(int W, int wt[],int val[], int n){ int []dp = new int[W + 1]; for (int i = 1; i < n + 1; i++) { for (int w = W; w >= 0; w--) { if (wt[i - 1] <= w) { dp[w] = Math.max(dp[w],dp[w - wt[i - 1]] + val[i - 1]); } } } return dp[W]; } static void seive() { Arrays.fill(seive, 1); seive[0]=0; seive[1]=0; for(int i=2;i*i<1000001;i++) { if(seive[i]==1) { for(int j=i*i;j<1000001;j+=i) { if(seive[j]==1) { seive[j]=0; } } } } } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void sort(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static int[] nia(int n){ int[] arr= new int[n]; int i=0; while(i<n){ arr[i++]=in.readInt(); } return arr; } static long[] nla(int n){ long[] arr= new long[n]; int i=0; while(i<n){ arr[i++]=in.readLong(); } return arr; } static int[] nia1(int n){ int[] arr= new int[n+1]; int i=1; while(i<=n){ arr[i++]=in.readInt(); } return arr; } static Integer[] nIa(int n){ Integer[] arr= new Integer[n]; int i=0; while(i<n){ arr[i++]=in.readInt(); } return arr; } static Long[] nLa(int n){ Long[] arr= new Long[n]; int i=0; while(i<n){ arr[i++]=in.readLong(); } return arr; } static long gcd(long a, long b) { if (b==0) return a; return gcd(b, a%b); } static void print(long i) { System.out.println(i); } static void print(Object o) { System.out.println(o); } static void print(int a[]) { for(int i:a) { System.out.print(i+" "); } System.out.println(); } static void print(long a[]) { for(long i:a) { System.out.print(i+" "); } System.out.println(); } static void print(ArrayList<Long> a) { for(long i:a) { System.out.print(i+" "); } System.out.println(); } static void print(Object a[]) { for(Object i:a) { System.out.print(i+" "); } System.out.println(); } static void setTime() { systemTime = System.currentTimeMillis(); } static void printTime() { System.err.println("Time consumed: " + (System.currentTimeMillis() - systemTime)); } static void printMemory() { System.err.println("Memory consumed: " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1000 + "kb"); } static class Scanner{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String readString() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } double readDouble() { return Double.parseDouble(readString()); } int readInt() { return Integer.parseInt(readString()); } long readLong() { return Long.parseLong(readString()); } } }
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.*; import java.lang.*; import java.io.*; public class Main { public static void main (String[] args) throws java.lang.Exception { Scanner scn = new Scanner(System.in); int n = scn.nextInt(); int m = scn.nextInt(); long[][] arr = new long[n][m]; for(int i=0; i<n; i++) { for(int j=0; j<m; j++) arr[i][j] = scn.nextLong(); } long ans = 0; for(int col=0; col<m; col++) { // Frequency Array Corresponding to Count of Elements to given Cyclic Shift // freq[i] = Elements in Right Position for ith cyclic shift long[] freq = new long[n]; for(int row = 0; row < n; row++) { long desiredRow = (arr[row][col] - (col + 1l)) / m; if(arr[row][col] % m == (col + 1) % m && desiredRow >= 0 && desiredRow <= n-1) { if(desiredRow <= row) freq[row - (int)desiredRow]++; else freq[n + row - (int)desiredRow]++; } } long minOperations = n; for(int i=0; i<n; i++) { // Operations = Changes in Values (n - freq[i]) + Cyclic Shifts (i) long totalOperations = (n - freq[i]) + i; minOperations = Math.min(minOperations, totalOperations); } ans += minOperations; } System.out.println(ans); } }
java
13
A
A. Numberstime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.Note that all computations should be done in base 10. You should find the result as an irreducible fraction; written in base 10.InputInput contains one integer number A (3 ≤ A ≤ 1000).OutputOutput should contain required average value in format «X/Y», where X is the numerator and Y is the denominator.ExamplesInputCopy5OutputCopy7/3InputCopy3OutputCopy2/1NoteIn the first sample number 5 written in all bases from 2 to 4 looks so: 101, 12, 11. Sums of digits are 2, 3 and 2, respectively.
[ "implementation", "math" ]
import java.util.Scanner; public class Main { public static int n; public static int b; public static int a; public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); b = n-2; a = 0; for (int i = 2; i < n; i++) { for (int j = n; j > 0 ; j = j / i) { a += j % i; } } fix(); System.out.println(a + "/" + b); System.out.flush(); } public static void fix() { for (int i = 2; i <= b; i++) { if (b % i == 0 && a % i == 0) { b /= i; a /= i; fix(); } } } }
java
1321
A
A. Contest for Robotstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp is preparing the first programming contest for robots. There are nn problems in it, and a lot of robots are going to participate in it. Each robot solving the problem ii gets pipi points, and the score of each robot in the competition is calculated as the sum of pipi over all problems ii solved by it. For each problem, pipi is an integer not less than 11.Two corporations specializing in problem-solving robot manufacturing, "Robo-Coder Inc." and "BionicSolver Industries", are going to register two robots (one for each corporation) for participation as well. Polycarp knows the advantages and flaws of robots produced by these companies, so, for each problem, he knows precisely whether each robot will solve it during the competition. Knowing this, he can try predicting the results — or manipulating them. For some reason (which absolutely cannot involve bribing), Polycarp wants the "Robo-Coder Inc." robot to outperform the "BionicSolver Industries" robot in the competition. Polycarp wants to set the values of pipi in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot. However, if the values of pipi will be large, it may look very suspicious — so Polycarp wants to minimize the maximum value of pipi over all problems. Can you help Polycarp to determine the minimum possible upper bound on the number of points given for solving the problems?InputThe first line contains one integer nn (1≤n≤1001≤n≤100) — the number of problems.The second line contains nn integers r1r1, r2r2, ..., rnrn (0≤ri≤10≤ri≤1). ri=1ri=1 means that the "Robo-Coder Inc." robot will solve the ii-th problem, ri=0ri=0 means that it won't solve the ii-th problem.The third line contains nn integers b1b1, b2b2, ..., bnbn (0≤bi≤10≤bi≤1). bi=1bi=1 means that the "BionicSolver Industries" robot will solve the ii-th problem, bi=0bi=0 means that it won't solve the ii-th problem.OutputIf "Robo-Coder Inc." robot cannot outperform the "BionicSolver Industries" robot by any means, print one integer −1−1.Otherwise, print the minimum possible value of maxi=1npimaxi=1npi, if all values of pipi are set in such a way that the "Robo-Coder Inc." robot gets strictly more points than the "BionicSolver Industries" robot.ExamplesInputCopy5 1 1 1 0 0 0 1 1 1 1 OutputCopy3 InputCopy3 0 0 0 0 0 0 OutputCopy-1 InputCopy4 1 1 1 1 1 1 1 1 OutputCopy-1 InputCopy9 1 0 0 0 0 0 0 0 1 0 1 1 0 1 1 1 1 0 OutputCopy4 NoteIn the first example; one of the valid score assignments is p=[3,1,3,1,1]p=[3,1,3,1,1]. Then the "Robo-Coder" gets 77 points, the "BionicSolver" — 66 points.In the second example, both robots get 00 points, and the score distribution does not matter.In the third example, both robots solve all problems, so their points are equal.
[ "greedy" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class test { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int n = Integer.parseInt(br.readLine()); StringTokenizer tokenizer = new StringTokenizer(br.readLine()); int[] r = new int[n]; for (int i = 0; i < n; i++) { r[i] = Integer.parseInt(tokenizer.nextToken()); } tokenizer = new StringTokenizer(br.readLine()); int[] b = new int[n]; for (int i = 0; i < n; i++) { b[i] = Integer.parseInt(tokenizer.nextToken()); } pw.println(solve(r, b, n)); pw.flush(); pw.close(); br.close(); } public static int solve(int[] r, int[] b, int n) { int rw = 0; int bw = 0; for (int i = 0; i < n; i++) { if (r[i] == 1 && b[i] == 0) rw++; else if (r[i] == 0 && b[i] == 1) bw++; } if (rw == 0) return -1; if (rw > bw) return 1; return (int) Math.ceil((double) (bw + 1) / (double) rw); } }
java