contest_id
stringclasses
33 values
problem_id
stringclasses
14 values
statement
stringclasses
181 values
tags
listlengths
1
8
code
stringlengths
21
64.5k
language
stringclasses
3 values
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 lewin */ 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); CWaterBalance solver = new CWaterBalance(); solver.solve(1, in, out); out.close(); } static class CWaterBalance { long ccw(CWaterBalance.Point a, CWaterBalance.Point b, CWaterBalance.Point c) { long dx1 = b.x - a.x; long dy1 = b.y - a.y; long dx2 = c.x - a.x; long dy2 = c.y - a.y; return dx1 * dy2 - dy1 * dx2; } public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); int[] arr = in.readIntArray(n); long[] h = new long[n + 1]; for (int i = 1; i <= n; i++) { h[i] = h[i - 1] + arr[i - 1]; } CWaterBalance.Point[] v = new CWaterBalance.Point[n + 1]; int sidx = 0; for (int i = 0; i <= n; i++) { CWaterBalance.Point add = new CWaterBalance.Point(i, h[i]); while (sidx >= 2 && ccw(v[sidx - 2], v[sidx - 1], add) <= 0) sidx--; v[sidx++] = add; } for (int i = 1; i < sidx; i++) { double pr = 1.0 * (v[i].y - v[i - 1].y) / (v[i].x - v[i - 1].x); for (int j = (int) v[i - 1].x; j < v[i].x; j++) { out.printf("%.10f\n", pr); } } } static class Point { public long x; public long y; public Point(long x, long y) { this.x = x; this.y = y; } public String toString() { return "Point{" + "x=" + x + ", y=" + y + '}'; } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1 << 16]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int[] readIntArray(int tokens) { int[] ret = new int[tokens]; for (int i = 0; i < tokens; i++) { ret[i] = nextInt(); } return ret; } public int read() { if (this.numChars == -1) { throw new InputMismatchException(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException var2) { throw new InputMismatchException(); } if (this.numChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { ; } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { res *= 10; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public static boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == -1; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void printf(String format, Object... objects) { writer.printf(format, objects); } public void close() { writer.close(); } } }
java
1285
E
E. Delete a Segmenttime limit per test4 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn segments on a OxOx axis [l1,r1][l1,r1], [l2,r2][l2,r2], ..., [ln,rn][ln,rn]. Segment [l,r][l,r] covers all points from ll to rr inclusive, so all xx such that l≤x≤rl≤x≤r.Segments can be placed arbitrarily  — be inside each other, coincide and so on. Segments can degenerate into points, that is li=rili=ri is possible.Union of the set of segments is such a set of segments which covers exactly the same set of points as the original set. For example: if n=3n=3 and there are segments [3,6][3,6], [100,100][100,100], [5,8][5,8] then their union is 22 segments: [3,8][3,8] and [100,100][100,100]; if n=5n=5 and there are segments [1,2][1,2], [2,3][2,3], [4,5][4,5], [4,6][4,6], [6,6][6,6] then their union is 22 segments: [1,3][1,3] and [4,6][4,6]. Obviously, a union is a set of pairwise non-intersecting segments.You are asked to erase exactly one segment of the given nn so that the number of segments in the union of the rest n−1n−1 segments is maximum possible.For example, if n=4n=4 and there are segments [1,4][1,4], [2,3][2,3], [3,6][3,6], [5,7][5,7], then: erasing the first segment will lead to [2,3][2,3], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the second segment will lead to [1,4][1,4], [3,6][3,6], [5,7][5,7] remaining, which have 11 segment in their union; erasing the third segment will lead to [1,4][1,4], [2,3][2,3], [5,7][5,7] remaining, which have 22 segments in their union; erasing the fourth segment will lead to [1,4][1,4], [2,3][2,3], [3,6][3,6] remaining, which have 11 segment in their union. Thus, you are required to erase the third segment to get answer 22.Write a program that will find the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.Note that if there are multiple equal segments in the given set, then you can erase only one of them anyway. So the set after erasing will have exactly n−1n−1 segments.InputThe first line contains one integer tt (1≤t≤1041≤t≤104) — the number of test cases in the test. Then the descriptions of tt test cases follow.The first of each test case contains a single integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of segments in the given set. Then nn lines follow, each contains a description of a segment — a pair of integers lili, riri (−109≤li≤ri≤109−109≤li≤ri≤109), where lili and riri are the coordinates of the left and right borders of the ii-th segment, respectively.The segments are given in an arbitrary order.It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105.OutputPrint tt integers — the answers to the tt given test cases in the order of input. The answer is the maximum number of segments in the union of n−1n−1 segments if you erase any of the given nn segments.ExampleInputCopy3 4 1 4 2 3 3 6 5 7 3 5 5 5 5 5 5 6 3 3 1 1 5 5 1 5 2 2 4 4 OutputCopy2 1 5
[ "brute force", "constructive algorithms", "data structures", "dp", "graphs", "sortings", "trees", "two pointers" ]
//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 T = sc.nextInt(); while (T-- > 0) { int n = sc.nextInt(); int[][] events = new int[2 * n][]; int[] prefixAns1 = new int[n + 1]; int[] prefixAnsL = new int[n + 1]; for (int i = 0; i < n; i++) { int l = sc.nextInt(); int r = sc.nextInt(); events[i * 2] = new int[]{2 * l, i + 1}; events[i * 2 + 1] = new int[]{2 * r + 1, -i - 1}; } Arrays.sort(events, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { if (o1[0] == o2[0]) return Integer.compare(o1[1], o2[1]); return Integer.compare(o1[0], o2[0]); } }); int cnt = 0; int count0 = 0; int count1 = 0; int countL = 0; int eIdx = 0; while (eIdx < 2 * n) { int iv = events[eIdx][0]; int tIdx = eIdx; while (tIdx < 2 * n && events[tIdx][0] == iv && events[tIdx][1] < 0) { prefixAns1[-events[tIdx][1]] += count1; prefixAnsL[-events[tIdx][1]] += countL; tIdx++; } if (tIdx == eIdx + 1 && cnt == 1){ tIdx = eIdx; while (tIdx < 2 * n && events[tIdx][0] == iv && events[tIdx][1] < 0) { prefixAns1[-events[tIdx][1]] -= 1; tIdx++; } } cnt -= tIdx - eIdx; if (eIdx != tIdx) { if (cnt == 0) count0++; if (cnt == 1) count1++; } eIdx = tIdx; while (tIdx < 2 * n && events[tIdx][0] == iv && events[tIdx][1] > 0) { prefixAns1[events[tIdx][1]] -= count1; prefixAnsL[events[tIdx][1]] -= countL; tIdx++; } cnt += tIdx - eIdx; if (eIdx != tIdx) { if (cnt > 1) countL++; } eIdx = tIdx; } int best = 0; for (int i = 1; i <= n; i++) { if (prefixAnsL[i] == 0) { best = Math.max(best, count0 - 1); } else { best = Math.max(best, count0 + prefixAns1[i]); } } pw.println(best); } } } 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")); // int n = 200000; // pw.println("1 " + n); // Random rnd = new Random(); // for (int i = 0; i < n; i++) { // int a = rnd.nextInt(2000000000) - 1000000000; // int b = rnd.nextInt(1000000000); // pw.println(a + " " + (a + b)); // } 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
1305
C
C. Kuroni and Impossible Calculationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTo become the king of Codeforces; Kuroni has to solve the following problem.He is given nn numbers a1,a2,…,ana1,a2,…,an. Help Kuroni to calculate ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj|. As result can be very big, output it modulo mm.If you are not familiar with short notation, ∏1≤i<j≤n|ai−aj|∏1≤i<j≤n|ai−aj| is equal to |a1−a2|⋅|a1−a3|⋅|a1−a2|⋅|a1−a3|⋅ …… ⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅⋅|a1−an|⋅|a2−a3|⋅|a2−a4|⋅ …… ⋅|a2−an|⋅⋅|a2−an|⋅ …… ⋅|an−1−an|⋅|an−1−an|. In other words, this is the product of |ai−aj||ai−aj| for all 1≤i<j≤n1≤i<j≤n.InputThe first line contains two integers nn, mm (2≤n≤2⋅1052≤n≤2⋅105, 1≤m≤10001≤m≤1000) — number of numbers and modulo.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109).OutputOutput the single number — ∏1≤i<j≤n|ai−aj|modm∏1≤i<j≤n|ai−aj|modm.ExamplesInputCopy2 10 8 5 OutputCopy3InputCopy3 12 1 4 5 OutputCopy0InputCopy3 7 1 4 9 OutputCopy1NoteIn the first sample; |8−5|=3≡3mod10|8−5|=3≡3mod10.In the second sample, |1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12|1−4|⋅|1−5|⋅|4−5|=3⋅4⋅1=12≡0mod12.In the third sample, |1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7|1−4|⋅|1−9|⋅|4−9|=3⋅8⋅5=120≡1mod7.
[ "brute force", "combinatorics", "math", "number theory" ]
import java.io.*; import java.util.*; public class Codeforces{ static long mod = 1000000007L; // map.put(a[i],map.getOrDefault(a[i],0)+1); // map.putIfAbsent; static MyScanner sc = new MyScanner(); //<----------------------------------------------WRITE HERE-------------------------------------------> static void solve(){ int n = sc.nextInt(); int m = sc.nextInt(); int[] a = sc.readIntArray(n); if(n>m) { out.print(0); return; } long ans = 1; for(int i=0;i<n-1;i++) { for(int j=i+1;j<n;j++) { ans = (ans * (long)(Math.abs(a[i]-a[j])))%m; } } out.println(ans); } static int eea(int a, int b, int[] v) { if(b == 0) { v[0] = 1; v[1] = 0; return a; } int g = eea(b,a%b,v); int x = v[0]; int y = v[1]; v[0] = y; v[1] = x - y*(a/b); // out.println(a+" "+v[0]+" "+b+" "+v[1]); return g; } //<----------------------------------------------WRITE HERE-------------------------------------------> static void swap(int[] a,int i,int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } static void priArr(int[] a) { for(int i=0;i<a.length;i++) { out.print(a[i] + " "); } out.println(); } static long gcd(long a,long b){ if(b==0) return a; return gcd(b,a%b); } static int gcd(int a,int b){ if(b==0) return a; return gcd(b,a%b); } static class Pair implements Comparable<Pair>{ Integer val; Integer ind; Pair(int v,int f){ val = v; ind = f; } public int compareTo(Pair p){ int s1 = this.ind-this.val; int s2 = p.ind-p.val; if(s1 != s2) return s1-s2; return this.val - p.val; } } public static void main(String[] args) { out = new PrintWriter(new BufferedOutputStream(System.out)); // int t = sc.nextInt(); int t= 1; while(t-- >0){ solve(); } // Stop writing your solution here. ------------------------------------- out.close(); } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------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(); } public int[] readIntArray(int n){ int arr[] = new int[n]; for(int i = 0;i<n;i++){ arr[i] = Integer.parseInt(next()); } return arr; } int[] reverse(int arr[]){ int n= arr.length; int i = 0; int j = n-1; while(i<j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; j--;i++; } return arr; } long[] readLongArray(int n){ long arr[] = new long[n]; for(int i = 0;i<n;i++){ arr[i] = Long.parseLong(next()); } return arr; } 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; } } private static void sort(int[] arr) { List<Integer> list = new ArrayList<>(); for (int i=0; i<arr.length; i++){ list.add(arr[i]); } Collections.sort(list); // collections.sort uses nlogn in backend for (int i = 0; i < arr.length; i++){ arr[i] = list.get(i); } } }
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 JavaApplication38 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T, a, b, c; T = in.nextInt(); for (int t = 0; t < T; t++) { a = in.nextInt(); b = in.nextInt(); c = in.nextInt(); int x[] = {a, b, c}; Arrays.sort(x); int ans = 0; for (int i = 0; i < 3; i++) { if (x[i] > 0) { ans++; x[i]--; } } if (x[0] > 0 && x[2] > 0) { ans++; x[0]--; x[2]--; } if (x[1] > 0 && x[2] > 0) { ans++; x[1]--; x[2]--; } if (x[0] > 0 && x[1] > 0) { ans++; x[0]--; x[1]--; } if (x[0] > 0 && x[1] > 0 && x[2] > 0) { ans++; } System.out.println(ans); } } }
java
1316
C
C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109),  — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109)  — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2)  — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2 1 1 2 2 1 OutputCopy1 InputCopy2 2 999999937 2 1 3 1 OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime.
[ "constructive algorithms", "math", "ternary search" ]
//package cf; import java.io.*; import java.util.*; public class Temp_Class { static int p=1000000007; public static void main(String[] args) throws Exception{ BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(java.io.FileDescriptor.out), "ASCII"), 512); FastReader sc=new FastReader(); int t=1; StringBuilder sb=new StringBuilder(); while(t-- >0) { int n=sc.nextInt(); int m=sc.nextInt(); int p=sc.nextInt(); int ar[]=new int[n]; int br[]=new int[m]; String inp1[]=sc.nextLine().split(" "); String inp2[]=sc.nextLine().split(" "); for(int i=0;i<n;i++) { ar[i]=Integer.parseInt(inp1[i]); } for(int i=0;i<m;i++) { br[i]=Integer.parseInt(inp2[i]); } int ans=0; for(int i=0;i<n;i++) { if(ar[i]%p!=0) { ans+=i; break; } } for(int i=0;i<m;i++) { if(br[i]%p!=0) { ans+=i; break; } } System.out.println(ans); } //bwbwwbwbw*bwbwwbwbw // System.out.println(sb.toString()); out.flush(); } public static int binary_Search_upper(int ar[],int x) { int res=-1; int l=0;int r=ar.length-1; while(l<=r) { int mid=(l+r)>>1; if(ar[mid]==x) { res=mid; l=mid+1; } else if(ar[mid]>x) { r=mid-1; } else { l=mid+1; } } return res; } public static int binary_Search_lower(int ar[],int x) { int res=-1; int l=0;int r=ar.length-1; while(l<=r) { int mid=(l+r)>>1; if(ar[mid]==x) { res=mid; r=mid-1; } else if(ar[mid]>x) { r=mid-1; } else { l=mid+1; } } return res; } int bit[]=new int[(int)1e6]; public void update(int n,int val,int i) { i++; while(i<n) { bit[i]+=val; i+=(i)&(-i); } } public long query(int n,int i) { i++; long sum=0; while(i>0) { sum+=bit[i]; i-=(i)&(-i); } return sum; } /////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// 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
1290
A
A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains three space-separated integers nn, mm and kk (1≤m≤n≤35001≤m≤n≤3500, 0≤k≤n−10≤k≤n−1)  — the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4 6 4 2 2 9 2 3 8 5 4 4 1 2 13 60 4 4 1 3 1 2 2 1 2 2 0 1 2 OutputCopy8 4 1 1 NoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element. the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8]; the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8]; if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element); if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44.
[ "brute force", "data structures", "implementation" ]
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import java.util.*; import java.io.*; import java.math.*; public class A_Mind_Control { 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 = f.nextInt(); while(t-- > 0){ solve(); } out.close(); } public static void solve() { int n = f.nextInt(); int m = f.nextInt(); int k = f.nextInt(); int arr[] = f.nextArray(n); int ans = Integer.MIN_VALUE; k = min(k, m-1); for(int i = 0; i <= k; i++) { int curr = Integer.MAX_VALUE; for(int j = i; j+(n-m) < n-(k-i); j++) { curr = min(curr, max(arr[j], arr[j+(n-m)])); } ans = max(ans, curr); } out.println(ans); } // Sort an array public static void sort(int arr[]) { ArrayList<Integer> al = new ArrayList<>(); for(int i: arr) { al.add(i); } Collections.sort(al); for(int i = 0; i < arr.length; i++) { arr[i] = al.get(i); } } // Find all divisors of n public static void allDivisors(int n) { for(int i = 1; i*i <= n; i++) { if(n%i == 0) { System.out.println(i + " "); if(i != n/i) { System.out.println(n/i + " "); } } } } // Check if n is prime or not public static boolean isPrime(int n) { if(n < 1) return false; if(n == 2 || n == 3) return true; if(n % 2 == 0 || n % 3 == 0) return false; for(int i = 5; i*i <= n; i += 6) { if(n % i == 0 || n % (i+2) == 0) { return false; } } return true; } // Find gcd of a and b public static long gcd(long a, long b) { long dividend = a > b ? a : b; long divisor = a < b ? a : b; while(divisor > 0) { long reminder = dividend % divisor; dividend = divisor; divisor = reminder; } return dividend; } // Find lcm of a and b public static long lcm(long a, long b) { long lcm = gcd(a, b); long hcf = (a * b) / lcm; return hcf; } // Find factorial in O(n) time public static long fact(int n) { long res = 1; for(int i = 2; i <= n; i++) { res = res * i; } return res; } // Find power in O(logb) time public static long power(long a, long b) { long res = 1; while(b > 0) { if((b&1) == 1) { res = (res * a)%mod; } a = (a * a)%mod; b >>= 1; } return res; } // Find nCr public static long nCr(int n, int r) { if(r < 0 || r > n) { return 0; } long ans = fact(n) / (fact(r) * fact(n-r)); return ans; } // Find nPr public static long nPr(int n, int r) { if(r < 0 || r > n) { return 0; } long ans = fact(n) / fact(r); return ans; } // sort all characters of a string public static String sortString(String inputString) { char tempArray[] = inputString.toCharArray(); Arrays.sort(tempArray); return new String(tempArray); } // User defined class for fast I/O static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } boolean hasNext() { if (st != null && st.hasMoreTokens()) { return true; } String tmp; try { br.mark(1000); tmp = br.readLine(); if (tmp == null) { return false; } br.reset(); } catch (IOException e) { return false; } return true; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } boolean nextBoolean() { return Boolean.parseBoolean(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextArray(int n) { int[] a = new int[n]; for(int i=0; i<n; i++) { a[i] = nextInt(); } return a; } } } /** Dec Char Dec Char Dec Char Dec Char --------- --------- --------- ---------- 0 NUL (null) 32 SPACE 64 @ 96 ` 1 SOH (start of heading) 33 ! 65 A 97 a 2 STX (start of text) 34 " 66 B 98 b 3 ETX (end of text) 35 # 67 C 99 c 4 EOT (end of transmission) 36 $ 68 D 100 d 5 ENQ (enquiry) 37 % 69 E 101 e 6 ACK (acknowledge) 38 & 70 F 102 f 7 BEL (bell) 39 ' 71 G 103 g 8 BS (backspace) 40 ( 72 H 104 h 9 TAB (horizontal tab) 41 ) 73 I 105 i 10 LF (NL line feed, new line) 42 * 74 J 106 j 11 VT (vertical tab) 43 + 75 K 107 k 12 FF (NP form feed, new page) 44 , 76 L 108 l 13 CR (carriage return) 45 - 77 M 109 m 14 SO (shift out) 46 . 78 N 110 n 15 SI (shift in) 47 / 79 O 111 o 16 DLE (data link escape) 48 0 80 P 112 p 17 DC1 (device control 1) 49 1 81 Q 113 q 18 DC2 (device control 2) 50 2 82 R 114 r 19 DC3 (device control 3) 51 3 83 S 115 s 20 DC4 (device control 4) 52 4 84 T 116 t 21 NAK (negative acknowledge) 53 5 85 U 117 u 22 SYN (synchronous idle) 54 6 86 V 118 v 23 ETB (end of trans. block) 55 7 87 W 119 w 24 CAN (cancel) 56 8 88 X 120 x 25 EM (end of medium) 57 9 89 Y 121 y 26 SUB (substitute) 58 : 90 Z 122 z 27 ESC (escape) 59 ; 91 [ 123 { 28 FS (file separator) 60 < 92 \ 124 | 29 GS (group separator) 61 = 93 ] 125 } 30 RS (record separator) 62 > 94 ^ 126 ~ 31 US (unit separator) 63 ? 95 _ 127 DEL */ // (a/b)%mod == (a * moduloInverse(b)) % mod; // moduloInverse(b) = power(b, mod-2);
java
1296
A
A. Array with Odd Sumtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.In one move, you can choose two indices 1≤i,j≤n1≤i,j≤n such that i≠ji≠j and set ai:=ajai:=aj. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. you choose ii and jj and replace aiai with ajaj).Your task is to say if it is possible to obtain an array with an odd (not divisible by 22) sum of elements.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤20001≤t≤2000) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤20001≤n≤2000) — the number of elements in aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤20001≤ai≤2000), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 20002000 (∑n≤2000∑n≤2000).OutputFor each test case, print the answer on it — "YES" (without quotes) if it is possible to obtain the array with an odd sum of elements, and "NO" otherwise.ExampleInputCopy5 2 2 3 4 2 2 8 8 3 3 3 3 4 5 5 5 5 4 1 1 1 1 OutputCopyYES NO YES NO NO
[ "math" ]
import java.util.*; import java.io.*; public class Practice { static FastReader sc; static PrintWriter out; static int gcd(int a,int b){ if(b==0) return a; return gcd(b,a%b); } static void solve() { int n = sc.nextInt();//, x = sc.nextInt(); int[] arr = sc.readIntArray(n); boolean odd = false, even = false; for(int a : arr) if((a&1) == 1) odd = true; else even = true; if((n&1) == 1){ if(odd){ out.println("YES"); }else out.println("NO"); }else{ if(odd && even) out.println("YES"); else out.println("NO"); } } public static void main(String[] args) throws IOException { sc = new FastReader(); out = new PrintWriter(System.out); int tt = sc.nextInt(); for (int t = 1; t <= tt; t++) { // out.printf("Case %d: ", t); solve(); } //solve(); out.close(); } static int[] strToIntArray(String s){ String[] sarr = s.split(" "); int[] arr = new int[sarr.length]; for(int i = 0; i < sarr.length; i++){ arr[i] = Integer.parseInt(sarr[i]); } return arr; } static <E> void debug(E a) { System.err.println(a); } static void debug(int... a) { System.err.println(Arrays.toString(a)); } static <E> void print(E res) { out.println(res); } 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; } int[] readIntArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) res[i] = nextInt(); return res; } long[] readLongArray(int n) { long[] res = new long[n]; for (int i = 0; i < n; i++) res[i] = nextLong(); return res; } } }
java
1325
C
C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusive. All the written labels are distinct. The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3 1 2 1 3 OutputCopy0 1 InputCopy6 1 2 1 3 2 4 2 5 5 6 OutputCopy0 3 2 4 1NoteThe tree from the second sample:
[ "constructive algorithms", "dfs and similar", "greedy", "trees" ]
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); AEhabAndPathEticMEXs solver = new AEhabAndPathEticMEXs(); solver.solve(1, in, out); out.close(); } static class AEhabAndPathEticMEXs { int[][][] g; int n; int m; int[] from; int[] to; int[] wt; int[] deg; public void solve(int testNumber, InputReader in, OutputWriter out) { g = makeGraph(in); int val = 0; int[] ans = new int[n - 1]; Arrays.fill(ans, -1); for (int i = 0; i < n; i++) { if (deg[i] >= 3) { for (int[] a : g[i]) { ans[a[1]] = val++; } break; } } for (int i = 0; i < n; i++) { for (int[] a : g[i]) { if (ans[a[1]] == -1) { ans[a[1]] = val++; } } } for (int a : ans) out.println(a); } int[][][] makeGraph(InputReader in) { n = in.nextInt(); m = n - 1; from = new int[m]; to = new int[m]; wt = new int[m]; deg = new int[n]; for (int i = 0; i < m; i++) { int a = in.nextInt() - 1, b = in.nextInt() - 1; from[i] = a; to[i] = b; wt[i] = i; deg[a]++; deg[b]++; } return makeGraph(n, m); } int[][][] makeGraph(int N, int M) { int[][][] G = new int[N][][]; int[] p = new int[N]; for (int i = 0; i < M; i++) { p[from[i]]++; p[to[i]]++; } for (int i = 0; i < N; i++) G[i] = new int[p[i]][2]; for (int i = 0; i < M; i++) { --p[from[i]]; G[from[i]][p[from[i]]][0] = to[i]; G[from[i]][p[from[i]]][1] = wt[i]; --p[to[i]]; G[to[i]][p[to[i]]][0] = from[i]; G[to[i]][p[to[i]]][1] = wt[i]; } return G; } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void close() { writer.close(); } public void println(int i) { writer.println(i); } } 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
1284
B
B. New Year and Ascent Sequencetime limit per test2 secondsmemory limit per test1024 megabytesinputstandard inputoutputstandard outputA sequence a=[a1,a2,…,al]a=[a1,a2,…,al] of length ll has an ascent if there exists a pair of indices (i,j)(i,j) such that 1≤i<j≤l1≤i<j≤l and ai<ajai<aj. For example, the sequence [0,2,0,2,0][0,2,0,2,0] has an ascent because of the pair (1,4)(1,4), but the sequence [4,3,3,3,1][4,3,3,3,1] doesn't have an ascent.Let's call a concatenation of sequences pp and qq the sequence that is obtained by writing down sequences pp and qq one right after another without changing the order. For example, the concatenation of the [0,2,0,2,0][0,2,0,2,0] and [4,3,3,3,1][4,3,3,3,1] is the sequence [0,2,0,2,0,4,3,3,3,1][0,2,0,2,0,4,3,3,3,1]. The concatenation of sequences pp and qq is denoted as p+qp+q.Gyeonggeun thinks that sequences with ascents bring luck. Therefore, he wants to make many such sequences for the new year. Gyeonggeun has nn sequences s1,s2,…,sns1,s2,…,sn which may have different lengths. Gyeonggeun will consider all n2n2 pairs of sequences sxsx and sysy (1≤x,y≤n1≤x,y≤n), and will check if its concatenation sx+sysx+sy has an ascent. Note that he may select the same sequence twice, and the order of selection matters.Please count the number of pairs (x,yx,y) of sequences s1,s2,…,sns1,s2,…,sn whose concatenation sx+sysx+sy contains an ascent.InputThe first line contains the number nn (1≤n≤1000001≤n≤100000) denoting the number of sequences.The next nn lines contain the number lili (1≤li1≤li) denoting the length of sisi, followed by lili integers si,1,si,2,…,si,lisi,1,si,2,…,si,li (0≤si,j≤1060≤si,j≤106) denoting the sequence sisi. It is guaranteed that the sum of all lili does not exceed 100000100000.OutputPrint a single integer, the number of pairs of sequences whose concatenation has an ascent.ExamplesInputCopy5 1 1 1 1 1 2 1 4 1 3 OutputCopy9 InputCopy3 4 2 0 2 0 6 9 9 8 8 7 7 1 6 OutputCopy7 InputCopy10 3 62 24 39 1 17 1 99 1 60 1 64 1 30 2 79 29 2 20 73 2 85 37 1 100 OutputCopy72 NoteFor the first example; the following 99 arrays have an ascent: [1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4][1,2],[1,2],[1,3],[1,3],[1,4],[1,4],[2,3],[2,4],[3,4]. Arrays with the same contents are counted as their occurences.
[ "binary search", "combinatorics", "data structures", "dp", "implementation", "sortings" ]
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.*; import java.io.*; public class Main { // Graph // prefix sums //inputs public static void main(String args[])throws Exception{ Input sc=new Input(); precalculates p=new precalculates(); StringBuilder sb=new StringBuilder(); long n=sc.readInt(); ArrayList<Integer> lst1=new ArrayList<>(); ArrayList<Integer> lst2=new ArrayList<>(); for(int i=0;i<n;i++){ int a[]=sc.readArray(); boolean b=false; int min=Integer.MAX_VALUE; int max=Integer.MIN_VALUE; for(int j=1;j<a[0];j++){ min=Math.min(a[j],min); max=Math.max(a[j],max); if(a[j]<a[j+1]){ b=true; break; } } if(!b){ lst1.add(Math.min(min,a[a[0]])); lst2.add(Math.max(max,a[a[0]])); } } long ans=n*(long)n; long c=0; Collections.sort(lst2); //System.out.println(lst1); //System.out.println(lst2); HashMap<Integer,Integer> map=new HashMap<>(); for(int i=0;i<lst2.size();i++){ map.put(lst2.get(i),i); } for(int i=0;i<lst1.size();i++){ int k=Collections.binarySearch(lst2, lst1.get(i)); if(k<0){ k=Math.abs(k); // if(k==1) // k=0; // k++; k--; // System.out.println(k+" "+ lst1.get(i)); }else{ k=map.get(lst1.get(i))+1; } c+=k; } ans=ans-c; sb.append(ans+"\n"); System.out.print(sb); } } class Input{ BufferedReader br; StringTokenizer st; Input(){ br=new BufferedReader(new InputStreamReader(System.in)); st=new StringTokenizer(""); } public int[] readArray() throws Exception{ st=new StringTokenizer(br.readLine()); int a[]=new int[st.countTokens()]; for(int i=0;i<a.length;i++){ a[i]=Integer.parseInt(st.nextToken()); } return a; } public long[] readArrayLong() throws Exception{ st=new StringTokenizer(br.readLine()); long a[]=new long[st.countTokens()]; for(int i=0;i<a.length;i++){ a[i]=Long.parseLong(st.nextToken()); } return a; } public int readInt() throws Exception{ st=new StringTokenizer(br.readLine()); return Integer.parseInt(st.nextToken()); } public long readLong() throws Exception{ st=new StringTokenizer(br.readLine()); return Long.parseLong(st.nextToken()); } public String readString() throws Exception{ return br.readLine(); } public int[][] read2dArray(int n,int m)throws Exception{ int a[][]=new int[n][m]; for(int i=0;i<n;i++){ st=new StringTokenizer(br.readLine()); for(int j=0;j<m;j++){ a[i][j]=Integer.parseInt(st.nextToken()); } } return a; } } class precalculates{ public int[] prefixSumOneDimentional(int a[]){ int n=a.length; int dp[]=new int[n]; for(int i=0;i<n;i++){ if(i==0) dp[i]=a[i]; else dp[i]=dp[i-1]+a[i]; } return dp; } public int[] postSumOneDimentional(int a[]) { int n = a.length; int dp[] = new int[n]; for (int i = n - 1; i >= 0; i--) { if (i == n - 1) dp[i] = a[i]; else dp[i] = dp[i + 1] + a[i]; } return dp; } public int[][] prefixSum2d(int a[][]){ int n=a.length;int m=a[0].length; int dp[][]=new int[n+1][m+1]; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ dp[i][j]=a[i-1][j-1]+dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1]; } } return dp; } public long pow(long a,long b){ long mod=1000000007; long ans=0; if(b<=0) return 1; if(b%2==0){ ans=pow(a,b/2)%mod; return ((ans%mod)*(ans%mod))%mod; }else{ return ((a%mod)*(ans%mod))%mod; } } } class GraphInteger{ HashMap<Integer,vertex> vtces; class vertex{ HashMap<Integer,Integer> children; public vertex(){ children=new HashMap<>(); } } public GraphInteger(){ vtces=new HashMap<>(); } public void addVertex(int a){ vtces.put(a,new vertex()); } public void addEdge(int a,int b,int cost){ if(!vtces.containsKey(a)){ vtces.put(a,new vertex()); } if(!vtces.containsKey(b)){ vtces.put(b,new vertex()); } vtces.get(a).children.put(b,cost); // vtces.get(b).children.put(a,cost); } public boolean isCyclicDirected(){ boolean isdone[]=new boolean[vtces.size()+1]; boolean check[]=new boolean[vtces.size()+1]; for(int i=1;i<=vtces.size();i++) { if (!isdone[i] && isCyclicDirected(i,isdone, check)) { return true; } } return false; } private boolean isCyclicDirected(int i,boolean isdone[],boolean check[]){ if(check[i]) return true; if(isdone[i]) return false; check[i]=true; isdone[i]=true; Set<Integer> set=vtces.get(i).children.keySet(); for(Integer ii:set){ if(isCyclicDirected(ii,isdone,check)) return true; } check[i]=false; return false; } }
java
1325
C
C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusive. All the written labels are distinct. The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3 1 2 1 3 OutputCopy0 1 InputCopy6 1 2 1 3 2 4 2 5 5 6 OutputCopy0 3 2 4 1NoteThe tree from the second sample:
[ "constructive algorithms", "dfs and similar", "greedy", "trees" ]
//package com.company;//Read minute details if coming wrong for no idea questions import com.sun.source.tree.ArrayAccessTree; import javax.swing.*; import java.beans.IntrospectionException; import java.math.BigInteger; import java.util.*; import java.io.*; public class Main { static class pair implements Comparable<pair> { long a = 0; long b = 0; // int cnt; pair(long b, long a) { this.a = b; this.b = a; // cnt = x; } @Override public int compareTo(pair o) { if(this.a != o.a) return (int) (this.a - o.a); else return (int) (this.b - o.b); } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair) o; return p.a == a && p.b == b; } return false; } public int hashCode() { return (Long.valueOf(a).hashCode()) * 31 + (Long.valueOf(b).hashCode()); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine().trim(); } catch (Exception e) { e.printStackTrace(); } return str; } } static class FastWriter { private final BufferedWriter bw; public FastWriter() { this.bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void prlong(Object object) throws IOException { bw.append("" + object); } public void prlongln(Object object) throws IOException { prlong(object); bw.append("\n"); } public void close() throws IOException { bw.close(); } } public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } //HASHsET COLLISION AVOIDING CODE FOR STORING STRINGS // HashSet<Long> set = new HashSet<>(); // for(int i = 0; i < s.length(); i++){ // int b = 0; // long h = 1; // for(int j=i; j<s.length(); j++){ // h = 131*h + (int)s.charAt(j); // b += bad[(int)(s.charAt(j)-'a')]; // if(b<=k){ // set.add(h); // } // } // } // System.out.println(set.size()); //dsu static int[] par, rank; public static void dsu(int n) { par = new int[n]; rank = new int[n]; for (int i = 0; i < n; i++) { par[i] = i; rank[i] = 1; } } static int find(int u) { return par[u] == -1 ? -1 : par[u] == u ? u : (par[u] = find(par[u])); } static void union(int u, int v) { int a = find(u), b = find(v); if (a != b && a != -1 && b != -1) { par[b] = a; rank[a] += rank[b]; } } static void disunion(int u, int v) { int a = find(u), b = find(v); if (a != -1 && a == b) { par[a] = -1; } } static class Calc_nCr { private final long[] fact; private final long[] invfact; private final int p; Calc_nCr(int n, int prime) { fact = new long[n + 5]; invfact = new long[n + 5]; p = prime; fact[0] = 1; for (int i = 1; i <= n; i++) { fact[i] = (i * fact[i - 1]) % p; } invfact[n] = pow(fact[n], p - 2, p); for (int i = n - 1; i >= 0; i--) { invfact[i] = (invfact[i + 1] * (i + 1)) % p; } } private long nCr(int n, int r) { if (r > n || n < 0 || r < 0) return 0; return (((fact[n] * invfact[r]) % p) * invfact[n - r]) % p; } private static long pow(long a, long b, int mod) { long result = 1; while (b > 0) { if ((b & 1L) == 1) { result = (result * a) % mod; } a = (a * a) % mod; b >>= 1; } return result; } } static void sort(long[] a ) { ArrayList<Long> l = new ArrayList<>(); for(long i: a) { l.add(i); } Collections.sort(l); for(int i =0;i<a.length;++i) { a[i] = l.get(i); } } public static void main(String[] args) { try { FastReader in = new FastReader(); FastWriter out = new FastWriter(); // int mx=10000000; // boolean isPrime[] = new boolean[mx+5]; int primeDiv[] = new int[mx+5]; // for (int i = 0; i <= mx; i++) { // isPrime[i] = true; // } // for(int i =0;i<primeDiv.length;i++) // primeDiv[i]=i; // isPrime[0] = isPrime[1] = false; // for (long i = 2; i <= mx; i++) { // if (isPrime[(int)i]) { // for (long j = i*i; j <= mx; j += i) { // if (primeDiv[(int)j] == j) { // primeDiv[(int)j] = (int)i; // } // isPrime[(int)j] = false; // } // } // } // System.out.println( // String.format("%.12f", x)); int testCases=1; // int n =in.nextInt(); // long arr[]=new long[n]; // ArrayList<Long>ans=new ArrayList<>(); // for(int i =0;i<n;i++) // // // } ans.add(in.nextLong()); // Collections.sort(ans); // for(int i =0;i<n;i++) // arr[i]=ans.get(i); int mod =1000000007; fl: while (testCases-- > 0) { int n =in.nextInt(); ArrayList<ArrayList<Integer>>adj=new ArrayList<>(); int q[][]=new int[n][3]; for(int i =0;i<n;i++) adj.add(new ArrayList<>()); for(int i =0;i<n-1;i++) { int a =in.nextInt(); int b =in.nextInt(); a--;b--; int temp=a; a=Math.min(a,b); b=Math.max(temp,b); q[i][0]=a; q[i][1]=b; adj.get(a).add(b); adj.get(b).add(a); } // System.out.println(adj); int x =0; int y =-1; int x2 =0; int y2 =-1; boolean yes=true; int count =0; int a[][]=new int[3][2]; HashMap<Integer,Integer>map=new HashMap<>(); for(int i =0;i<n;i++) { if(adj.get(i).size()>=3) { yes=false; a[0][0]=(i);a[0][1]=adj.get(i).get(0); a[1][0]=(i);a[1][1]=adj.get(i).get(1); a[2][0]=(i);a[2][1]=adj.get(i).get(2); break ; } } HashMap<pair,Integer>b=new HashMap<>(); for(int i =0;i<3;i++) { pair p =new pair(a[i][0],a[i][1]); b.put(p,0);} Stack<Integer>ans=new Stack<>() ; // System.out.println(x+" "+y+" "+x2+" "+y2); for(int i =3;i<n-1;i++) ans.push(i); if(yes) { ans.push(2); ans.push(1); ans.push(0); } int aa=0; for(int i =0;i<n-1;i++) { int aaa =q[i][0]; int bbb =q[i][1]; // System.out.println(aaa+" "+bbb); pair p =new pair(aaa,bbb); pair p1 =new pair(bbb,aaa); if(b.containsKey(p)) { System.out.println(aa); aa++; } else if(b.containsKey(p1)) { System.out.println(aa); aa++; } else System.out.println(ans.pop()); } } out.close(); } catch (Exception e) { return; } } public static double dfs(ArrayList<ArrayList<Integer>>adj, int curr, int par) { double len = 0; for(int child: adj.get(curr)) { if(child == par) continue; len += dfs(adj, child, curr)+1; } //System.out.println(curr+" "+len); if(len == 0) // leaf node return 0; if(par == -1) // root node return len/adj.get(curr).size(); return len/(adj.get(curr).size()-1); } static long comb(int r, int n) { long result; result = factorial(n)/(factorial(r)*factorial(n-r)); return result; } static long factorial(int n) { int c; long result = 1; for (c = 1; c <= n; c++) result = result*c; return result; } static void LongestPalindromicPrefix(String str,int lps[]){ // String temp = str + '/'; // str = reverse(str); // temp += str; String temp =str; int n = temp.length(); for(int i = 1; i < n; i++) { int len = lps[i - 1]; while (len > 0 && temp.charAt(len) != temp.charAt(i)) { len = lps[len - 1]; } if (temp.charAt(i) == temp.charAt(len)) { len++; } lps[i] = len; } // return temp.substring(0, lps[n - 1]); } static String reverse(String input) { char[] a = input.toCharArray(); int l, r = a.length - 1; for(l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.valueOf(a); } } /* * *  ┏┓   ┏┓+ + * ┏┛┻━━━┛┻┓ + + * ┃       ┃ * ┃   ━   ┃ ++ + + + * ████━████+ * ◥██◤ ◥██◤ + * ┃   ┻   ┃ * ┃       ┃ + + * ┗━┓   ┏━┛ *   ┃  ┃ JACKS PET FROM ANOTHER WORLD *   ┃  ┃ *   ┃    ┗━━━┓ *   ┃        ┣┓------- *   ┃        ┏┛------- *  ┗┓┓┏━┳┓┏┛ + + + + *    ┃┫┫ ┃┫┫ *    ┗┻┛ ┗┻┛+ + + + */ //RULES //TAKE INPUT AS LONG IN CASE OF SUM OR MULITPLICATION OR CHECK THE CONTSRaint of the array //Always use stringbuilder of out.println for strinof out.println for string or high level output // IMPORTANT TRs1 TO USE BRUTE FORCE TECHNIQUE TO SOLVE THE PROs1 OTHER CERTAIN LIMIT IS GIVENIT IS GIVEN //Read minute details if coming wrong for no idea questions
java
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" ]
// practice with kaiboy import java.io.*; import java.util.*; public class CF1313C2 extends PrintWriter { CF1313C2() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1313C2 o = new CF1313C2(); o.main(); o.flush(); } void main() { int n = sc.nextInt(); int[] aa = new int[n + 2]; for (int i = 1; i <= n; i++) aa[i] = sc.nextInt(); long[] dp = new long[n + 2]; long[] dq = new long[n + 2]; int[] pp = new int[n + 2]; pp[0] = -1; int[] qq = new int[n + 2]; qq[n + 1] = n + 2; int[] qu = new int[n + 2]; int cnt = 0; qu[cnt++] = 0; for (int p, i = 1; i <= n; i++) { while (aa[p = qu[cnt - 1]] >= aa[i]) cnt--; qu[cnt++] = i; pp[i] = p; dp[i] = dp[p] + (long) (i - p) * aa[i]; } cnt = 0; qu[cnt++] = n + 1; for (int q, i = n; i >= 1; i--) { while (aa[q = qu[cnt - 1]] >= aa[i]) cnt--; qu[cnt++] = i; qq[i] = q; dq[i] = dq[q] + (long) (q - i) * aa[i]; } int h = 0; for (int i = 1; i <= n; i++) if (h == 0 || dp[h] + dq[h] - aa[h] < dp[i] + dq[i] - aa[i]) h = i; for (int i = h; i >= 1; ) { int a = aa[i]; int p = pp[i]; while (i != p) { aa[i] = a; i--; } } for (int i = h; i <= n; ) { int a = aa[i]; int q = qq[i]; while (i != q) { aa[i] = a; i++; } } for (int i = 1; i <= n; i++) print(aa[i] + " "); println(); } }
java
1285
F
F. Classical?time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven an array aa, consisting of nn integers, find:max1≤i<j≤nLCM(ai,aj),max1≤i<j≤nLCM(ai,aj),where LCM(x,y)LCM(x,y) is the smallest positive integer that is divisible by both xx and yy. For example, LCM(6,8)=24LCM(6,8)=24, LCM(4,12)=12LCM(4,12)=12, LCM(2,3)=6LCM(2,3)=6.InputThe first line contains an integer nn (2≤n≤1052≤n≤105) — the number of elements in the array aa.The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1051≤ai≤105) — the elements of the array aa.OutputPrint one integer, the maximum value of the least common multiple of two elements in the array aa.ExamplesInputCopy3 13 35 77 OutputCopy1001InputCopy6 1 2 4 8 16 32 OutputCopy32
[ "binary search", "combinatorics", "number theory" ]
//package com.company; import java.io.*; import java.util.*; public class Main { public static class Task { List<Integer> primes; int[] pF; int[] mobius; int[] cnt; boolean[] on; List<Integer>[] factors; void update(int x, int y) { for (int d: factors[x]) cnt[d] += y; } int count(int x) { int r = 0; for (int d: factors[x]) r += mobius[d] * cnt[d]; return r; } public void precompute() { int n = 100001; primes = new ArrayList<>(); pF = new int[n]; mobius = new int[n]; mobius[1] = 1; for (int i = 2; i < n; ++i) { if (pF[i] == 0) { pF[i] = i; primes.add(i); mobius[i] = -1; } for (int j = 0; j < primes.size () && i * primes.get(j) < n; ++j) { int p = primes.get(j); pF[i * p] = p; if (i % p == 0) { mobius[i * p] = 0; break; } else { mobius[i * p] = mobius[i] * mobius[p]; } } } cnt = new int[n]; on = new boolean[n]; factors = new List[n]; for (int i = 0; i < n; i++) { factors[i] = new ArrayList<>(); } for (int i = 1; i < n; i++) { for (int j = i; j < n; j += i) factors[j].add(i); } } int gcd(int x, int y) { return y == 0 ? x: gcd(y, x % y); } long lcm(int x, int y) { int g = gcd(x, y); return (long) x * y / g; } public void solve(Scanner sc, PrintWriter pw) throws IOException { precompute(); int n = sc.nextInt(); for (int i = 0; i < n; i++) { on[sc.nextInt()] = true; } long m = 0; int[] stack = new int[n]; int sIdx = 0; for (int g = 1; g <= 100000; g++) { for (int i = 100000 / g; i > 0; i--) if (on[i * g]) { m = Math.max(m, i * g); int coprimes = count(i); while (coprimes > 0) { int x = stack[sIdx - 1]; int _g = gcd(i, x); m = Math.max(m, (long) g * i * x / _g); if (_g == 1) coprimes--; update(stack[sIdx - 1], -1); sIdx--; } update(i, 1); stack[sIdx++] = i; } while (sIdx > 0) { update(stack[sIdx - 1], -1); sIdx--; } } pw.println(m); } } 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
1324
D
D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5 4 8 2 6 2 4 5 4 1 3 OutputCopy7 InputCopy4 1 3 2 4 1 3 2 4 OutputCopy0
[ "binary search", "data structures", "sortings", "two pointers" ]
// Author : Shadman Shariar // // Email : [email protected] // import java.io.*; import java.util.*; import java.time.*; import java.lang.Math.*; import java.io.BufferedReader; import java.io.IOException; import java.math.BigInteger; import java.text.DecimalFormat; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.function.Supplier;import java.io.Closeable; import java.util.regex.Pattern;import java.util.regex.Matcher; import java.util.stream.*;import static java.lang.System.exit; import java.nio.charset.Charset; import java.security.KeyStore.Entry; public class Main { public static Main obj = new Main(); private static final Integer Null = null; public static final long N = (long)(1000000001); public static final long Bigmod = 1_000_000_007; public static final String Vowels = "aeiouAEIOU"; public static final Random random = new Random(); public static int [] dx = {-1, 1, 0, 0, -1, -1, 1, 1}; public static int [] dy = {0, 0, -1, 1, -1, 1, -1, 1}; public static int [] dp1 = new int [10]; public static int [][] dp2 = new int[10][10]; public static final long bigmod = (long)(Math.pow(10,9)+7); public static final String spliter1 = "\\s+", spliter2 = "[ ]+"; public static FastReader fr = new FastReader(); public static Scanner input = new Scanner(System.in); public static PrintWriter out = new PrintWriter(System.out); public static DecimalFormat df = new DecimalFormat(".00"); public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static void main (String[]args) throws Exception{Scanner input=new Scanner(System.in); //===========================================================================================// //Vector vc = new Vector(); //BigInteger bi = new BigInteger("1000"); //StringBuilder sb = new StringBuilder(); //StringBuffer sbf = new StringBuffer(); //StringTokenizer st = new StringTokenizer("string",spliter1); //ArrayList<Integer> al= new ArrayList<Integer>(); //LinkedList<Integer> ll= new LinkedList<Integer>(); //Stack <Integer> stk = new Stack <Integer>(); //Queue <Integer> q = new LinkedList<Integer>(); //ArrayDeque<Integer> ad = new ArrayDeque<Integer>(); //PriorityQueue <Integer> pq = new PriorityQueue<Integer>(); //PriorityQueue <Integer> pqr = new PriorityQueue<Integer>(Comparator.reverseOrder()); //HashSet<Integer> hs = new HashSet<Integer>(); //LinkedHashSet<Integer> lhs = new LinkedHashSet<Integer>(); //TreeSet<Integer> ts = new TreeSet<Integer>(); //TreeSet<Integer> tsr = new TreeSet<Integer>(Comparator.reverseOrder()); //Hashtable<Integer,Integer> ht = new Hashtable<Integer,Integer>(); //HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>(); //LinkedHashMap<Integer,Integer> lhm = new LinkedHashMap<Integer,Integer>(); //TreeMap<Integer,Integer> tm = new TreeMap<Integer,Integer>(); //TreeMap<Integer,Integer> tmr = new TreeMap<Integer,Integer>(Comparator.reverseOrder()); //ArrayList<ArrayList<Integer>> al2= new ArrayList<ArrayList<Integer>>(); //LinkedList<LinkedList<Integer>> ll2= new LinkedList<LinkedList<Integer>>(); //LinkedList<Integer> adj[] = new LinkedList[1000]; //ArrayList<Integer> adj2[] = new ArrayList[1000]; //HashSet<Integer> hsj[] = new HashSet[1000]; //HashMap<Integer,Integer> hmj[] = new HashMap[1000]; //ArrayList<int[]> aa = new ArrayList<int[]>(); //LinkedList<long[]> la = new LinkedList<long[]>(); //Arrays.sort(2d Array, Comparator.comparingInt(o -> o[0])); //SortedSet< Integer > ss = new TreeSet<>( (i, j) -> i > j ? 1 : -1 ); //SortedMap< Integer, Integer > sm = new TreeMap<>( (i, j) -> i > j ? 1 : -1 ); //===========================================================================================// //long start = System.currentTimeMillis(); // Bitmask ----------------------------------- // Check Bit - (number&(1<<pos)) -> 0/1 bit | // Set Bit - number = (number|(1<<pos)) | // Unset Bit - number = (number&(~(1<<pos))) | // inverse toggle - number = number^(1<<pos) | //-------------------------------------------- int tc = 1; //tc = input.nextInt(); for (int tt = 1; tt <= tc; tt++) { int n = fr.nextInt(); Integer [] arr = new Integer [n]; Integer [] brr = new Integer [n]; for (int i = 0; i < arr.length; i++) { arr[i] = fr.nextInt(); } for (int i = 0; i < brr.length; i++) { brr[i] = fr.nextInt(); } int [] dis = new int [n]; for (int i = 0; i < brr.length; i++) { dis[i] = arr[i]-brr[i]; } sort(dis); int l =0, r = n-1; long sum =0 ; while(l<r) { if(dis[l]+dis[r] > 0) { sum+= (r-l); r--; } else { l++; } } out.println(sum); } //long end = System.currentTimeMillis(); //System.out.println("Time : "+((end-start)/1000)); //===========================================================================================// out.flush(); out.close(); input.close(); System.exit(0); } //===========================================================================================// //-------->> Temporary Method Starts Here <<--------// //-------->> Temporary Method Ends Here <<--------// //===========================================================================================// public static void bdfs(char[][] grid, int i, int j) { if(i<0||j<0||i>=grid.length||j>=grid[i].length||grid[i][j]=='0')return; grid[i][j] = '0';bdfs(grid, i+1, j);bdfs(grid, i-1, j);bdfs(grid, i, j+1); bdfs(grid, i, j-1); return;} public static class pair { int first, second; public pair(int first, int second) { this.first = first; this.second = second;}} public static void debug(Object... obj){System.err.println(Arrays.deepToString(obj));} public static void swap(int a[], int i, int j) { a[i] ^= a[j];a[j] ^= a[i];a[i] ^= a[j];} public static void swap(long a[], int i, int j) { a[i] ^= a[j];a[j] ^= a[i];a[i] ^= a[j];} public 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);} public static long add(long a, long b) {return (a+b)%Bigmod;} public static long sub(long a, long b) {return ((a-b)%Bigmod+Bigmod)%Bigmod;} public static long mul(long a, long b) {return (a*b)%Bigmod;} public static long exp(long base,long exp){if(exp==0)return 1;long half=exp(base,exp/2); if (exp%2==0) return mul(half, half);return mul(half, mul(half, base));} public static long lcm(long a,long b){return (a/gcd(a,b))*b;} public static long gcd(long a,long b){if(a==0)return b;return gcd(b%a,a);} public static long nPr(long n,long r){return factorial(n)/factorial(n-r);} public static long nCr(long n,long r){return factorial(n)/(factorial(r)*factorial(n-r));} public static long factorial(long n){return (n==1||n==0)?1:n*factorial(n-1);} public static long countsubstr(String str){long n=str.length();return n*(n+1)/2;} public static long fastpower(long a,long b,long n) {long res=1;while(b>0){if((b&1)!=0) {res=(res*a%n)%n;}a=(a%n*a%n)%n;b=b>>1;}return res;} public static void subsequences(String s,String ans){if(s.length()==0){ss. add(ans);return;}subsequences(s.substring(1),ans+s.charAt(0));subsequences (s.substring(1),ans);}public static List<String>ss=new ArrayList<>(); public static boolean perfectsquare(long x){if(x>=0) {long sr=(long)(Math.sqrt(x));return((sr*sr)==x);}return false;} public static boolean perfectcube(long N){int cube;int c=0;for(int i=0;i<=N;i++){cube=i*i*i; if(cube==N){c=1;break;}else if (cube>N){c=0;break;}}if(c==1)return true;else return false;} public static boolean[] sieveOfEratosthenes(int n){boolean prime[]=new boolean[n+1]; for (int i = 0; i <= n; i++)prime[i] = true;for (int p = 2; p * p <= n; p++){ if(prime[p]==true){for(int i=p*p;i<=n;i+=p)prime[i]=false;}}prime[1]=false;return prime;} public static int binarysearch(int arr[],int l,int r,int x) {if (r >= l){int mid = l + (r - l) / 2;if (arr[mid]==x)return mid;if(arr[mid]>x)return binarysearch(arr, l, mid - 1, x);return binarysearch(arr, mid + 1, r, x);}return -1;} public static void rangeofprime(int a,int b){int i, j, flag;for (i = a; i <= b; i++) {if (i == 1 || i == 0)continue;flag = 1;for (j = 2; j <= i / 2; ++j) {if (i % j == 0) {flag = 0;break;}}if (flag == 1)System.out.println(i);}} public static boolean isprime(long n){if(n<=1)return false;else if(n==2)return true;else if (n%2==0)return false;for(long i=3;i<=Math.sqrt(n);i+=2){if(n%i==0)return false;}return true;} public static void rufflesort(int[]a){int n=a.length;for(int i=0;i<n;i++){ int oi=random.nextInt(n),temp=a[oi];a[oi]=a[i]; a[i]=temp;}Arrays.sort(a);} public static int pit(int n){int res=1;for(int i=2;i<n;i++)if(gcd(i,n)==1)res++;return res;} //===========================================================================================// public static class Node{ int data ; Node left, right; public Node (int data) { this.data = data; } } public static Node createTree() { Node root = null; System.out.println("data : "); int data = input.nextInt(); if(data == -1) return null; root = new Node(data); System.out.println("left : " + data); root.left = createTree(); System.out.println("right :"+ data); root.right = createTree(); return root; } public 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[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] readArrayL(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
java
1325
A
A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1≤t≤100)(1≤t≤100)  — the number of testcases.Each testcase consists of one line containing a single integer, xx (2≤x≤109)(2≤x≤109).OutputFor each testcase, output a pair of positive integers aa and bb (1≤a,b≤109)1≤a,b≤109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2 2 14 OutputCopy1 1 6 4 NoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14.
[ "constructive algorithms", "greedy", "number theory" ]
import java.util.Scanner; public class JavaApplication67 { 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=0,b=0; if(n%2==0){ a=n/2; b=n/2; } else{ a=n-1; b=1; } System.out.println(a+" "+b); } } }
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" ]
//Some of the methods are copied from GeeksforGeeks Website import java.util.*; import java.lang.*; import java.io.*; public class Main { //static Scanner sc=new Scanner(System.in); //static Reader sc=new Reader(); static FastReader sc=new FastReader(System.in); static long mod = (long)(1e9)+ 7; static int max_num=(int)1e5+5; public static void main (String[] args) throws java.lang.Exception { try{ /* Collections.sort(al,(a,b)->a.x-b.x); Collections.sort(al,Collections.reverseOrder()); StringBuilder sb=new StringBuilder(""); sb.append(cur); sb=sb.reverse(); String rev=sb.toString(); long n=sc.nextLong(); String s=sc.next(); char a[]=s.toCharArray(); StringBuilder sb=new StringBuilder(); map.put(a[i],map.getOrDefault(a[i],0)+1); map.putIfAbsent(x,new ArrayList<>()); out.println("Case #"+tt+": "+ans ); */ int t =1;// sc.nextInt(); for(int tt=1;tt<=t;tt++) { int q=sc.nextInt(); int x=sc.nextInt(); Set<Integer> set=new HashSet<>(); int lvl[]=new int[x]; int mex=0; for(int i=0;i<q;i++) { int y=sc.nextInt()%x; int val=lvl[y]*x+y; lvl[y]++; set.add(val); while(set.contains(mex)) mex++; out.println(mex); } } out.flush(); out.close(); } catch(Exception e) {} } /* ...SOLUTION ENDS HERE...........SOLUTION ENDS HERE... */ static void flag(boolean flag) { out.println(flag ? "YES" : "NO"); out.flush(); } /* Map<Long,Long> map=new HashMap<>(); for(int i=0;i<n;i++) { if(!map.containsKey(a[i])) map.put(a[i],1); else map.replace(a[i],map.get(a[i])+1); } Set<Map.Entry<Long,Long>> hmap=map.entrySet(); for(Map.Entry<Long,Long> data : hmap) { } Iterator<Integer> itr = set.iterator(); while(itr.hasNext()) { int val=itr.next(); } */ // static class Pair // { // int x,y; // Pair(int x,int y) // { // this.x=x; // this.y=y; // } // } // Arrays.sort(p, new Comparator<Pair>() // { // @Override // public int compare(Pair o1,Pair o2) // { // if(o1.x>o2.x) return 1; // else if(o1.x==o2.x) // { // if(o1.y>o2.y) return 1; // else return -1; // } // else return -1; // }}); static void print(int a[]) { int n=a.length; for(int i=0;i<n;i++) { out.print(a[i]+" "); } out.println(); out.flush(); } static void print(long a[]) { int n=a.length; for(int i=0;i<n;i++) { out.print(a[i]+" "); } out.println(); out.flush(); } static void print_int(ArrayList<Integer> al) { int si=al.size(); for(int i=0;i<si;i++) { out.print(al.get(i)+" "); } out.println(); out.flush(); } static void print_long(ArrayList<Long> al) { int si=al.size(); for(int i=0;i<si;i++) { out.print(al.get(i)+" "); } out.println(); out.flush(); } static void pn(int x) { out.println(x); out.flush(); } static void pn(long x) { out.println(x); out.flush(); } static void pn(String x) { out.println(x); out.flush(); } static int LowerBound(int a[], int x) { int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]>=x) r=m; else l=m; } return r; } static int UpperBound(int a[], int x) {// x is the key or target value int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]<=x) l=m; else r=m; } return l+1; } static void DFS(ArrayList<Integer> graph[],boolean[] visited, int u) { visited[u]=true; int v=0; for(int i=0;i<graph[u].size();i++) { v=graph[u].get(i); if(!visited[v]) DFS(graph,visited,v); } } static boolean[] prime(int num) { boolean[] bool = new boolean[num]; for (int i = 0; i< bool.length; i++) { bool[i] = true; } for (int i = 2; i< Math.sqrt(num); i++) { if(bool[i] == true) { for(int j = (i*i); j<num; j = j+i) { bool[j] = false; } } } if(num >= 0) { bool[0] = false; bool[1] = false; } return bool; } static long nCr(long a,long b,long mod) { return (((fact[(int)a] * modInverse(fact[(int)b],mod))%mod * modInverse(fact[(int)(a - b)],mod))%mod + mod)%mod; } static long fact[]=new long[max_num]; static void fact_fill() { fact[0]=1l; for(int i=1;i<max_num;i++) { fact[i]=(fact[i-1]*(long)i); if(fact[i]>=mod) fact[i]%=mod; } } static long modInverse(long a, long m) { return power(a, m - 2, m); } static long power(long x, long y, long m) { if (y == 0) return 1; long p = power(x, y / 2, m) % m; p = (long)((p * (long)p) % m); if (y % 2 == 0) return p; else return (long)((x * (long)p) % m); } static long sum_array(int a[]) { int n=a.length; long sum=0; for(int i=0;i<n;i++) sum+=a[i]; return sum; } static long sum_array(long a[]) { int n=a.length; long sum=0; for(int i=0;i<n;i++) sum+=a[i]; return sum; } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void sort(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void reverse_array(int a[]) { int n=a.length; int i,t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } static void reverse_array(long a[]) { int n=a.length; int i; long t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b%a, a); } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } static class FastReader{ byte[] buf = new byte[2048]; int index, total; InputStream in; FastReader(InputStream is) { in = is; } int scan() throws IOException { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) { return -1; } } return buf[index++]; } String next() throws IOException { int c; for (c = scan(); c <= 32; c = scan()); StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) { sb.append((char) c); } return sb.toString(); } int nextInt() throws IOException { int c, val = 0; for (c = scan(); c <= 32; c = scan()); boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } long nextLong() throws IOException { int c; long val = 0; for (c = scan(); c <= 32; c = scan()); boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static PrintWriter out=new PrintWriter(System.out); static int int_max=Integer.MAX_VALUE; static int int_min=Integer.MIN_VALUE; static long long_max=Long.MAX_VALUE; static long long_min=Long.MIN_VALUE; } // Thank You !
java
1312
C
C. Adding Powerstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSuppose you are performing the following algorithm. There is an array v1,v2,…,vnv1,v2,…,vn filled with zeroes at start. The following operation is applied to the array several times — at ii-th step (00-indexed) you can: either choose position pospos (1≤pos≤n1≤pos≤n) and increase vposvpos by kiki; or not choose any position and skip this step. You can choose how the algorithm would behave on each step and when to stop it. The question is: can you make array vv equal to the given array aa (vj=ajvj=aj for each jj) after some step?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases. Next 2T2T lines contain test cases — two lines per test case.The first line of each test case contains two integers nn and kk (1≤n≤301≤n≤30, 2≤k≤1002≤k≤100) — the size of arrays vv and aa and value kk used in the algorithm.The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10160≤ai≤1016) — the array you'd like to achieve.OutputFor each test case print YES (case insensitive) if you can achieve the array aa after some step or NO (case insensitive) otherwise.ExampleInputCopy5 4 100 0 0 0 0 1 2 1 3 4 1 4 1 3 2 0 1 3 3 9 0 59049 810 OutputCopyYES YES NO NO YES NoteIn the first test case; you can stop the algorithm before the 00-th step, or don't choose any position several times and stop the algorithm.In the second test case, you can add k0k0 to v1v1 and stop the algorithm.In the third test case, you can't make two 11 in the array vv.In the fifth test case, you can skip 9090 and 9191, then add 9292 and 9393 to v3v3, skip 9494 and finally, add 9595 to v2v2.
[ "bitmasks", "greedy", "implementation", "math", "number theory", "ternary search" ]
import java.io.*; import java.util.*; public class C { 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[]) { if (System.getProperty("ONLINE_JUDGE") == null) { // Input is a file try { System.setIn(new FileInputStream("input.txt")); System.setOut(new PrintStream(new FileOutputStream("output.txt"))); } catch (Exception e) { System.err.println("Error"); } } else { // Input is System.in } FastReader sc = new FastReader(); // Scanner sc = new Scanner(System.in); //System.out.println(java.time.LocalTime.now()); StringBuilder sb = new StringBuilder(); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); long k = sc.nextLong(); long[] arr = new long[n]; for (int i = 0; i < n; i++)arr[i] = sc.nextLong(); Set<Integer> set = new HashSet<>(); String ans = "YES"; boolean flag = true; int ind = -1; while (++ind != n) { if (arr[ind] == 0)continue; int pow = 0; while (arr[ind] != 0) { if (arr[ind] % k == 1) { if (set.contains(pow)) { flag = false; break; } else { set.add(pow); } } else if (arr[ind] % k != 0) { flag = false; break; } arr[ind] /= k; pow++; } if (!flag)break; } //System.out.println(set); if (!flag)ans = "NO"; sb.append(ans + "\n"); } System.out.println(sb); } //------------------------------------------------------------------------// class Pair implements Comparable<Pair> { int a; //first member of pair int b; //second member of pair public Pair(int a, int b) { this.a = a; this.b = b; } @Override public String toString() { return "(" + this.a + ", " + this.b + ")"; } @Override public int compareTo(Pair o) { return this.a - o.a; } } //----------------------------------------------------// public static void shuffleArray(int[] arr) { int n = arr.length; Random rnd = new Random(); for (int i = 0; i < n; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(n - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } //----------------------------------------------------// public static boolean isPowerOfTwo(long x) { return x != 0 && ((x & (x - 1)) == 0); } //----------------------------------------------------// public static long digSum(long a) { long sum = 0; while (a > 0) { sum += a % 10; a /= 10; } return sum; } //----------------------------------------------------// 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 += 6) { if (n % i == 0 || n % (i + 2) == 0)return false; } return true; } //----------------------------------------------------// public static int nextPrime(int n) { while (true) { n++; if (isPrime(n)) break; } return n; } //----------------------------------------------------// 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); } }
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 { 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 t=1; while(t-->0) { int ng = sc.nextInt(); while(ng --> 0) { int n = sc.nextInt(); char arr[] = sc.next().toCharArray(); ArrayList<Integer> list = new ArrayList<>(); for(int i=0;i<n;i++) { if(arr[i] == 'A') { list.add(i); } } if(list.size() == 0) { System.out.println(0); } else { list.add(n); int ans = Integer.MIN_VALUE; for(int i=0;i<list.size()-1;i++) { int diff = list.get(i + 1) - list.get(i) - 1; ans = Math.max(ans , diff); } System.out.println(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()); } 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; } } static class FenwickTree { //Binary Indexed Tree //1 indexed public int[] tree; public int size; public FenwickTree(int size) { this.size = size; tree = new int[size+5]; } public void add(int i, int v) { while(i <= size) { tree[i] += v; i += i&-i; } } public int find(int i) { int res = 0; while(i >= 1) { res += tree[i]; i -= i&-i; } return res; } public int find(int l, int r) { return find(r)-find(l-1); } } 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; } private static long mergeAndCount(int[] arr, int l, int m, int r) { // Left subarray int[] left = Arrays.copyOfRange(arr, l, m + 1); // Right subarray int[] right = Arrays.copyOfRange(arr, m + 1, r + 1); int i = 0, j = 0, k = l;long 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; } // Merge sort function private static long mergeSortAndCount(int[] arr, int l, int r) { // Keeps track of the inversion count at a // particular node of the recursion tree long count = 0; if (l < r) { int m = (l + r) / 2; // Total inversion count = left subarray count // + right subarray count + merge count // Left subarray count count += mergeSortAndCount(arr, l, m); // Right subarray count count += mergeSortAndCount(arr, m + 1, r); // Merge count count += mergeAndCount(arr, l, m, r); } return count; } static void my_sort(long[] arr) { ArrayList<Long> 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); } } static void reverse_sorted(int[] arr) { ArrayList<Integer> list = new ArrayList<>(); for(int i=0;i<arr.length;i++) { list.add(arr[i]); } Collections.sort(list , Collections.reverseOrder()); for(int i=0;i<arr.length;i++) { arr[i] = list.get(i); } } static int LowerBound(int a[], int x) { // x is the target value or key int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]>=x) r=m; else l=m; } return r; } static int UpperBound(ArrayList<Integer> list, int x) {// x is the key or target value int l=-1,r=list.size(); while(l+1<r) { int m=(l+r)>>>1; if(list.get(m)<=x) l=m; else r=m; } return l+1; } 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 class Queue_Pair implements Comparable<Queue_Pair> { int first , second; public Queue_Pair(int first, int second) { this.first=first; this.second=second; } public int compareTo(Queue_Pair o) { return Integer.compare(o.first, first); } } static void leftRotate(int arr[], int d, int n) { for (int i = 0; i < d; i++) leftRotatebyOne(arr, n); } static void leftRotatebyOne(int arr[], int n) { int i, temp; temp = arr[0]; for (i = 0; i < n - 1; i++) arr[i] = arr[i + 1]; arr[n-1] = temp; } static boolean isPalindrome(String str) { // Pointers pointing to the beginning // and the end of the string int i = 0, j = str.length() - 1; // While there are characters to compare while (i < j) { // If there is a mismatch if (str.charAt(i) != str.charAt(j)) return false; // Increment first pointer and // decrement the other i++; j--; } // Given string is a palindrome return true; } static boolean palindrome_array(char arr[], int n) { // Initialise flag to zero. int flag = 0; // Loop till array size n/2. for (int i = 0; i <= n / 2 && n != 0; i++) { // Check if first and last element are different // Then set flag to 1. if (arr[i] != arr[n - i - 1]) { flag = 1; break; } } // If flag is set then print Not Palindrome // else print Palindrome. if (flag == 1) return false; else return true; } static boolean allElementsEqual(int[] arr,int n) { int z=0; for(int i=0;i<n-1;i++) { if(arr[i]==arr[i+1]) { z++; } } if(z==n-1) { return true; } else { return false; } } static boolean allElementsDistinct(int[] arr,int n) { int z=0; for(int i=0;i<n-1;i++) { if(arr[i]!=arr[i+1]) { z++; } } if(z==n-1) { return true; } else { return false; } } public static void reverse(int[] array) { // Length of the array int n = array.length; // Swaping the first half elements with last half // elements for (int i = 0; i < n / 2; i++) { // Storing the first half elements temporarily int temp = array[i]; // Assigning the first half to the last half array[i] = array[n - i - 1]; // Assigning the last half to the first half array[n - i - 1] = temp; } } public static void reverse_Long(long[] array) { // Length of the array int n = array.length; // Swaping the first half elements with last half // elements for (int i = 0; i < n / 2; i++) { // Storing the first half elements temporarily long temp = array[i]; // Assigning the first half to the last half array[i] = array[n - i - 1]; // Assigning the last half to the first half array[n - i - 1] = temp; } } static boolean isSorted(int[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { return false; } } return true; } static boolean isReverseSorted(int[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] < a[i + 1]) { return false; } } return true; } static int[] rearrangeEvenAndOdd(int arr[], int n) { ArrayList<Integer> list = new ArrayList<>(); for(int i=0;i<n;i++) { if(arr[i]%2==0) { list.add(arr[i]); } } for(int i=0;i<n;i++) { if(arr[i]%2!=0) { list.add(arr[i]); } } int len = list.size(); int[] array = list.stream().mapToInt(i->i).toArray(); return array; } static long[] rearrangeEvenAndOddLong(long arr[], int n) { ArrayList<Long> list = new ArrayList<>(); for(int i=0;i<n;i++) { if(arr[i]%2==0) { list.add(arr[i]); } } for(int i=0;i<n;i++) { if(arr[i]%2!=0) { list.add(arr[i]); } } int len = list.size(); long[] array = list.stream().mapToLong(i->i).toArray(); return array; } static boolean isPrime(long 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 (long i = 3; i <= Math.sqrt(n); i += 2) { if (n % i == 0) return false; } return true; } static long getSum(long n) { long sum = 0; while (n != 0) { sum = sum + n % 10; n = n/10; } return sum; } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static long gcdLong(long a, long b) { if (b == 0) return a; return gcdLong(b, a % b); } static void swap(int i, int j) { int temp = i; i = j; j = temp; } static int countDigit(int n) { return (int)Math.floor(Math.log10(n) + 1); } } class Pair { int first; int second; Pair(int first , int second) { this.first = first; this.second = second; } }
java
1296
F
F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values: his departure station ajaj; his arrival station bjbj; minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4 1 2 3 2 3 4 2 1 2 5 1 3 3 OutputCopy5 3 5 InputCopy6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 OutputCopy5 3 1 2 1 InputCopy6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 OutputCopy-1
[ "constructive algorithms", "dfs and similar", "greedy", "sortings", "trees" ]
import java.io.*; import java.util.*; public class Task { public static void main(String[] args) throws Exception { new Task().go(); } PrintWriter out; Reader in; BufferedReader br; Task() throws IOException { try { //br = new BufferedReader( new FileReader("input.txt") ); //in = new Reader("input.txt"); in = new Reader("input.txt"); out = new PrintWriter( new BufferedWriter(new FileWriter("output.txt")) ); } catch (Exception e) { //br = new BufferedReader( new InputStreamReader( System.in ) ); in = new Reader(); out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out)) ); } } void go() throws Exception { //int t = in.nextInt(); int t = 1; while (t > 0) { solve(); t--; } out.flush(); out.close(); } int inf = 2000000000; int mod = 1000000007; double eps = 0.000000001; int n; int m; ArrayList<Integer>[] g; int[][] buity = new int[5000][5000]; void solve() throws IOException { int n = in.nextInt(); g = new ArrayList[n]; Pair[] edges = new Pair[n - 1]; for (int i = 0; i < n; i++) g[i] = new ArrayList<>(); for (int i = 0; i < n - 1; i++) { int x = in.nextInt() - 1; int y = in.nextInt() - 1; g[x].add(y); g[y].add(x); buity[x][y] = 1; buity[y][x] = 1; edges[i] = new Pair(x, y); } boolean ok = true; int m = in.nextInt(); int[][] paths = new int[m][n + 1]; int[] gs = new int[m]; int[] p = new int[n]; ArrayDeque<Integer> q = new ArrayDeque<>(); for (int i = 0; i < m; i++) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; int z = in.nextInt(); gs[i] = z; q.add(a); Arrays.fill(p, -1); p[a] = a; while (!q.isEmpty()) { int v = q.poll(); for (int u : g[v]) { if (p[u] == -1) { p[u] = v; q.add(u); } } } int pos = 1; while (b != a) { paths[i][pos] = b; pos++; int prev = b; b = p[b]; if (buity[prev][b] < z) { buity[prev][b] = z; buity[b][prev] = z; } } paths[i][pos] = a; pos++; paths[i][0] = pos; } for (int i = 0; i < m; i++) { int min = 1000000; int len = paths[i][0]; for (int j = 2; j < len; j++) { int x = paths[i][j - 1]; int y = paths[i][j]; min = Math.min(min, buity[x][y]); } ok &= min == gs[i]; } if (ok) { for (int i = 0; i < n - 1; i++) out.print(buity[edges[i].a][edges[i].b] + " "); } else { out.println(-1); } } class Pair implements Comparable<Pair> { int a; int b; Pair(int a, int b) { this.a = a; this.b = b; } public int compareTo(Pair p) { if (a != p.a) return Integer.compare(a, p.a); else return Integer.compare(-b, -p.b); } } class Item { int a; int b; int c; Item(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } } class Reader { BufferedReader br; StringTokenizer tok; Reader(String file) throws IOException { br = new BufferedReader( new FileReader(file) ); } Reader() throws IOException { br = new BufferedReader( new InputStreamReader(System.in) ); } String next() throws IOException { while (tok == null || !tok.hasMoreElements()) tok = new StringTokenizer(br.readLine()); return tok.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.valueOf(next()); } long nextLong() throws NumberFormatException, IOException { return Long.valueOf(next()); } double nextDouble() throws NumberFormatException, IOException { return Double.valueOf(next()); } String nextLine() throws IOException { return br.readLine(); } } static class InputReader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public InputReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public InputReader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
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.lang.*; import java.io.*; public class Main { static long mod = (int)1e9+7; public static void main (String[] args) throws java.lang.Exception { FastReader sc =new FastReader(); int t=sc.nextInt(); // int t=1; while(t-->0) { int a=sc.nextInt(); int b=sc.nextInt(); int x=sc.nextInt(); int y=sc.nextInt(); int first = a * y; int second = (b -y -1) * a; int third = (a - x -1) * b; int fourth = b * x; int ans = Math.max(first , Math.max(second , Math.max(third , fourth))); System.out.println(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()); } 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; } 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 void leftRotate(int arr[], int d, int n) { for (int i = 0; i < d; i++) leftRotatebyOne(arr, n); } static void leftRotatebyOne(int arr[], int n) { int i, temp; temp = arr[0]; for (i = 0; i < n - 1; i++) arr[i] = arr[i + 1]; arr[n-1] = temp; } static boolean isPalindrome(String str) { // Pointers pointing to the beginning // and the end of the string int i = 0, j = str.length() - 1; // While there are characters to compare while (i < j) { // If there is a mismatch if (str.charAt(i) != str.charAt(j)) return false; // Increment first pointer and // decrement the other i++; j--; } // Given string is a palindrome return true; } static boolean palindrome_array(char arr[], int n) { // Initialise flag to zero. int flag = 0; // Loop till array size n/2. for (int i = 0; i <= n / 2 && n != 0; i++) { // Check if first and last element are different // Then set flag to 1. if (arr[i] != arr[n - i - 1]) { flag = 1; break; } } // If flag is set then print Not Palindrome // else print Palindrome. if (flag == 1) return false; else return true; } static boolean allElementsEqual(int[] arr,int n) { int z=0; for(int i=0;i<n-1;i++) { if(arr[i]==arr[i+1]) { z++; } } if(z==n-1) { return true; } else { return false; } } static boolean allElementsDistinct(int[] arr,int n) { int z=0; for(int i=0;i<n-1;i++) { if(arr[i]!=arr[i+1]) { z++; } } if(z==n-1) { return true; } else { return false; } } public static void reverse(int[] array) { // Length of the array int n = array.length; // Swaping the first half elements with last half // elements for (int i = 0; i < n / 2; i++) { // Storing the first half elements temporarily int temp = array[i]; // Assigning the first half to the last half array[i] = array[n - i - 1]; // Assigning the last half to the first half array[n - i - 1] = temp; } } public static void reverse_Long(long[] array) { // Length of the array int n = array.length; // Swaping the first half elements with last half // elements for (int i = 0; i < n / 2; i++) { // Storing the first half elements temporarily long temp = array[i]; // Assigning the first half to the last half array[i] = array[n - i - 1]; // Assigning the last half to the first half array[n - i - 1] = temp; } } static boolean isSorted(int[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { return false; } } return true; } static boolean isReverseSorted(int[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] < a[i + 1]) { return false; } } return true; } static int[] rearrangeEvenAndOdd(int arr[], int n) { ArrayList<Integer> list = new ArrayList<>(); for(int i=0;i<n;i++) { if(arr[i]%2==0) { list.add(arr[i]); } } for(int i=0;i<n;i++) { if(arr[i]%2!=0) { list.add(arr[i]); } } int len = list.size(); int[] array = list.stream().mapToInt(i->i).toArray(); return array; } static long[] rearrangeEvenAndOddLong(long arr[], int n) { ArrayList<Long> list = new ArrayList<>(); for(int i=0;i<n;i++) { if(arr[i]%2==0) { list.add(arr[i]); } } for(int i=0;i<n;i++) { if(arr[i]%2!=0) { list.add(arr[i]); } } int len = list.size(); long[] array = list.stream().mapToLong(i->i).toArray(); return array; } static boolean isPrime(long 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 (long i = 3; i <= Math.sqrt(n); i += 2) { if (n % i == 0) return false; } return true; } static int getSum(int n) { int sum = 0; while (n != 0) { sum = sum + n % 10; n = n/10; } return sum; } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static long gcdLong(long a, long b) { if (b == 0) return a; return gcdLong(b, a % b); } static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } static int countDigit(long n) { return (int)Math.floor(Math.log10(n) + 1); } }
java
1301
D
D. Time to Runtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputBashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father); so he should lose weight.In order to lose weight, Bashar is going to run for kk kilometers. Bashar is going to run in a place that looks like a grid of nn rows and mm columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4nm−2n−2m)(4nm−2n−2m) roads.Let's take, for example, n=3n=3 and m=4m=4. In this case, there are 3434 roads. It is the picture of this case (arrows describe roads):Bashar wants to run by these rules: He starts at the top-left cell in the grid; In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row ii and in the column jj, i.e. in the cell (i,j)(i,j) he will move to: in the case 'U' to the cell (i−1,j)(i−1,j); in the case 'D' to the cell (i+1,j)(i+1,j); in the case 'L' to the cell (i,j−1)(i,j−1); in the case 'R' to the cell (i,j+1)(i,j+1); He wants to run exactly kk kilometers, so he wants to make exactly kk moves; Bashar can finish in any cell of the grid; He can't go out of the grid so at any moment of the time he should be on some cell; Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times. Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.You should give him aa steps to do and since Bashar can't remember too many steps, aa should not exceed 30003000. In every step, you should give him an integer ff and a string of moves ss of length at most 44 which means that he should repeat the moves in the string ss for ff times. He will perform the steps in the order you print them.For example, if the steps are 22 RUD, 33 UUL then the moves he is going to move are RUD ++ RUD ++ UUL ++ UUL ++ UUL == RUDRUDUULUULUUL.Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to kk kilometers or say, that it is impossible?InputThe only line contains three integers nn, mm and kk (1≤n,m≤5001≤n,m≤500, 1≤k≤1091≤k≤109), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.OutputIf there is no possible way to run kk kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.If the answer is "YES", on the second line print an integer aa (1≤a≤30001≤a≤3000) — the number of steps, then print aa lines describing the steps.To describe a step, print an integer ff (1≤f≤1091≤f≤109) and a string of moves ss of length at most 44. Every character in ss should be 'U', 'D', 'L' or 'R'.Bashar will start from the top-left cell. Make sure to move exactly kk moves without visiting the same road twice and without going outside the grid. He can finish at any cell.We can show that if it is possible to run exactly kk kilometers, then it is possible to describe the path under such output constraints.ExamplesInputCopy3 3 4 OutputCopyYES 2 2 R 2 L InputCopy3 3 1000000000 OutputCopyNO InputCopy3 3 8 OutputCopyYES 3 2 R 2 D 1 LLRR InputCopy4 4 9 OutputCopyYES 1 3 RLD InputCopy3 4 16 OutputCopyYES 8 3 R 3 L 1 D 3 R 1 D 1 U 3 L 1 D NoteThe moves Bashar is going to move in the first example are: "RRLL".It is not possible to run 10000000001000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.The moves Bashar is going to move in the third example are: "RRDDLLRR".The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
[ "constructive algorithms", "graphs", "implementation" ]
import java.io.*; import java.util.*; import java.awt.Point; public class timetorun { static LinkedList<Integer>[] ll; public static void main(String[] args) throws Exception { Scanner sc=new Scanner(System.in); int n=sc.nextInt(),m=sc.nextInt(),k=sc.nextInt(); int total=4*n*m-2*(n+m); if(k>total){ System.out.println("NO"); return; } int steps=0; StringBuilder sb=new StringBuilder(); boolean z=false; int km=0; for(int i=0;i<n-1;i++){ for(int j=1;j<m;j++){ km++; sb.append("R"); if(km==k){ z=true; break; } } if(z)break; for(int j=m-2;j>=0;j--){ km++; sb.append("L"); if(km==k){ z=true; break; } } if(z)break; sb.append("D"); km++; if(km==k){ z=true; break; } } for(int i=1;i<m && !z;i++){ km++; sb.append("R"); if(km==k){ z=true; break; } } for(int i=m-1;i>=1 && !z;i--){ for(int j=1;j<n;j++){ km++; sb.append("U"); if(km==k){ z=true; break; } } if(z)break; for(int j=n-2;j>=0;j--){ km++; sb.append("D"); if(km==k){ z=true; break; } } if(z)break; sb.append("L");km++; if(km==k){ z=true; break; } } for(int i=n-2;i>=0 && !z;i--){ sb.append("U");km++; if(km==k){ z=true; break; } } StringBuilder sb2=new StringBuilder(); int temp=1; for(int i=1;i<sb.length();i++){ if(sb.charAt(i)==sb.charAt(i-1))temp++; else{ sb2.append(temp+" "+sb.charAt(i-1)+"\n"); temp=1; steps++; } } sb2.append(temp+" "+sb.charAt(sb.length()-1)); steps++; System.out.println("YES\n"+steps); System.out.println(sb2); } }
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
1313
D
D. Happy New Yeartime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputBeing Santa Claus is very difficult. Sometimes you have to deal with difficult situations.Today Santa Claus came to the holiday and there were mm children lined up in front of him. Let's number them from 11 to mm. Grandfather Frost knows nn spells. The ii-th spell gives a candy to every child whose place is in the [Li,Ri][Li,Ri] range. Each spell can be used at most once. It is also known that if all spells are used, each child will receive at most kk candies.It is not good for children to eat a lot of sweets, so each child can eat no more than one candy, while the remaining candies will be equally divided between his (or her) Mom and Dad. So it turns out that if a child would be given an even amount of candies (possibly zero), then he (or she) will be unable to eat any candies and will go sad. However, the rest of the children (who received an odd number of candies) will be happy.Help Santa Claus to know the maximum number of children he can make happy by casting some of his spells.InputThe first line contains three integers of nn, mm, and kk (1≤n≤100000,1≤m≤109,1≤k≤81≤n≤100000,1≤m≤109,1≤k≤8) — the number of spells, the number of children and the upper limit on the number of candy a child can get if all spells are used, respectively.This is followed by nn lines, each containing integers LiLi and RiRi (1≤Li≤Ri≤m1≤Li≤Ri≤m) — the parameters of the ii spell.OutputPrint a single integer — the maximum number of children that Santa can make happy.ExampleInputCopy3 5 31 32 43 5OutputCopy4NoteIn the first example, Santa should apply the first and third spell. In this case all children will be happy except the third.
[ "bitmasks", "dp", "implementation" ]
import java.io.*; import java.util.*; public class Main{ static int n,m,k; static int[]idxInMask; static event[]in; static class event implements Comparable<event>{ int type,x,idx; event(int t,int xx,int ii){ type=t;//start -> 0 , end -> 1 x=xx; idx=ii; } @Override public int compareTo(event o) { return x==o.x?type-o.type:x-o.x; } } static int[][]memo; static int dp(int i,int msk) { if(i>=2*n)return 0; if(memo[i][msk]!=-1)return memo[i][msk]; if(in[i].type==0) { int nxt=in[i+1].type; int newmsk=msk|(1<<idxInMask[in[i].idx]); int incTake=0,incLeave=0; if(Integer.bitCount(newmsk)%2==1) { incTake=in[i+1].x-in[i].x; if(nxt==1) { incTake++; } } else { incLeave=in[i+1].x-in[i].x; if(nxt==1) { incLeave++; } } return memo[i][msk]=Math.max(dp(i+1, newmsk)+incTake, dp(i+1, msk)+incLeave); } int inc=0; int newmsk=msk; if((newmsk&(1<<idxInMask[in[i].idx]))!=0) newmsk=msk^(1<<idxInMask[in[i].idx]); if(Integer.bitCount(newmsk)%2==1) { if(i+1<2*n) { inc=in[i+1].x-in[i].x; if(in[i+1].type==0)inc--; } } return memo[i][msk]=dp(i+1,newmsk)+inc; } public static void main(String[] args) throws Exception{ MScanner sc=new MScanner(System.in); PrintWriter pw=new PrintWriter(System.out); n=sc.nextInt();m=sc.nextInt();k=sc.nextInt(); in=new event[2*n]; for(int i=0;i<n;i++) { in[2*i]=new event(0, sc.nextInt(), i); in[2*i+1]=new event(1, sc.nextInt(), i); } Arrays.sort(in); idxInMask=new int[n]; boolean[]indices=new boolean[k]; for(int i=0;i<2*n;i++) { if(in[i].type==0) { int idx=0; while(indices[idx])idx++; idxInMask[in[i].idx]=idx; indices[idx]=true; } else { int idx=idxInMask[in[i].idx]; indices[idx]=false; } } memo=new int[2*n][1<<k]; for(int[]i:memo)Arrays.fill(i, -1); pw.println(dp(0,0)); 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
1315
B
B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs: buy one bus ticket to get from 11 to 33, buy one tram ticket to get from 33 to 66, buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5 2 2 1 BB 1 1 1 AB 3 2 8 AABBBBAABB 5 3 4 BBBBB 2 1 1 ABABAB OutputCopy2 1 3 1 6
[ "binary search", "dp", "greedy", "strings" ]
import java.util.*; public class B1315 { public static boolean check(String s, long a , long b,int idx,long p){ long cost = 0; for(int i=idx;i<s.length()-1;i++){ char ch = s.charAt(i); while(i<s.length() && s.charAt(i)==ch) i++; i--; cost +=(ch=='A' ? a : b); } return cost<=p; } public static void main(String[] args) { Scanner scn = new Scanner(System.in); int t = scn.nextInt(); while(t-->0){ long a =scn.nextInt(); long b = scn.nextInt(); long p =scn.nextInt(); String s = scn.next(); int si = 0; int ei = s.length()-1; int res = s.length(); while(si<=ei){ int mid = (si+ei)/2; // char ch = s.charAt(mid); boolean flag = check(s, a, b, mid, p); if(flag){ ei = mid-1; res = Math.min(res,mid); }else{ si = mid+1; } } System.out.println(res+1); } } }
java
1303
C
C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following: if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem); otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5 ababa codedoca abcda zxzytyz abcdefghijklmnopqrstuvwxyza OutputCopyYES bacdefghijklmnopqrstuvwxyz YES edocabfghijklmnpqrstuvwxyz NO YES xzytabcdefghijklmnopqrsuvw NO
[ "dfs and similar", "greedy", "implementation" ]
import java.io.*; import java.util.*; public class Perfect_Keyboard { static FastScanner fs; static FastWriter fw; static boolean checkOnlineJudge = System.getProperty("ONLINE_JUDGE") == null; private static final int[][] kdir = new int[][]{{-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}, {1, -2}, {2, -1}, {2, 1}, {1, 2}}; private static final int[][] dir = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}}; private static final int iMax = (int) (1e9 + 100), iMin = (int) (-1e9 - 100); private static final long lMax = (long) (1e18 + 100), lMin = (long) (-1e18 - 100); private static final int mod1 = (int) (1e9 + 7); private static final int mod2 = 998244353; public static void main(String[] args) throws IOException { fs = new FastScanner(); fw = new FastWriter(); int t = 1; t = fs.nextInt(); while (t-- > 0) { solve(); } fw.out.close(); } private static void solve() { String s = fs.nextLine(); int n = s.length(); char[] arr = new char[100]; Arrays.fill(arr, '#'); arr[30] = s.charAt(0); int[] indexes = new int[26]; Arrays.fill(indexes, -1); indexes[s.charAt(0) - 'a'] = 30; for (int i = 1; i < n; i++) { char c = s.charAt(i); char prev_char = s.charAt(i - 1); int idx = indexes[prev_char - 'a']; if (indexes[c - 'a'] != -1) { if (!(arr[idx + 1] == c || arr[idx - 1] == c)) { fw.out.println("NO"); return; } } else { if (arr[idx + 1] == '#') { arr[idx + 1] = c; indexes[c - 'a'] = idx + 1; } else if (arr[idx - 1] == '#') { arr[idx - 1] = c; indexes[c - 'a'] = idx - 1; } else { fw.out.println("NO"); return; } } } StringBuilder ans = new StringBuilder(); for (int i = 0; i < 26; i++) { if (indexes[i] == -1) { char c = (char) (i + 'a'); ans.append(c); } } for (int i = 0; i < 100; i++) { if (arr[i] != '#') ans.append(arr[i]); } fw.out.println("YES"); fw.out.println(ans); } private static class UnionFind { private final int[] parent; private final int[] rank; UnionFind(int n) { parent = new int[n + 5]; rank = new int[n + 5]; for (int i = 0; i <= n; i++) { parent[i] = i; rank[i] = 0; } } private int find(int i) { if (parent[i] == i) return i; return parent[i] = find(parent[i]); } private void union(int a, int b) { a = find(a); b = find(b); if (a != b) { if (rank[a] < rank[b]) { int temp = a; a = b; b = temp; } parent[b] = a; if (rank[a] == rank[b]) rank[a]++; } } } private static class Calc_nCr { private final long[] fact; private final long[] invfact; private final int p; Calc_nCr(int n, int prime) { fact = new long[n + 5]; invfact = new long[n + 5]; p = prime; fact[0] = 1; for (int i = 1; i <= n; i++) { fact[i] = (i * fact[i - 1]) % p; } invfact[n] = pow(fact[n], p - 2, p); for (int i = n - 1; i >= 0; i--) { invfact[i] = (invfact[i + 1] * (i + 1)) % p; } } private long nCr(int n, int r) { if (r > n || n < 0 || r < 0) return 0; return (((fact[n] * invfact[r]) % p) * invfact[n - r]) % p; } } private static long gcd(long a, long b) { return (b == 0 ? a : gcd(b, a % b)); } private static long lcm(long a, long b) { return ((a * b) / gcd(a, b)); } private static long pow(long a, long b, int mod) { long result = 1; while (b > 0) { if ((b & 1L) == 1) { result = (result * a) % mod; } a = (a * a) % mod; b >>= 1; } return result; } private static long ceilDiv(long a, long b) { return ((a + b - 1) / b); } private static long getMin(long... args) { long min = lMax; for (long arg : args) min = Math.min(min, arg); return min; } private static long getMax(long... args) { long max = lMin; for (long arg : args) max = Math.max(max, arg); return max; } private static boolean isPalindrome(String s, int l, int r) { int i = l, j = r; while (j - i >= 1) { if (s.charAt(i) != s.charAt(j)) return false; i++; j--; } return true; } private static List<Integer> primes(int n) { boolean[] primeArr = new boolean[n + 5]; Arrays.fill(primeArr, true); for (int i = 2; (i * i) <= n; i++) { if (primeArr[i]) { for (int j = i * i; j <= n; j += i) { primeArr[j] = false; } } } List<Integer> primeList = new ArrayList<>(); for (int i = 2; i <= n; i++) { if (primeArr[i]) primeList.add(i); } return primeList; } private static int noOfSetBits(long x) { int cnt = 0; while (x != 0) { x = x & (x - 1); cnt++; } return cnt; } private static boolean isPerfectSquare(long num) { long sqrt = (long) Math.sqrt(num); return ((sqrt * sqrt) == num); } private static class Pair<U, V> { private final U first; private final V second; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; return first.equals(pair.first) && second.equals(pair.second); } @Override public int hashCode() { return Objects.hash(first, second); } @Override public String toString() { return "(" + first + ", " + second + ")"; } private Pair(U ff, V ss) { this.first = ff; this.second = ss; } } private static void randomizeIntArr(int[] arr, int n) { Random r = new Random(); for (int i = (n - 1); i > 0; i--) { int j = r.nextInt(i + 1); swapInIntArr(arr, i, j); } } private static void randomizeLongArr(long[] arr, int n) { Random r = new Random(); for (int i = (n - 1); i > 0; i--) { int j = r.nextInt(i + 1); swapInLongArr(arr, i, j); } } private static void swapInIntArr(int[] arr, int a, int b) { int temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } private static void swapInLongArr(long[] arr, int a, int b) { long temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } private static int[] readIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = fs.nextInt(); return arr; } private static long[] readLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = fs.nextLong(); return arr; } private static List<Integer> readIntList(int n) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(fs.nextInt()); return list; } private static List<Long> readLongList(int n) { List<Long> list = new ArrayList<>(); for (int i = 0; i < n; i++) list.add(fs.nextLong()); return list; } private static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner() throws IOException { if (checkOnlineJudge) this.br = new BufferedReader(new FileReader("src/input.txt")); else this.br = new BufferedReader(new InputStreamReader(System.in)); this.st = new StringTokenizer(""); } public String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException err) { err.printStackTrace(); } } return st.nextToken(); } public String nextLine() { if (st.hasMoreTokens()) { return st.nextToken("").trim(); } try { return br.readLine().trim(); } catch (IOException err) { err.printStackTrace(); } return ""; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } private static class FastWriter { PrintWriter out; FastWriter() throws IOException { if (checkOnlineJudge) out = new PrintWriter(new FileWriter("src/output.txt")); else out = new PrintWriter(System.out); } } }
java
1324
D
D. Pair of Topicstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThe next lecture in a high school requires two topics to be discussed. The ii-th topic is interesting by aiai units for the teacher and by bibi units for the students.The pair of topics ii and jj (i<ji<j) is called good if ai+aj>bi+bjai+aj>bi+bj (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of topics.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109), where aiai is the interestingness of the ii-th topic for the teacher.The third line of the input contains nn integers b1,b2,…,bnb1,b2,…,bn (1≤bi≤1091≤bi≤109), where bibi is the interestingness of the ii-th topic for the students.OutputPrint one integer — the number of good pairs of topic.ExamplesInputCopy5 4 8 2 6 2 4 5 4 1 3 OutputCopy7 InputCopy4 1 3 2 4 1 3 2 4 OutputCopy0
[ "binary search", "data structures", "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 D_Pair_of_Topics { 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 a[] = f.nextArray(n); int b[] = f.nextArray(n); int sub[] = new int[n]; for(int i = 0; i < n; i++) { sub[i] = a[i] - b[i]; } sort(sub); long ans = 0; for(int i = n-1; i >= 0; i--) { if(sub[i] <= 0) { break; } ans += func(sub, i); } out.println(ans); } public static int func(int arr[], int ind) { int r = ind-1; int l = 0; int reqInd = -1; while(r >= l) { int mid = (l+r)/2; if(arr[mid]+arr[ind] > 0) { reqInd = mid; r = mid-1; } else { l = mid+1; } } return (reqInd == -1) ? 0 : ind - reqInd; } // 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
1304
F2
F2. Animal Observation (hard version)time limit per test3 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputThe only difference between easy and hard versions is the constraint on kk.Gildong loves observing animals, so he bought two cameras to take videos of wild animals in a forest. The color of one camera is red, and the other one's color is blue.Gildong is going to take videos for nn days, starting from day 11 to day nn. The forest can be divided into mm areas, numbered from 11 to mm. He'll use the cameras in the following way: On every odd day (11-st, 33-rd, 55-th, ...), bring the red camera to the forest and record a video for 22 days. On every even day (22-nd, 44-th, 66-th, ...), bring the blue camera to the forest and record a video for 22 days. If he starts recording on the nn-th day with one of the cameras, the camera records for only one day. Each camera can observe kk consecutive areas of the forest. For example, if m=5m=5 and k=3k=3, he can put a camera to observe one of these three ranges of areas for two days: [1,3][1,3], [2,4][2,4], and [3,5][3,5].Gildong got information about how many animals will be seen in each area on each day. Since he would like to observe as many animals as possible, he wants you to find the best way to place the two cameras for nn days. Note that if the two cameras are observing the same area on the same day, the animals observed in that area are counted only once.InputThe first line contains three integers nn, mm, and kk (1≤n≤501≤n≤50, 1≤m≤2⋅1041≤m≤2⋅104, 1≤k≤m1≤k≤m) – the number of days Gildong is going to record, the number of areas of the forest, and the range of the cameras, respectively.Next nn lines contain mm integers each. The jj-th integer in the i+1i+1-st line is the number of animals that can be seen on the ii-th day in the jj-th area. Each number of animals is between 00 and 10001000, inclusive.OutputPrint one integer – the maximum number of animals that can be observed.ExamplesInputCopy4 5 2 0 2 1 1 0 0 0 3 1 2 1 0 4 3 1 3 3 0 0 4 OutputCopy25 InputCopy3 3 1 1 2 3 4 5 6 7 8 9 OutputCopy31 InputCopy3 3 2 1 2 3 4 5 6 7 8 9 OutputCopy44 InputCopy3 3 3 1 2 3 4 5 6 7 8 9 OutputCopy45 NoteThe optimal way to observe animals in the four examples are as follows:Example 1: Example 2: Example 3: Example 4:
[ "data structures", "dp", "greedy" ]
import java.util.*; import java.io.*; public class Animals{ static int lim=20050; static int n,m,k,temp,max; static int[][] M = new int[55][lim]; static int[][] DP = new int[55][lim]; static Deque<tuple> mono = new LinkedList<>(); public static void insert(tuple e){ while(!mono.isEmpty()&& e.v>mono.peekLast().v){mono.removeLast();} mono.addLast(e); } public static void drop(int i){ if(mono.peekFirst().i==i){mono.removeFirst();} } public static int sum(int l,int p,int q){ return M[l][q]-M[l][p-1]; } public static int lpun(int l, int x){ return DP[l-1][x]-M[l][x+k-1]; } public static int rpun(int l, int x){ return DP[l-1][x]+M[l][x-1]; } public static void main(String[] args) throws IOException{ Reader in = new Reader(); n = in.nextInt();m = in.nextInt();k = in.nextInt(); for (int i = 1; i <=n; i++) { for (int j = 1; j <=m; j++) { M[i][j]=in.nextInt()+M[i][j-1]; } } for (int i = 1; i <= m-k+1; i++) { DP[1][i]=sum(1,i,i+k-1)+sum(2,i,i+k-1); } tuple tem; for (int i = 2; i <= n; i++) { //left max=0;mono.clear(); for (int j = 1; j <= m-k+1; j++) { if(j>k){drop(j-k);max = Math.max(max,DP[i-1][j-k]);} insert(new tuple(j, lpun(i,j))); tem = mono.peekFirst(); DP[i][j] = Math.max(DP[i-1][tem.i]+sum(i,tem.i+k,j+k-1), max+sum(i,j,j+k-1)); } //right max=0;mono.clear(); for (int j = m-k+1; j >= 1; j--) { if(j+k<= m-k+1){drop(j+k);max = Math.max(max,DP[i-1][j+k]);} insert(new tuple(j, rpun(i,j))); tem = mono.peekFirst(); DP[i][j] = Math.max(DP[i][j],Math.max(DP[i-1][tem.i]+sum(i,j,tem.i-1), max+sum(i,j,j+k-1))); } for(int j=1;j<=m-k+1;j++){DP[i][j]+=sum(i+1,j,j+k-1);} } int ans=0; for (int i = 1; i <= m-k+1; i++) { ans = Math.max(DP[n][i],ans); } System.out.println(ans); in.close(); } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } } class tuple{ int i,v; public tuple(int a,int b){ this.i=a;this.v=b; } }
java
1141
C
C. Polycarp Restores Permutationtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputAn array of integers p1,p2,…,pnp1,p2,…,pn is called a permutation if it contains each number from 11 to nn exactly once. For example, the following arrays are permutations: [3,1,2][3,1,2], [1][1], [1,2,3,4,5][1,2,3,4,5] and [4,3,1,2][4,3,1,2]. The following arrays are not permutations: [2][2], [1,1][1,1], [2,3,4][2,3,4].Polycarp invented a really cool permutation p1,p2,…,pnp1,p2,…,pn of length nn. It is very disappointing, but he forgot this permutation. He only remembers the array q1,q2,…,qn−1q1,q2,…,qn−1 of length n−1n−1, where qi=pi+1−piqi=pi+1−pi.Given nn and q=q1,q2,…,qn−1q=q1,q2,…,qn−1, help Polycarp restore the invented permutation.InputThe first line contains the integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the length of the permutation to restore. The second line contains n−1n−1 integers q1,q2,…,qn−1q1,q2,…,qn−1 (−n<qi<n−n<qi<n).OutputPrint the integer -1 if there is no such permutation of length nn which corresponds to the given array qq. Otherwise, if it exists, print p1,p2,…,pnp1,p2,…,pn. Print any such permutation if there are many of them.ExamplesInputCopy3 -2 1 OutputCopy3 1 2 InputCopy5 1 1 1 1 OutputCopy1 2 3 4 5 InputCopy4 -1 2 2 OutputCopy-1
[ "math" ]
import java.io.*; import java.util.*; public class CF1562C extends PrintWriter { CF1562C() { super(System.out); } public static Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF1562C o = new CF1562C(); o.main(); o.flush(); } static long calculate(long p, long q) { long mod = 1000000007, expo; expo = mod - 2; // Loop to find the value // until the expo is not zero while (expo != 0) { // Multiply p with q // if expo is odd if ((expo & 1) == 1) { p = (p * q) % mod; } q = (q * q) % mod; // Reduce the value of // expo by 2 expo >>= 1; } return p; } static String longestPalSubstr(String str) { // The result (length of LPS) int maxLength = 1; int start = 0; int len = str.length(); int low, high; // One by one consider every // character as center // point of even and length // palindromes for (int i = 1; i < len; ++i) { // Find the longest even // length palindrome with // center points as i-1 and i. low = i - 1; high = i; while (low >= 0 && high < len && str.charAt(low) == str.charAt(high)) { --low; ++high; } // Move back to the last possible valid palindrom substring // as that will anyway be the longest from above loop ++low; --high; if (str.charAt(low) == str.charAt(high) && high - low + 1 > maxLength) { start = low; maxLength = high - low + 1; } // Find the longest odd length // palindrome with center point as i low = i - 1; high = i + 1; while (low >= 0 && high < len && str.charAt(low) == str.charAt(high)) { --low; ++high; } // Move back to the last possible valid palindrom substring // as that will anyway be the longest from above loop ++low; --high; if (str.charAt(low) == str.charAt(high) && high - low + 1 > maxLength) { start = low; maxLength = high - low + 1; } } return str.substring(start, start + maxLength - 1); } long check(long a){ long ret=0; for(long k=2;(k*k*k)<=a;k++){ ret=ret+(a/(k*k*k)); } return ret; } /*public static int getFirstSetBitPos(int n) { return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1; } public static int bfsq(int n, int m, HashMap<Integer,ArrayList<Integer>>h,boolean v ){ v[n]=true; if(n==m) return 1; else { int a=h.get(n).get(0); int b=h.get(n).get(1); if(b>m) return(m-n); else { int a1=bfsq(a,m,h,v); int b1=bfsq(b,m,h,v); return 1+Math.min(a1,b1); } } }*/ static long nCr(int n, int r) { return fact(n) / (fact(r) * fact(n - r)); } // Returns factorial of n static long fact(long n) { long res = 1; for (long i = 2; i <= n; i++) res = res * i; return res; } /*void bfs(int src, HashMap<Integer,ArrayList<Integer,Integer>>h,int deg, boolean v[] ){ a[src]=deg; Queue<Integer>= new LinkedList<Integer>(); q.add(src); while(!q.isEmpty()){ (int a:h.get(src)){ if() } } }*/ /* void dfs(int root, int par, HashMap<Integer,ArrayList<Integer>>h,int dp[], int child[]) { dp[root]=0; child[root]=1; for(int x: h.get(root)){ if(x == par) continue; dfs(x,root,h,in,dp); child[root]+=child[x]; } ArrayList<Integer> mine= new ArrayList<Integer>(); for(int x: h.get(root)) { if(x == par) continue; mine.add(x); } if(mine.size() >=2){ int y= Math.max(child[mine.get(0)] - 1 + dp[mine.get(1)] , child[mine.get(1)] -1 + dp[mine.get(0)]); dp[root]=y;} else if(mine.size() == 1) dp[root]=child[mine.get(0)] - 1; } */ class Pair implements Comparable<Pair>{ int i; int j; Pair (int a, int b){ i = a; j = b; } public int compareTo(Pair A){ return (int)(this.i-A.i); }} /*static class Pair { int i; int j; Pair() { } Pair(int i, int j) { this.i = i; this.j = j; } }*/ /*ArrayList<Integer> check(int a[], int b){ int n=a.length; long ans=0;int k=0; ArrayList<Integer>ab= new ArrayList<Integer>(); for(int i=0;i<n;i++){ if(a[i]%m==0) {k=a[i]; while(a[i]%m==0){ a[i]=a[i]/m; } for(int z=0;z<k/a[i];z++){ ab.add(a[i]); } } else{ ab.add(a[i]); } } return ab; } */ /*int check[]; int tree[]; static void build( int []arr) { // insert leaf nodes in tree for (int i = 0; i < n; i++) tree[n + i] = arr[i]; // build the tree by calculating // parents for (int i = n - 1; i > 0; --i){ int ans= Math.min(tree[i << 1], tree[i << 1 | 1]); int ans1=Math.max((tree[i << 1], tree[i << 1 | 1])); if(ans==0) } }*/ /*static void ab(long n) { // Note that this loop runs till square root for (long i=1; i<=Math.sqrt(n); i++) { if(i==1) { p.add(n/i); continue; } if (n%i==0) { // If divisors are equal, print only one if (n/i == i) p.add(i); else // Otherwise print both { p.add(i); p.add(n/i); } } } }*/ void main() { //int g=sc.nextInt(); //int mod=1000000007; //for(int w=0;w<g;w++){ int n=sc.nextInt(); long a[]= new long[n-1]; for(int i=0;i<n-1;i++) a[i]=sc.nextLong(); long mn=a[0]; long mx=a[0]; long b[]= new long[n-1]; b[0]=a[0]; long ans[]= new long[n]; boolean check=true; boolean v[]= new boolean[n+1]; for(int i=1;i<n-1;i++){ b[i]=b[i-1]+a[i]; if(b[i]>mx) mx=b[i]; if(b[i]<mn) mn=b[i]; }int c=1; for(c=1;c<=n;c++){ if(c+mn>0&&c+mx<=n) break; } if(c>n){ println(-1); return;} else { v[c]=true; ans[0]=c; for(int i=0;i<n-1;i++){ if(v[(int)(c+b[i])]==true) { check=false; break; } else{ ans[i+1]=c+b[i]; v[(int)(c+b[i])]=true; }} if(!check) println(-1); else{ for(int i=0;i<n;i++) print(ans[i]+" "); println(""); } } } }
java
1290
A
A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains three space-separated integers nn, mm and kk (1≤m≤n≤35001≤m≤n≤3500, 0≤k≤n−10≤k≤n−1)  — the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4 6 4 2 2 9 2 3 8 5 4 4 1 2 13 60 4 4 1 3 1 2 2 1 2 2 0 1 2 OutputCopy8 4 1 1 NoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element. the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8]; the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8]; if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element); if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44.
[ "brute force", "data structures", "implementation" ]
//package mindcontrol; import java.util.*; import java.io.*; public class mindcontrol { 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()); int m = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); int controlled = Math.min(m - 1, k); int uncontrolled = m - 1 - controlled; int[] nums = new int[n]; st = new StringTokenizer(fin.readLine()); for(int i = 0; i < n; i++) { nums[i] = Integer.parseInt(st.nextToken()); } int ans = 0; int initL = controlled; int initR = n - 1; while(initL >= 0) { int curAns = Integer.MAX_VALUE; int l = initL + uncontrolled; int r = initR; while(l >= initL) { curAns = Math.min(Math.max(nums[l], nums[r]), curAns); l --; r --; } ans = Math.max(curAns, ans); initL --; initR --; } fout.append(ans).append("\n"); } System.out.print(fout); } }
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.text.DecimalFormat; import java.util.ArrayList; import java.util.Locale; import java.util.StringTokenizer; import java.util.stream.IntStream; public class Main { static { Locale.setDefault(Locale.ENGLISH); } private static DecimalFormat decimalFormat = new DecimalFormat("#0.00000000"); private static class Reader implements Closeable { private BufferedReader reader; private StringTokenizer tokenizer; public Reader() { reader = new BufferedReader(new InputStreamReader(System.in)); } public Reader(String fileName) { try { reader = new BufferedReader(new FileReader(fileName)); } catch (FileNotFoundException e) { throw new IllegalStateException("There is no file with given name"); } } public String nextToken() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { String nextLine = reader.readLine(); if (nextLine == null) { return null; } tokenizer = new StringTokenizer(nextLine); } catch (IOException e) { throw new IllegalStateException("I/O Error"); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } @Override public void close() throws IOException { reader.close(); } } private static class Pair implements Comparable<Pair> { private int x; private int y; public Pair(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } @Override public int compareTo(Pair o) { if (this.x != o.x) return Integer.compare(this.x, o.x); return Integer.compare(this.y, o.y); } } private <T> ArrayList<T> createArrayList(int n, T value) { ArrayList<T> result = new ArrayList<>(); IntStream.range(0, n).forEach(i -> result.add(value)); return result; } public static void main(String[] args) throws IOException { Reader reader = new Reader(); //Reader reader = new Reader("input.txt"); PrintWriter writer = new PrintWriter(System.out); new Main().solve(reader, writer); reader.close(); writer.close(); } private static class Cow { private int l; private int r; public Cow(int l, int r) { this.l = l; this.r = r; } public int getL() { return l; } public int getR() { return r; } } private void solve(Reader reader, PrintWriter writer) { int n = reader.nextInt(); int m = reader.nextInt(); ArrayList<Integer> s = new ArrayList<>(); for (int i = 0; i < n; ++i) { s.add(reader.nextInt()); } ArrayList<Cow>[] cowsByF = new ArrayList[5001]; for (int i = 1; i <= n; ++i) { cowsByF[i] = new ArrayList<>(); } boolean[] used = new boolean[5000]; for (int i = 0; i < m; ++i) { int f = reader.nextInt(); int h = reader.nextInt(); int l = -1; int r = -1; int counter = 0; for (int j = 0; j < n; ++j) { if (s.get(j) == f) { counter++; if (counter == h) { l = j; break; } } } counter = 0; for (int j = n - 1; j >= 0; --j) { if (s.get(j) == f) { counter++; if (counter == h) { r = j; break; } } } if (l != -1) { used[l] = true; cowsByF[f].add(new Cow(l, r)); } } int bestResult = 0; long bestCount = 0; for (int i = -1; i < n; ++i) { //граница разделения if (i > -1 && !used[i]) { continue; } int result = 0; long count = 1; boolean usedProperCow = false; for (int j = 1; j <= n; ++j) { //уровень сладости boolean usedProperCowAtJ = false; int l = 0; int r = 0; int mixed = 0; for (Cow cow : cowsByF[j]) { if (cow.l == i) { usedProperCow = true; usedProperCowAtJ = true; continue; } if (cow.l <= i && cow.r <= i) { l++; } if (cow.l > i && cow.r > i) { r++; } if (cow.l <= i && cow.r > i) { mixed++; } } if (usedProperCowAtJ) { if (r + mixed == 0) { result += 1; continue; } else { result += 2; int mult = (r + mixed) % 1000000007; count *= mult; continue; } } if (l + r + mixed == 0) { continue; } if (mixed + (l > 0 ? 1 : 0) + (r > 0 ? 1 : 0) > 1) { result += 2; int mult = (l * mixed + r * mixed + mixed * (mixed - 1)) % 1000000007; count *= mult; } else { result += 1; int mult = (l + r + mixed * 2) % 1000000007; count *= mult; } count %= 1000000007; } if (result > bestResult) { bestResult = result; bestCount = count; } else if (result == bestResult && (i == -1 || usedProperCow)) { bestCount += count; bestCount %= 1000000007; } } writer.println(bestResult + " " + bestCount); } }
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 ProblemB { static int ans = Integer.MAX_VALUE; static int n,m,x,y,d; public static void main(String[] args) throws Exception { Scanner in = new Scanner(); int test = in.readInt(); StringBuilder sb = new StringBuilder(); while(test-->0){ int a = in.readInt(); int b =in.readInt(); int c = in.readInt(); int ans = Integer.MAX_VALUE; int res[] = new int[3]; for(int i =1;i<=2*a;i++){ for(int j =i;j<=2*b;j+=i){ int t = (c/j)*j; int cur = Math.abs(a-i)+Math.abs(b-j)+Math.abs(c-t); if(ans>cur){ ans = cur; res[0] = i;res[1]=j;res[2]=t; } t+=j; cur = Math.abs(a-i)+Math.abs(b-j)+Math.abs(c-t); if(ans>cur){ ans = cur; res[0] = i;res[1]=j;res[2]=t; } } } sb.append(ans+"\n"); sb.append(res[0]+" "+res[1]+" "+res[2]+"\n"); } System.out.println(sb); } public static ArrayList<Integer> factors(int n){ ArrayList<Integer>l = new ArrayList<>(); for(int i = 1;i*i<=n;i++){ if(n%i == 0){ l.add(i); if(n/i != i)l.add(n/i); } } return l; } public static void build(int seg[],int ind,int l,int r,int a[]){ if(l == r){ seg[ind] = a[l]; return; } int mid = (l+r)/2; build(seg,(2*ind)+1,l,mid,a); build(seg,(2*ind)+2,mid+1,r,a); seg[ind] = Math.min(seg[(2*ind)+1],seg[(2*ind)+2]); } public static long gcd(long a, long b){ return b ==0 ?a:gcd(b,a%b); } public static long nearest(TreeSet<Long> list,long target){ long nearest = -1,sofar = Integer.MAX_VALUE; for(long it:list){ if(Math.abs(it - target)<sofar){ sofar = Math.abs(it - target); nearest = it; } } return nearest; } public static ArrayList<Long> factors(long n){ ArrayList<Long>l = new ArrayList<>(); for(long i = 1;i*i<=n;i++){ if(n%i == 0){ l.add(i); if(n/i != i)l.add(n/i); } } Collections.sort(l); return l; } public static void swap(int a[],int i, int j){ int t = a[i]; a[i] = a[j]; a[j] = t; } public static boolean isSorted(long a[]){ for(int i =0;i<a.length;i++){ if(i+1<a.length && a[i]>a[i+1])return false; } return true; } public static int first(ArrayList<Long>list,long target){ int index = -1; int l = 0,r = list.size()-1; while(l<=r){ int mid = (l+r)/2; if(list.get(mid) == target){ index = mid; r = mid-1; }else if(list.get(mid)>target){ r = mid-1; }else l = mid+1; } return index; } public static int last(ArrayList<Long>list,long target){ int index = -1; int l = 0,r = list.size()-1; while(l<=r){ int mid = (l+r)/2; if(list.get(mid) == target){ index= mid; l = mid+1; }else if(list.get(mid)<target){ l = mid+1; }else r = mid-1; } return index; } public static void sort(int arr[]){ ArrayList<Integer>list = new ArrayList<>(); for(int it:arr)list.add(it); Collections.sort(list); for(int i = 0;i<arr.length;i++)arr[i] = list.get(i); } static class Pair{ int x,y; public Pair(int x,int y){ this.x = x; this.y = y; } } static class Scanner{ BufferedReader br; StringTokenizer st; public Scanner(){ br = new BufferedReader(new InputStreamReader(System.in)); } public String read() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } public int readInt() { return Integer.parseInt(read()); } public long readLong() { return Long.parseLong(read()); } public double readDouble(){return Double.parseDouble(read());} public String readLine() throws Exception { return br.readLine(); } } }
java
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" ]
// package c1296; // // Codeforces Round #617 (Div. 3) 2020-02-04 06:35 // A. Array with Odd Sum // https://codeforces.com/contest/1296/problem/A // time limit per test 1 second; memory limit per test 256 megabytes // public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*' // // You are given an array a consisting of n integers. // // In one move, you can choose two indices 1 <= i, j <= n such that i != j and set a_i := a_j. 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 i and j // and replace a_i with a_j). // // Your task is to say if it is possible to obtain an array with an odd (not divisible by 2) sum of // elements. // // You have to answer t independent test cases. // // Input // // The first line of the input contains one integer t (1 <= t <= 2000) -- the number of test cases. // // The next 2t lines describe test cases. The first line of the test case contains one integer n (1 // <= n <= 2000) -- the number of elements in a. The second line of the test case contains n // integers a_1, a_2, ..., a_n (1 <= a_i <= 2000), where a_i is the i-th element of a. // // It is guaranteed that the sum of n over all test cases does not exceed 2000 (\sum n <= 2000). // // Output // // For 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. // // Example /* input: 5 2 2 3 4 2 2 8 8 3 3 3 3 4 5 5 5 5 4 1 1 1 1 output: YES NO YES NO NO */ // import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.lang.invoke.MethodHandles; import java.util.Random; import java.util.StringTokenizer; public class C1296A { static final int MOD = 998244353; static final Random RAND = new Random(); static boolean solve(int[] a) { int n = a.length; int[] ct = new int[2]; int sum = 0; for (int v : a) { ct[v%2]++; sum += v; } if (sum % 2 == 1) { return true; } if (ct[1] == 0 || ct[0] == 0) { return false; } return true; } static boolean test = false; static void doTest() { if (!test) { return; } long t0 = System.currentTimeMillis(); System.out.format("%d msec\n", System.currentTimeMillis() - t0); System.exit(0); } public static void main(String[] args) { doTest(); MyScanner in = new MyScanner(); int T = in.nextInt(); for (int t = 1; t <= T; t++) { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } boolean ans = solve(a); System.out.println(ans? "YES" : "NO"); } } static void output(int[] a) { if (a == null) { System.out.println("-1"); return; } StringBuilder sb = new StringBuilder(); for (int v : a) { sb.append(v); sb.append(' '); if (sb.length() > 4000) { System.out.print(sb.toString()); sb.setLength(0); } } System.out.println(sb.toString()); } static void myAssert(boolean cond) { if (!cond) { throw new RuntimeException("Unexpected"); } } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { try { final String USERDIR = System.getProperty("user.dir"); String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", ""); cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname; final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in"); br = new BufferedReader(new InputStreamReader(fin.exists() ? new FileInputStream(fin) : System.in)); } catch (Exception e) { br = new BufferedReader(new InputStreamReader(System.in)); } } public String next() { try { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
java
1296
F
F. Berland Beautytime limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThere are nn railway stations in Berland. They are connected to each other by n−1n−1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.You have a map of that network, so for each railway section you know which stations it connects.Each of the n−1n−1 sections has some integer value of the scenery beauty. However, these values are not marked on the map and you don't know them. All these values are from 11 to 106106 inclusive.You asked mm passengers some questions: the jj-th one told you three values: his departure station ajaj; his arrival station bjbj; minimum scenery beauty along the path from ajaj to bjbj (the train is moving along the shortest path from ajaj to bjbj). You are planning to update the map and set some value fifi on each railway section — the scenery beauty. The passengers' answers should be consistent with these values.Print any valid set of values f1,f2,…,fn−1f1,f2,…,fn−1, which the passengers' answer is consistent with or report that it doesn't exist.InputThe first line contains a single integer nn (2≤n≤50002≤n≤5000) — the number of railway stations in Berland.The next n−1n−1 lines contain descriptions of the railway sections: the ii-th section description is two integers xixi and yiyi (1≤xi,yi≤n,xi≠yi1≤xi,yi≤n,xi≠yi), where xixi and yiyi are the indices of the stations which are connected by the ii-th railway section. All the railway sections are bidirected. Each station can be reached from any other station by the railway.The next line contains a single integer mm (1≤m≤50001≤m≤5000) — the number of passengers which were asked questions. Then mm lines follow, the jj-th line contains three integers ajaj, bjbj and gjgj (1≤aj,bj≤n1≤aj,bj≤n; aj≠bjaj≠bj; 1≤gj≤1061≤gj≤106) — the departure station, the arrival station and the minimum scenery beauty along his path.OutputIf there is no answer then print a single integer -1.Otherwise, print n−1n−1 integers f1,f2,…,fn−1f1,f2,…,fn−1 (1≤fi≤1061≤fi≤106), where fifi is some valid scenery beauty along the ii-th railway section.If there are multiple answers, you can print any of them.ExamplesInputCopy4 1 2 3 2 3 4 2 1 2 5 1 3 3 OutputCopy5 3 5 InputCopy6 1 2 1 6 3 1 1 5 4 1 4 6 1 3 3 4 1 6 5 2 1 2 5 OutputCopy5 3 1 2 1 InputCopy6 1 2 1 6 3 1 1 5 4 1 4 6 1 1 3 4 3 6 5 3 1 2 4 OutputCopy-1
[ "constructive algorithms", "dfs and similar", "greedy", "sortings", "trees" ]
import java.io.*; import java.util.*; public class Sol{ public static List<Integer> adj[]; public static int query[][]; public static int get[][] = new int[5000][5000]; public static int edge[]; public static int par[]; public static int depth[]; public static int n, m, D; public static void main(String[] args) throws IOException{ FastIO sc = new FastIO(System.in); PrintWriter out = new PrintWriter(System.out); boolean poss = true; n = sc.nextInt(); par = new int[n]; depth = new int[n]; edge = new int[n-1]; adj = new ArrayList[n]; for(int i=0; i<n; ++i) { adj[i] = new ArrayList<>(); } int idx = 0; for(int i=0; i<n-1; ++i) { int a = sc.nextInt()-1; int b = sc.nextInt()-1; adj[a].add(b); adj[b].add(a); get[a][b] = idx; get[b][a] = idx; idx++; edge[i] = -1; } depth[0] = 0; par[0] = 0; DFS(0, 0); int m = sc.nextInt(); query = new int[m][3]; for(int i=0; i<m; ++i) { query[i][0] =sc.nextInt()-1; query[i][1] = sc.nextInt()-1; query[i][2] = sc.nextInt(); } ColumnSort(query, 2); for(int i=m-1; i>=0; --i) { boolean change = false; int num = query[i][2]; int curr1 = query[i][0]; int curr2 = query[i][1]; while(curr1!=curr2) { if(depth[curr1]>depth[curr2]) { idx = get[curr1][par[curr1]]; if(edge[idx]==-1||edge[idx]==num) { edge[idx] = num; change = true; } curr1 = par[curr1]; }else { idx = get[curr2][par[curr2]]; if(edge[idx]==-1||edge[idx]==num) { edge[idx] = num; change = true; } curr2 = par[curr2]; } } if(!change) poss = false; } if(!poss) { out.println(-1); }else { for(int i=0; i<n-1; ++i) { out.print(Math.max(edge[i], 1) + " "); } out.println(); } out.close(); } public static void DFS(int curr, int p) { for(int i: adj[curr]) { if(i==p) continue; par[i] = curr; depth[i] = depth[curr]+1; DFS(i, curr); } } public static void ColumnSort(int arr[][], int col) { Arrays.sort(arr, new Comparator<int[]>() { @Override public int compare(int[] entry1, int[] entry2) { Integer a = entry1[col]; Integer b = entry2[col]; return a.compareTo(b); } }); } static class FastIO { // Is your Fast I/O being bad? InputStream dis; byte[] buffer = new byte[1 << 17]; int pointer = 0; public FastIO(String fileName) throws IOException { dis = new FileInputStream(fileName); } public FastIO(InputStream is) throws IOException { dis = is; } int nextInt() throws IOException { int ret = 0; byte b; do { b = nextByte(); } while (b <= ' '); boolean negative = false; if (b == '-') { negative = true; b = nextByte(); } while (b >= '0' && b <= '9') { ret = 10 * ret + b - '0'; b = nextByte(); } return (negative) ? -ret : ret; } long nextLong() throws IOException { long ret = 0; byte b; do { b = nextByte(); } while (b <= ' '); boolean negative = false; if (b == '-') { negative = true; b = nextByte(); } while (b >= '0' && b <= '9') { ret = 10 * ret + b - '0'; b = nextByte(); } return (negative) ? -ret : ret; } byte nextByte() throws IOException { if (pointer == buffer.length) { dis.read(buffer, 0, buffer.length); pointer = 0; } return buffer[pointer++]; } String next() throws IOException { StringBuffer ret = new StringBuffer(); byte b; do { b = nextByte(); } while (b <= ' '); while (b > ' ') { ret.appendCodePoint(b); b = nextByte(); } return ret.toString(); } } }
java
1141
B
B. Maximal Continuous Resttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputEach day in Berland consists of nn hours. Polycarp likes time management. That's why he has a fixed schedule for each day — it is a sequence a1,a2,…,ana1,a2,…,an (each aiai is either 00 or 11), where ai=0ai=0 if Polycarp works during the ii-th hour of the day and ai=1ai=1 if Polycarp rests during the ii-th hour of the day.Days go one after another endlessly and Polycarp uses the same schedule for each day.What is the maximal number of continuous hours during which Polycarp rests? It is guaranteed that there is at least one working hour in a day.InputThe first line contains nn (1≤n≤2⋅1051≤n≤2⋅105) — number of hours per day.The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where ai=0ai=0 if the ii-th hour in a day is working and ai=1ai=1 if the ii-th hour is resting. It is guaranteed that ai=0ai=0 for at least one ii.OutputPrint the maximal number of continuous hours during which Polycarp rests. Remember that you should consider that days go one after another endlessly and Polycarp uses the same schedule for each day.ExamplesInputCopy5 1 0 1 0 1 OutputCopy2 InputCopy6 0 1 0 1 1 0 OutputCopy2 InputCopy7 1 0 1 1 1 0 1 OutputCopy3 InputCopy3 0 0 0 OutputCopy0 NoteIn the first example; the maximal rest starts in last hour and goes to the first hour of the next day.In the second example; Polycarp has maximal rest from the 44-th to the 55-th hour.In the third example, Polycarp has maximal rest from the 33-rd to the 55-th hour.In the fourth example, Polycarp has no rest at all.
[ "implementation" ]
import java.io.*; import java.util.*; public class codeforces { public static void main(String[] args) { Scanner scn= new Scanner(System.in); int n= scn.nextInt(); int [] arr= new int [n]; for(int i=0; i<n; i++){ arr[i]=scn.nextInt(); } int count=0; int max=0; for(int j=0; j<2; j++){ for(int i=0; i<n; i++){ if(arr[i]==1){ count++; } else{ max= Math.max(max, count); count=0; if(j==1){ System.out.println(max); return; } } } } } }
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 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_Motarack_s_Birthday { 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(); int arr[] = f.nextArray(n); int max = Integer.MIN_VALUE; int min = Integer.MAX_VALUE; for(int i = 0; i < n; i++) { if(arr[i] == -1) { if(i-1 >= 0 && arr[i-1] != -1) { max = max(max, arr[i-1]); min = min(min, arr[i-1]); } if(i+1 < n && arr[i+1] != -1) { max = max(max, arr[i+1]); min = min(min, arr[i+1]); } } } int k = (max+min)/2; for(int i = 0; i < n; i++) { if(arr[i] == -1) { arr[i] = k; } } int m = 0; for(int i = 1; i < n; i++) { m = max(m, abs(arr[i]-arr[i-1])); } out.println(m + " " + k); } // 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
1311
A
A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.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. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5 2 3 10 10 2 4 7 4 9 3 OutputCopy1 0 2 2 1 NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66.
[ "greedy", "implementation", "math" ]
import java.util.Scanner; public class AddOddOrSubtractEven { public static void main(String[] args) { Scanner input = new Scanner(System.in); int testCases = input.nextInt(); for (int i = 0; i < testCases; i++) { int startNum = input.nextInt(); int desiredNum = input.nextInt(); if (desiredNum == startNum) System.out.println("0"); else if (desiredNum > startNum) { if ((desiredNum-startNum)%2 == 1) { System.out.println("1"); } else { System.out.println("2");; } } else { if ((startNum-desiredNum)%2 == 0) { System.out.println("1");; } else { System.out.println("2"); } } } } }
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" ]
//package USACO; import java.util.*; import java.io.*; public class kuroniAndImpossibleCalculation { public static void main(String[]args){ Kattio io = new Kattio(); int n = io.nextInt(); int m = io.nextInt(); int[]arr = new int[m]; for(int i = 0; i < m; i++) { arr[i] = -1; } boolean zero = false; for(int i = 0; i < n; i++) { int s = io.nextInt(); if(arr[s % m ] != -1) { zero = true; } arr[s % m] = s; //io.println(s); } if(zero == true) { io.println("0"); } else { ArrayList<Integer>arr2 = new ArrayList<Integer>(); for(int i = 0; i < m; i++) { if(arr[i] != -1) { arr2.add(arr[i]); } } long ans = 1L; for(int i = 0; i < arr2.size(); i++) { for(int j = i+1; j < arr2.size(); j++) { //io.println(arr2.get(i) + " " + arr2.get(j)); ans = (ans * Math.abs(arr2.get(i)- arr2.get(j))) % m; } } io.println(ans); } io.close(); } static class Kattio extends PrintWriter { private BufferedReader r; private StringTokenizer st; // standard input public Kattio() { this(System.in, System.out); } public Kattio(InputStream i, OutputStream o) { super(o); r = new BufferedReader(new InputStreamReader(i)); } // USACO-style file input public Kattio(String problemName) throws IOException { super(problemName + ".out"); r = new BufferedReader(new FileReader(problemName + ".in")); } // returns null if no more input public String next() { try { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(r.readLine()); return st.nextToken(); } catch (Exception e) { } return null; } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } } }
java
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.Scanner; /* */ public class C2 { static int happyCount=0; static long[] facts; static long m; public static void main(String[] args) { Scanner fs=new Scanner(System.in); int n=fs.nextInt(); m=fs.nextLong(); precomp(); long total=0; for (int i=1; i<=n; i++) { int things=n-i+1; long orderings=facts[i]; long otherOrderings=facts[n-i]; int waysToPlace=(n-i+1); total+=things*orderings%m*waysToPlace%m*otherOrderings%m; total%=m; } System.out.println(total); } static void precomp() { facts=new long[1_000_001]; facts[0]=1; for (int i=1; i<facts.length; i++) facts[i]=facts[i-1]*i%m; } static void allPerms(int[] cur, boolean[] used, int index) { int n=cur.length; if (index==n) { for (int i=0; i<n; i++) { int min=cur[i], max=cur[i]; for (int j=i; j<n; j++) { min=Math.min(cur[j], min); max=Math.max(cur[j], max); if (max-min == j-i) { happyCount++; } } } return; } for (int toPlace=0; toPlace<n; toPlace++) { if (used[toPlace]) continue; cur[index]=toPlace; used[toPlace]=true; allPerms(cur, used, index+1); used[toPlace]=false; } } }
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.util.*; import java.io.*; import java.math.*; /* Hepler Class Methods **only Few Imp Ones** * int[][] getIntMatrix(String s,int r,int c) //Works only for int and long * char getCharacterValue(int i) * int getIntegerValueOfCharacter(char c) * boolean isPerfectSquare(int n) // works only for int and long * int getLargestPrimeFactor(int n) //works only for int and long * boolean isPrime(int n) //works only for int and long * void printArray(int a[]), //works for all * void printMatrix(int a[][]), //works for all * void printNestedList(ArrayList<ArrayList<Integer>> a) //works for all * boolean isPalindrome //works for all except Character * T swap(T) //works only for int[],long[] and String * T getArraySum(T[]) //works only for int[],long[],double[] * T reverse(T) //works only for String,int and long * T[] getReverseArray(T[]) //works for all * HashSet<T> getHashSet(T[]) //works for int[],long[],char[],String[] * T setBit(T,k,side) //works only when n = int or long and k is always int **returns int or long** * String setBitString(T,k,side) //works only when n = int or long and k is always int **returns String** * int getSetBits(long n) //Gives Number of sets bits in a number * String cvtToBinary(T) * int cvtToDecimal(String n) //Always returns Long * boolean isPowerOf2(T) * boolean isSafe(T [][], row,col) //Returns whether current row and col are under bounds * T Log2(T num) //Returns (Math.log(num) / Math.log(2)) * long nCr(long n,long r) // Returns nCr value * long nCrMod(long n,long r) // Returns nCr % MOD value * */ public class A { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); static Helper sc = new Helper(br); static int MOD = 1000000007,INF = Integer.MAX_VALUE,NEG_INF = Integer.MIN_VALUE,SEM_INF = INF / 2; //BigInteger B = new BigInteger("1"); //Scanner scanner = new Scanner(System.in); public static void main(String args[]) { try { int t = sc.getInt(br.readLine()); while (t-- > 0) { testCase(); } out.flush(); }catch (Exception e){ System.out.println("Exception Occured: " + e.getMessage()); e.printStackTrace(); } } private static void testCase() throws Exception { long bagSize = sc.nextLong();int n = sc.nextInt(); long a[] = sc.getLongArray(br.readLine()); int count[] = new int[65]; Arrays.parallelSort(a,0,n); sc.getReverseArray(a); long sum = 0; for(int x = 0;x < n;x++) { long num = a[x]; for(int i = 0;i < 32;i++) { if(((num >> i) & 1) == 1) { count[i]++; break; } } sum += a[x]; } if(sum < bagSize) { writeln(-1); return; } int ans = 0; for(int x = 0;x < 60;) { if(((bagSize >> x) & 1) == 1) { if(count[x] > 0) { count[x]--; }else { while(x < 60 && count[x] == 0) { ans++; x++; } count[x] -=1; continue; } } count[x + 1] += count[x] / 2; x++; } writeln(ans); } public static void writeln() throws Exception { out.write("\n"); } public static void write(Object o) throws Exception { out.write(String.valueOf(o)); } public static void writeln(Object o) throws Exception { out.write(String.valueOf(o) + "\n"); } public static void println() { System.out.println(); } public static void print(Object o) { System.out.print(String.valueOf(o)); } public static void println(Object o) { System.out.println(String.valueOf(o)); } static class Helper { FastReader fr; /*Constructor*/ public Helper(BufferedReader br) { try{ fr = new FastReader(br); }catch (Exception e){ System.out.println("Exception Occured: " + e.getMessage()); e.printStackTrace(); } } /* Inputs*/ public String next() throws Exception { return fr.next(); } public int nextInt() throws Exception { return fr.nextInt(); } public long nextLong() throws Exception { return fr.nextLong(); } public String trimLine() throws Exception { return fr.trimLine(); } public String rawLine() throws Exception { return fr.nextLine(); } public double nextDouble() throws Exception { return fr.nextDouble(); } public float nextFloat() throws Exception { return fr.nextFloat(); } public int [] getIntArray( String s) throws Exception { String input[] = s.split(" "); int res[] = new int[input.length]; for(int x = 0;x < res.length;x++) res[x] = getInt(input[x]); return res; } public long [] getLongArray( String s) throws Exception { String input[] = s.split(" "); long res[] = new long[input.length]; for(int x = 0;x < res.length;x++) res[x] = getLong(input[x]); return res; } public double [] getDoubleArray( String s) throws Exception { String input[] = s.split(" "); double res[] = new double[input.length]; for(int x = 0;x < res.length;x++) res[x] = getDouble(input[x]); return res; } public int[][] getIntMatrix(String s,int r,int c) { int i = 0;int mat[][] = new int[r][c]; String st[] = s.split(" "); for(int x = 0;x < r;x++) for(int y =0 ;y < c;y++) mat[x][y] = Integer.parseInt(st[i++]); return mat; } public long[][] getlongMatrix(String s,int r,int c) { int i = 0;long mat[][] = new long[r][c]; String st[] = s.split(" "); for(int x = 0;x < r;x++) for(int y =0 ;y < c;y++) mat[x][y] = Long.parseLong(st[i++]); return mat; } public int getInt(String s) { return Integer.parseInt(s); } public long getLong(String s) { return Long.parseLong(s); } public float getFloat(String s) { return Float.parseFloat(s); } public double getDouble(String s) { return Double.parseDouble(s); } /*Some basic hepler methods*/ public char getCharacterValue(int i) { return (char)i; } public int getIntegerValueOfCharacter(char c) { return (int)c; } public int Log2(int num) { return (int)(Math.log(num) / Math.log(2)); } public long Log2(long num) { return (long) (Math.log(num) / Math.log(2)); } public double Log2(double num) { return (double) (Math.log(num) / Math.log(2)); } public long nCr(long n,long r) { if(r > n - r) r = n - r; long res = 1; for(long x = 0;x < r;x++) { res *= (n - x); res /= (x + 1); } return res; } public long nCrMod(long n,long r,long md) { if(r > n - r) r = n - r; long res = 1; for(long x = 0;x < r;x++) { res = (res * (n - x)) % md; res /= (x + 1); } return res % md; } public int getGCD(int a,int b) { if(b == 0) return a; return getGCD(b,a % b); } public long getGCD(long a,long b) { if(b == 0) return a; return getGCD(b,a % b); } public double getGCD(double a,double b) { if(b == 0) return a; return getGCD(b,a % b); } public float getGCD(float a,float b) { if(b == 0) return a; return getGCD(b,a % b); } public int getLCM(int a,int b) { return ((a * b) / getGCD(a,b)); } public long getLCM(long a,long b) { return ((a * b) / getGCD(a,b)); } public double getLCM(double a,double b) { return ((a * b) / getGCD(a,b)); } public float getLCM(float a,float b) { return ((a * b) / getGCD(a,b)); } public boolean isSafe(int a[][],int x,int y) { if(x >=0 && y >= 0 && x < a.length && y < a[0].length) return true; return false; } public boolean isSafe(long a[][],int x,int y) { if(x >=0 && y >= 0 && x < a.length && y < a[0].length) return true; return false; } public boolean isSafe(double a[][],int x,int y) { if(x >=0 && y >= 0 && x < a.length && y < a[0].length) return true; return false; } public boolean isSafe(char a[][],int x,int y) { if(x >=0 && y >= 0 && x < a.length && y < a[0].length) return true; return false; } public boolean isPerfectSquare(int n) { if(n == 0 || n == 1) return true; if(n == 2 || n == 3) return false; double d = Math.sqrt(n); return (d - Math.floor(d) == 0); } public boolean isPerfectSquare(long n) { if(n == 0 || n == 1) return true; if(n == 2 || n == 3) return false; double d = Math.sqrt(n); return (d - Math.floor(d) == 0); } public boolean isPowerOf2(long n) { return n != 0 && (n & (n - 1)) == 0; } public long fastPow(long n,long p) { long res = 1; while(p > 0){ if(p % 2 != 0) res = res * n; p = p / 2; n = n * n; } return res; } public long modPow(long n,long p,long md) { long res = 1; n = n % md; if(n == 0) return 0; while(p > 0){ if(p % 2 != 0) res = ((res % md) * (n % md)) % md; p = p / 2; n = ((n % md) * (n % md)) % md; } return (res % md); } public boolean isPalindrome(int n) { StringBuilder sb = new StringBuilder(n + ""); return (Integer.parseInt(sb.reverse().toString()) == n); } public boolean isPalindrome(long n) { StringBuilder sb = new StringBuilder(n + ""); return (Long.parseLong(sb.reverse().toString()) == n); } public boolean isPalindrome(String s) { StringBuilder sb = new StringBuilder(s + ""); return (sb.reverse().toString().equals(s)); } public int getSmallestPrimeFactor(int n) { if(n == 1 || n == 0) return n; if(n % 2 == 0) return 2; else if(n % 3 == 0) return 3; int pf = -1; for(int x = 3;x <= Math.sqrt(n);x += 2) if(n % x == 0) return x; return n; } public int getLargestPrimeFactor(int n) { int pf = -1; if(n == 1 || n == 2 || n == 3 || n == 0) return n; while(n % 2 == 0){ pf = 2; n /= 2; } for(int x = 3;x <= Math.sqrt(n);x += 2) while (n % x == 0){ pf = x; n /= x; } if(n > 2) pf = n; return pf; } public long getSmallestPrimeFactor(long n) { if(n == 1 || n == 0) return n; if(n % 2 == 0) return 2; else if(n % 3 == 0) return 3; for(long x = 3;x <= Math.sqrt(n);x += 2) if(n % x == 0) return x; return n; } public long getLargestPrimeFactor(long n) { long pf = -1; if(n == 1 || n == 2 || n == 3 || n == 0) return n; while(n % 2 == 0){ pf = 2; n /= 2; } for(long x = 3;x <= Math.sqrt(n);x += 2) while (n % x == 0){ pf = x; n /= x; } if(n > 2) pf = n; return pf; } public boolean isPrime(int n) { if(n == 0 || n == 1) return false; if(getLargestPrimeFactor(n) == n) return true; return false; } public boolean isPrime(long n) { if(n == 0 || n == 1) return false; if(getLargestPrimeFactor(n) == n) return true; return false; } public int getSetBits(long n) { int count = 0; while (n > 0){ count += n % 2; n /= 2; } return count; } public int setBit(int n,int k,String side) throws Exception { if(side.equalsIgnoreCase("r") || side.equalsIgnoreCase("right")){ return ((1 << k) | n); }else if(side.equalsIgnoreCase("l") || side.equalsIgnoreCase("left")){ return (int)cvtToDecimal(setBitString(n,k,"l")); }else throw new Exception("Unknown Side of shift! side must be l,left,r,right"); } public long setBit(long n,int k,String side) throws Exception { if(side.equalsIgnoreCase("r") || side.equalsIgnoreCase("right")){ return ((1 << k) | n); }else if(side.equalsIgnoreCase("l") || side.equalsIgnoreCase("left")){ return cvtToDecimal(setBitString(n,k,"l")); }else throw new Exception("Unknown Side of shift! side must be l,left,r,right"); } public String setBitString(int n,int k,String side) throws Exception { StringBuilder sb = new StringBuilder(cvtToBinary(n) + ""); if(side.equalsIgnoreCase("r") || side.equalsIgnoreCase("right")){ sb.setCharAt(sb.length() - 1 - k,'1'); }else if(side.equalsIgnoreCase("l") || side.equalsIgnoreCase("left")){ sb.setCharAt(k,'1'); }else throw new Exception("Unknown Side of shift! side must be l,left,r,right"); return sb.toString(); } public String setBitString(long n, int k,String side) throws Exception { StringBuilder sb = new StringBuilder(cvtToBinary(n) + ""); if(side.equalsIgnoreCase("r") || side.equalsIgnoreCase("right")){ sb.setCharAt(sb.length() - 1 - k,'1'); }else if(side.equalsIgnoreCase("l") || side.equalsIgnoreCase("left")){ sb.setCharAt(k,'1'); }else throw new Exception("Unknown Side of shift! side must be l,left,r,right"); return sb.toString(); } public long cvtToDecimal(String n) { String num = n; long dec_value = 0; // Initializing base value to 1, // i.e 2^0 long base = 1; int len = num.length(); for (int i = len - 1; i >= 0; i--) { if (num.charAt(i) == '1') dec_value += base; base = base * 2; } return dec_value; } public String cvtToBinary(int n) { if(n == 0 || n == 1) return "" + n; StringBuilder sb = new StringBuilder(); while (n > 1){ if(n % 2 == 0) sb.append(0); else sb.append(1); n /= 2; } if(n == 1) sb.append(1); return sb.reverse().toString(); } public String cvtToBinary(long n) { if(n == 0 || n == 1) return "" + n; StringBuilder sb = new StringBuilder(); while (n > 1){ if(n % 2 == 0) sb.append(0); else sb.append(1); n /= 2; } if(n == 1) sb.append(1); return sb.reverse().toString(); } /*Printing Arena*/ public void print(BufferedWriter out,Object s) throws Exception { out.write(String.valueOf(s)); } public void println(BufferedWriter out,Object s) throws Exception { out.write(String.valueOf(s)); } public void printArray(int a[],int s,int e,boolean nextLine) { if(e >= a.length || s < 0) throw new ArrayIndexOutOfBoundsException("Array Index Out Of Bounds " + "[" + s + ", " + e + "] Array Size: " + a.length); for(int x = s;x <= e;x++) System.out.print(String.valueOf(a[x]) + " "); if(nextLine) System.out.println(); } public void printArray(long a[],int s,int e,boolean nextLine) { if(e >= a.length || s < 0) throw new ArrayIndexOutOfBoundsException("Array Index Out Of Bounds " + "[" + s + ", " + e + "] Array Size: " + a.length); for(int x = s;x <= e;x++) System.out.print(String.valueOf(a[x]) + " "); if(nextLine) System.out.println(); } public void printArray(char a[],int s,int e,boolean nextLine) { if(e >= a.length || s < 0) throw new ArrayIndexOutOfBoundsException("Array Index Out Of Bounds " + "[" + s + ", " + e + "] Array Size: " + a.length); for(int x = s;x <= e;x++) System.out.print(String.valueOf(a[x]) + " "); if(nextLine) System.out.println(); } public void printArray(double a[],int s,int e,boolean nextLine) { if(e >= a.length || s < 0) throw new ArrayIndexOutOfBoundsException("Array Index Out Of Bounds " + "[" + s + ", " + e + "] Array Size: " + a.length); for(int x = s;x <= e;x++) System.out.print(String.valueOf(a[x]) + " "); if(nextLine) System.out.println(); } public void printArray(String a[],int s,int e,boolean nextLine) { if(e >= a.length || s < 0) throw new ArrayIndexOutOfBoundsException("Array Index Out Of Bounds " + "[" + s + ", " + e + "] Array Size: " + a.length); for(int x = s;x <= e;x++) System.out.print(String.valueOf(a[x]) + " "); if(nextLine) System.out.println(); } public void printArray(Object a[],int s,int e,boolean nextLine) { if(e >= a.length || s < 0) throw new ArrayIndexOutOfBoundsException("Array Index Out Of Bounds " + "[" + s + ", " + e + "] Array Size: " + a.length); for(int x = s;x <= e;x++) System.out.print(a[x].toString() + " "); if(nextLine) System.out.println(); } public void printMatrix(int a[][]) { for(int x = 0;x < a.length;x++){ for (int y = 0;y < a[0].length;y++) System.out.print(a[x][y] + " "); System.out.println(); } } public void printMatrix(long a[][]) { for(int x = 0;x < a.length;x++){ for (int y = 0;y < a[0].length;y++) System.out.print(String.valueOf(a[x][y]) + " "); System.out.println(); } } public void printMatrix(char a[][]) { for(int x = 0;x < a.length;x++){ for (int y = 0;y < a[0].length;y++) System.out.print(String.valueOf(a[x][y]) + " "); System.out.println(); } } public void printMatrix(double a[][]) { for(int x = 0;x < a.length;x++){ for (int y = 0;y < a[0].length;y++) System.out.print(String.valueOf(a[x][y]) + " "); System.out.println(); } } public void printMatrix(String a[][]) { for(int x = 0;x < a.length;x++){ for (int y = 0;y < a[0].length;y++) System.out.print(String.valueOf(a[x][y]) + " "); System.out.println(); } } public void printMatrix(Object a[][]) { for(int x = 0;x < a.length;x++){ for (int y = 0;y < a[0].length;y++) System.out.print(a[x][y].toString() + " "); System.out.println(); } } public void printIntNestedList(ArrayList<ArrayList<Integer>> a) { for(int x = 0;x < a.size();x++){ ArrayList<Integer> al = a.get(x); for(int y = 0;y < al.size();y++) System.out.print(String.valueOf(al.get(y)) + " "); System.out.println(); } } public void printLongNestedList(ArrayList<ArrayList<Long>> a) { for(int x = 0;x < a.size();x++){ ArrayList<Long> al = a.get(x); for(int y = 0;y < al.size();y++) System.out.print(String.valueOf(al.get(y)) + " "); System.out.println(); } } public void printCharNestedList(ArrayList<ArrayList<Character>> a) { for(int x = 0;x < a.size();x++){ ArrayList<Character> al = a.get(x); for(int y = 0;y < al.size();y++) System.out.print(String.valueOf(al.get(y)) + " "); System.out.println(); } } public void printStringNestedList(ArrayList<ArrayList<String>> a) { for(int x = 0;x < a.size();x++){ ArrayList<String> al = a.get(x); for(int y = 0;y < al.size();y++) System.out.print(String.valueOf(al.get(y)) + " "); System.out.println(); } } public String swap(String st,int i,int j) { StringBuilder sb = new StringBuilder(st); sb.setCharAt(i,st.charAt(j)); sb.setCharAt(j,st.charAt(i)); return sb.toString(); } public int [] swap(int a[],int i,int j) { int t = a[i]; a[i] = a[j]; a[j] = t; return a; } public long[] swap(long a[],int i,int j) { long t = a[i]; a[i] = a[j]; a[j] = t; return a; } public long getArraySum(int a[],int s,int e) { long sum = 0; if(e >= a.length || s < 0) throw new ArrayIndexOutOfBoundsException("Array Index Out Of Bounds " + "[" + e + ", " + s + "]"); for(int x = s;x <= e;x++) sum += a[x]; return sum; } public long getArraySum(long a[],int s,int e) { long sum = 0; if(e >= a.length || s < 0) throw new ArrayIndexOutOfBoundsException("Array Index Out Of Bounds " + "[" + e + ", " + s + "]"); for(int x = s;x <= e;x++) sum += a[x]; return sum; } public double getArraySum(double a[],int s,int e) { double sum = 0; if(e >= a.length || s < 0) throw new ArrayIndexOutOfBoundsException("Array Index Out Of Bounds " + "[" + e + ", " + s + "]"); for(int x = s;x <= e;x++) sum += a[x]; return sum; } public int reverse(int n) { StringBuilder sb = new StringBuilder(n + ""); return Integer.parseInt(sb.reverse().toString()); } public long reverse(long n) { StringBuilder sb = new StringBuilder(n + ""); return Long.parseLong(sb.reverse().toString()); } public String reverse(String s) { StringBuilder sb = new StringBuilder(s + ""); return sb.reverse().toString(); } public Object[] getReverseArray(Object a[]) { int i = 0,j = a.length - 1; while (i <= j) { Object o = a[i]; a[i] = a[j]; a[j] = o; i++;j--; } return a; } public int[] getReverseArray(int a[]) { int i = 0,j = a.length - 1; while (i <= j) { int o = a[i]; a[i] = a[j]; a[j] = o; i++;j--; } return a; } public double[] getReverseArray(double a[]) { int i = 0,j = a.length - 1; while (i <= j) { double o = a[i]; a[i] = a[j]; a[j] = o; i++;j--; } return a; } public char[] getReverseArray(char a[]) { int i = 0,j = a.length - 1; while (i <= j) { char o = a[i]; a[i] = a[j]; a[j] = o; i++;j--; } return a; } public long[] getReverseArray(long a[]) { int i = 0,j = a.length - 1; while (i <= j) { long o = a[i]; a[i] = a[j]; a[j] = o; i++;j--; } return a; } public String[] getReverseArray(String a[]) { int i = 0,j = a.length - 1; while (i <= j) { String o = a[i]; a[i] = a[j]; a[j] = o; i++;j--; } return a; } public HashSet<Integer> getHashSet(int a[]) { HashSet<Integer> set = new HashSet<>(); for(int x = 0;x < a.length;x++) set.add(a[x]); return set; } public HashSet<Long> getHashSet(long a[]) { HashSet<Long> set = new HashSet<>(); for(int x = 0;x < a.length;x++) set.add(a[x]); return set; } public HashSet<Character> getHashSet(char a[]) { HashSet<Character> set = new HashSet<>(); for(int x = 0;x < a.length;x++) set.add(a[x]); return set; } public HashSet<String> getHashSet(String a[]) { HashSet<String> set = new HashSet<>(); for(int x = 0;x < a.length;x++) set.add(a[x]); return set; } public int getMax(int a[]) { int max = Integer.MIN_VALUE; for(int x = 0;x < a.length;x++) max = Math.max(max,a[x]); return max; } public long getMax(long a[]) { long max = Long.MIN_VALUE; for(int x = 0;x < a.length;x++) max = Math.max(max,a[x]); return max; } public double getMax(double a[]) { double max = Double.MIN_VALUE; for(int x = 0;x < a.length;x++) max = Math.max(max,a[x]); return max; } public int getMin(int a[]) { int min = Integer.MAX_VALUE; for(int x = 0;x < a.length;x++) min = Math.min(min,a[x]); return min; } public long getMin(long a[]) { long min = Long.MAX_VALUE; for(int x = 0;x < a.length;x++) min = Math.min(min,a[x]); return min; } public double getMin(double a[]) { double min = Double.MAX_VALUE; for(int x = 0;x < a.length;x++) min = Math.min(min,a[x]); return min; } private class FastReader { BufferedReader br; StringTokenizer st; public FastReader(BufferedReader br) throws Exception { this.br = br; } public String next() throws Exception { if(st == null || !st.hasMoreElements()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(next()); } public long nextLong() throws Exception { return Long.parseLong(next()); } public String trimLine() throws Exception { try{ return br.readLine().trim(); }catch (Exception e){ System.out.println("Exception Occured: " + e.getMessage()); e.printStackTrace(); return null; } } public String nextLine() throws Exception { try{ return br.readLine(); }catch (Exception e){ System.out.println("Exception Occured: " + e.getMessage()); e.printStackTrace(); return null; } } public double nextDouble() throws Exception { return Double.parseDouble(next()); } public float nextFloat() throws Exception { return Float.parseFloat(next()); } } } }
java
1316
B
B. String Modificationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputVasya has a string ss of length nn. He decides to make the following modification to the string: Pick an integer kk, (1≤k≤n1≤k≤n). For ii from 11 to n−k+1n−k+1, reverse the substring s[i:i+k−1]s[i:i+k−1] of ss. For example, if string ss is qwer and k=2k=2, below is the series of transformations the string goes through: qwer (original string) wqer (after reversing the first substring of length 22) weqr (after reversing the second substring of length 22) werq (after reversing the last substring of length 22) Hence, the resulting string after modifying ss with k=2k=2 is werq. Vasya wants to choose a kk such that the string obtained after the above-mentioned modification is lexicographically smallest possible among all choices of kk. Among all such kk, he wants to choose the smallest one. Since he is busy attending Felicity 2020, he asks for your help.A string aa is lexicographically smaller than a string bb if and only if one of the following holds: aa is a prefix of bb, but a≠ba≠b; in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb. InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤50001≤t≤5000). The description of the test cases follows.The first line of each test case contains a single integer nn (1≤n≤50001≤n≤5000) — the length of the string ss.The second line of each test case contains the string ss of nn lowercase latin letters.It is guaranteed that the sum of nn over all test cases does not exceed 50005000.OutputFor each testcase output two lines:In the first line output the lexicographically smallest string s′s′ achievable after the above-mentioned modification. In the second line output the appropriate value of kk (1≤k≤n1≤k≤n) that you chose for performing the modification. If there are multiple values of kk that give the lexicographically smallest string, output the smallest value of kk among them.ExampleInputCopy6 4 abab 6 qwerty 5 aaaaa 6 alaska 9 lfpbavjsm 1 p OutputCopyabab 1 ertyqw 3 aaaaa 1 aksala 6 avjsmbpfl 5 p 1 NoteIn the first testcase of the first sample; the string modification results for the sample abab are as follows : for k=1k=1 : abab for k=2k=2 : baba for k=3k=3 : abab for k=4k=4 : babaThe lexicographically smallest string achievable through modification is abab for k=1k=1 and 33. Smallest value of kk needed to achieve is hence 11.
[ "brute force", "constructive algorithms", "implementation", "sortings", "strings" ]
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.*; import java.io.*; public class Main { // Graph // prefix sums //inputs public static void main(String args[])throws Exception{ Input sc=new Input(); precalculates p=new precalculates(); StringBuilder sb=new StringBuilder(); int t=sc.readInt(); for(int f=0;f<t;f++){ int n=sc.readInt(); String str=sc.readString(); ArrayList<String> lst=new ArrayList<>(); lst.add(str); StringBuilder sin=new StringBuilder(str.charAt(0)+""); StringBuilder sap=new StringBuilder(str.charAt(0)+""); ArrayList<String> fin=new ArrayList<>(); fin.add(str); for(int i=1;i<n;i++){ if((n-i+1)%2==0){ lst.add(str.substring(i)+sin); }else { lst.add(str.substring(i)+sap); } sap.append(str.charAt(i)+""); sin.insert(0,str.charAt(i)+""); fin.add(lst.get(lst.size()-1)+""); } Collections.sort(lst); int ind=0; for(int i=0;i<n;i++){ if(lst.get(0).equals(fin.get(i))){ ind=i; break; } } sb.append(lst.get(0)+"\n"+(ind+1)+"\n"); } System.out.print(sb); } } /* 1 qwerty 2 qwerty -> wqerty -> weqrty -> werqty -> wertqy -> wertyq 3 qwerty -> ewqrty -> erqwty -> ertwqy -> ertyqw 4 qwerty -> rewqty -> rtqwey -> rtyewq 5 qwerty -> trewqy -> tyqwer */ class Input{ BufferedReader br; StringTokenizer st; Input(){ br=new BufferedReader(new InputStreamReader(System.in)); st=new StringTokenizer(""); } public int[] readArray() throws Exception{ st=new StringTokenizer(br.readLine()); int a[]=new int[st.countTokens()]; for(int i=0;i<a.length;i++){ a[i]=Integer.parseInt(st.nextToken()); } return a; } public long[] readArrayLong() throws Exception{ st=new StringTokenizer(br.readLine()); long a[]=new long[st.countTokens()]; for(int i=0;i<a.length;i++){ a[i]=Long.parseLong(st.nextToken()); } return a; } public int readInt() throws Exception{ st=new StringTokenizer(br.readLine()); return Integer.parseInt(st.nextToken()); } public long readLong() throws Exception{ st=new StringTokenizer(br.readLine()); return Long.parseLong(st.nextToken()); } public String readString() throws Exception{ return br.readLine(); } public int[][] read2dArray(int n,int m)throws Exception{ int a[][]=new int[n][m]; for(int i=0;i<n;i++){ st=new StringTokenizer(br.readLine()); for(int j=0;j<m;j++){ a[i][j]=Integer.parseInt(st.nextToken()); } } return a; } } class precalculates{ public long gcd(long p, long q) { if (q == 0) return p; else return gcd(q, p % q); } public int[] prefixSumOneDimentional(int a[]){ int n=a.length; int dp[]=new int[n]; for(int i=0;i<n;i++){ if(i==0) dp[i]=a[i]; else dp[i]=dp[i-1]+a[i]; } return dp; } public int[] postSumOneDimentional(int a[]) { int n = a.length; int dp[] = new int[n]; for (int i = n - 1; i >= 0; i--) { if (i == n - 1) dp[i] = a[i]; else dp[i] = dp[i + 1] + a[i]; } return dp; } public int[][] prefixSum2d(int a[][]){ int n=a.length;int m=a[0].length; int dp[][]=new int[n+1][m+1]; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ dp[i][j]=a[i-1][j-1]+dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1]; } } return dp; } public long pow(long a,long b){ long mod=1000000007; long ans=1; if(b<=0) return 1; if(b%2==0){ ans=pow(a,b/2)%mod; return ((ans%mod)*(ans%mod))%mod; }else{ ans=pow(a,b-1)%mod; return ((a%mod)*(ans%mod))%mod; } } } class GraphInteger{ HashMap<Integer,vertex> vtces; class vertex{ HashMap<Integer,Integer> children; public vertex(){ children=new HashMap<>(); } } public GraphInteger(){ vtces=new HashMap<>(); } public void addVertex(int a){ vtces.put(a,new vertex()); } public void addEdge(int a,int b,int cost){ if(!vtces.containsKey(a)){ vtces.put(a,new vertex()); } if(!vtces.containsKey(b)){ vtces.put(b,new vertex()); } vtces.get(a).children.put(b,cost); // vtces.get(b).children.put(a,cost); } public boolean isCyclicDirected(){ boolean isdone[]=new boolean[vtces.size()+1]; boolean check[]=new boolean[vtces.size()+1]; for(int i=1;i<=vtces.size();i++) { if (!isdone[i] && isCyclicDirected(i,isdone, check)) { return true; } } return false; } private boolean isCyclicDirected(int i,boolean isdone[],boolean check[]){ if(check[i]) return true; if(isdone[i]) return false; check[i]=true; isdone[i]=true; Set<Integer> set=vtces.get(i).children.keySet(); for(Integer ii:set){ if(isCyclicDirected(ii,isdone,check)) return true; } check[i]=false; return false; } } class union_find { int n; int[] sz; int[] par; union_find(int nval) { n = nval; sz = new int[n + 1]; par = new int[n + 1]; for (int i = 0; i <= n; i++) { par[i] = i; sz[i] = 1; } } int root(int x) { if (par[x] == x) return x; return par[x] = root(par[x]); } boolean find(int a, int b) { return root(a) == root(b); } int union(int a, int b) { int ra = root(a); int rb = root(b); if (ra == rb) return 0; if(a==b) return 0; if (sz[a] > sz[b]) { int temp = ra; ra = rb; rb = temp; } par[ra] = rb; sz[rb] += sz[ra]; return 1; } }
java
1324
B
B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a subsequence of the array aa if bb can be obtained by removing some (possibly, zero) elements from aa (not necessarily consecutive) without changing the order of remaining elements. For example, [2][2], [1,2,1,3][1,2,1,3] and [2,3][2,3] are subsequences of [1,2,1,3][1,2,1,3], but [1,1,2][1,1,2] and [4][4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array aa of length nn is the palindrome if ai=an−i−1ai=an−i−1 for all ii from 11 to nn. For example, arrays [1234][1234], [1,2,1][1,2,1], [1,3,2,2,3,1][1,3,2,2,3,1] and [10,100,10][10,100,10] are palindromes, but arrays [1,2][1,2] and [1,2,3,1][1,2,3,1] are not.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 50005000 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5 3 1 2 1 5 1 2 2 3 2 3 1 1 2 4 1 2 2 1 10 1 1 2 2 3 3 4 4 5 5 OutputCopyYES YES NO YES NO NoteIn the first test case of the example; the array aa has a subsequence [1,2,1][1,2,1] which is a palindrome.In the second test case of the example, the array aa has two subsequences of length 33 which are palindromes: [2,3,2][2,3,2] and [2,2,2][2,2,2].In the third test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.In the fourth test case of the example, the array aa has one subsequence of length 44 which is a palindrome: [1,2,2,1][1,2,2,1] (and has two subsequences of length 33 which are palindromes: both are [1,2,1][1,2,1]).In the fifth test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.
[ "brute force", "strings" ]
// package c1324; // // Codeforces Round #627 (Div. 3) 2020-03-12 05:05 // B. Yet Another Palindrome Problem // https://codeforces.com/contest/1324/problem/B // 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 an array a consisting of n integers. // // Your task is to determine if a has some of length at least 3 that is a palindrome. // // Recall that an array b is called a of the array a if b can be obtained by removing some // (possibly, zero) elements from a (not necessarily consecutive) without changing the order of // remaining elements. For example, [2], [1, 2, 1, 3] and [2, 3] are subsequences of [1, 2, 1, 3], // but [1, 1, 2] and [4] are not. // // Also, recall that a palindrome is an array that reads the same backward as forward. In other // words, the array a of length n is the palindrome if a_i = a_{n - i - 1} for all i from 1 to n. // For example, arrays [1234], [1, 2, 1], [1, 3, 2, 2, 3, 1] and [10, 100, 10] are palindromes, but // arrays [1, 2] and [1, 2, 3, 1] are not. // // You have to answer t independent test cases. // // Input // // The first line of the input contains one integer t (1 <= t <= 100) -- the number of test cases. // // Next 2t lines describe test cases. The first line of the test case contains one integer n (3 <= n // <= 5000) -- the length of a. The second line of the test case contains n integers a_1, a_2, ..., // a_n (1 <= a_i <= n), where a_i is the i-th element of a. // // It is guaranteed that the sum of n over all test cases does not exceed 5000 (\sum n <= 5000). // // Output // // For each test case, print the answer -- "YES" (without quotes) if a has some of length at least 3 // that is a palindrome and "NO" otherwise. // // Example /* input: 5 3 1 2 1 5 1 2 2 3 2 3 1 1 2 4 1 2 2 1 10 1 1 2 2 3 3 4 4 5 5 output: YES YES NO YES NO */ // Note // // In the first test case of the example, the array a has a subsequence [1, 2, 1] which is a // palindrome. // // In the second test case of the example, the array a has two subsequences of length 3 which are // palindromes: [2, 3, 2] and [2, 2, 2]. // // In the third test case of the example, the array a has no subsequences of length at least 3 which // are palindromes. // // In the fourth test case of the example, the array a has one subsequence of length 4 which is a // palindrome: [1, 2, 2, 1] (and has two subsequences of length 3 which are palindromes: both are // [1, 2, 1]). // // In the fifth test case of the example, the array a has no subsequences of length at least 3 which // are palindromes. // 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.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.StringTokenizer; public class C1324B { static final int MOD = 998244353; static final Random RAND = new Random(); static boolean solve(int[] a) { int n = a.length; Map<Integer, List<Integer>> vim = new HashMap<>(); for (int i = 0; i < n; i++) { vim.computeIfAbsent(a[i], x -> new ArrayList<>()).add(i); } for (List<Integer> idxes : vim.values()) { if (idxes.size() >= 3) { return true; } else if (idxes.size() == 2) { if (idxes.get(1) - idxes.get(0) > 1) { return true; } } } return false; } static boolean test = false; static void doTest() { if (!test) { return; } long t0 = System.currentTimeMillis(); System.out.format("%d msec\n", System.currentTimeMillis() - t0); System.exit(0); } public static void main(String[] args) { doTest(); MyScanner in = new MyScanner(); int T = in.nextInt(); for (int t = 1; t <= T; t++) { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } boolean ans = solve(a); System.out.println(ans? "YES" : "NO"); } } static void output(int[] a) { if (a == null) { System.out.println("-1"); return; } StringBuilder sb = new StringBuilder(); for (int v : a) { sb.append(v); sb.append(' '); if (sb.length() > 4000) { System.out.print(sb.toString()); sb.setLength(0); } } System.out.println(sb.toString()); } static void myAssert(boolean cond) { if (!cond) { throw new RuntimeException("Unexpected"); } } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { try { final String USERDIR = System.getProperty("user.dir"); String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", ""); cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname; final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in"); br = new BufferedReader(new InputStreamReader(fin.exists() ? new FileInputStream(fin) : System.in)); } catch (Exception e) { br = new BufferedReader(new InputStreamReader(System.in)); } } public String next() { try { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
java
1315
B
B. Homecomingtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputAfter a long party Petya decided to return home; but he turned out to be at the opposite end of the town from his home. There are nn crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.The crossroads are represented as a string ss of length nn, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad. Currently Petya is at the first crossroad (which corresponds to s1s1) and his goal is to get to the last crossroad (which corresponds to snsn).If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a bus station, one can pay aa roubles for the bus ticket, and go from ii-th crossroad to the jj-th crossroad by the bus (it is not necessary to have a bus station at the jj-th crossroad). Formally, paying aa roubles Petya can go from ii to jj if st=Ast=A for all i≤t<ji≤t<j. If for two crossroads ii and jj for all crossroads i,i+1,…,j−1i,i+1,…,j−1 there is a tram station, one can pay bb roubles for the tram ticket, and go from ii-th crossroad to the jj-th crossroad by the tram (it is not necessary to have a tram station at the jj-th crossroad). Formally, paying bb roubles Petya can go from ii to jj if st=Bst=B for all i≤t<ji≤t<j.For example, if ss="AABBBAB", a=4a=4 and b=3b=3 then Petya needs: buy one bus ticket to get from 11 to 33, buy one tram ticket to get from 33 to 66, buy one bus ticket to get from 66 to 77. Thus, in total he needs to spend 4+3+4=114+3+4=11 roubles. Please note that the type of the stop at the last crossroad (i.e. the character snsn) does not affect the final expense.Now Petya is at the first crossroad, and he wants to get to the nn-th crossroad. After the party he has left with pp roubles. He's decided to go to some station on foot, and then go to home using only public transport.Help him to choose the closest crossroad ii to go on foot the first, so he has enough money to get from the ii-th crossroad to the nn-th, using only tram and bus tickets.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1041≤t≤104).The first line of each test case consists of three integers a,b,pa,b,p (1≤a,b,p≤1051≤a,b,p≤105) — the cost of bus ticket, the cost of tram ticket and the amount of money Petya has.The second line of each test case consists of one string ss, where si=Asi=A, if there is a bus station at ii-th crossroad, and si=Bsi=B, if there is a tram station at ii-th crossroad (2≤|s|≤1052≤|s|≤105).It is guaranteed, that the sum of the length of strings ss by all test cases in one test doesn't exceed 105105.OutputFor each test case print one number — the minimal index ii of a crossroad Petya should go on foot. The rest of the path (i.e. from ii to nn he should use public transport).ExampleInputCopy5 2 2 1 BB 1 1 1 AB 3 2 8 AABBBBAABB 5 3 4 BBBBB 2 1 1 ABABAB OutputCopy2 1 3 1 6
[ "binary search", "dp", "greedy", "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_Homecoming { 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 a = f.nextInt(); int b = f.nextInt(); int p = f.nextInt(); String s = f.nextLine(); int n = s.length(); long arr[] = new long[n]; int ind = n-2; arr[ind] = (s.charAt(ind) == 'A') ? a : b; ind--; while(ind >= 0) { if(s.charAt(ind) == s.charAt(ind+1)) { arr[ind] = arr[ind+1]; } else { if(s.charAt(ind) == 'A') { arr[ind] = arr[ind+1] + a; } else { arr[ind] = arr[ind+1] + b; } } ind--; } for(int i = 0; i < n; i++) { if(arr[i] <= p) { out.println(i+1); return; } } } public static void sort(int arr[]) { ArrayList<Integer> al = new ArrayList<>(); for(int i: arr) { al.add(i); } Collections.sort(al); for(int i = 0; i < arr.length; i++) { arr[i] = al.get(i); } } public static void allDivisors(int n) { for(int i = 1; i*i <= n; i++) { if(n%i == 0) { System.out.println(i + " "); if(i != n/i) { System.out.println(n/i + " "); } } } } public static boolean isPrime(int n) { if(n < 1) return false; if(n == 2 || n == 3) return true; if(n % 2 == 0 || n % 3 == 0) return false; for(int i = 5; i*i <= n; i += 6) { if(n % i == 0 || n % (i+2) == 0) { return false; } } return true; } public static int gcd(int a, int b) { int dividend = a > b ? a : b; int divisor = a < b ? a : b; while(divisor > 0) { int reminder = dividend % divisor; dividend = divisor; divisor = reminder; } return dividend; } public static int lcm(int a, int b) { int lcm = gcd(a, b); int hcf = (a * b) / lcm; return hcf; } public static String sortString(String inputString) { char tempArray[] = inputString.toCharArray(); Arrays.sort(tempArray); return new String(tempArray); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } float nextFloat() { return Float.parseFloat(next()); } boolean nextBoolean() { return Boolean.parseBoolean(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } int[] nextArray(int n) { int[] a = new int[n]; for(int i=0; i<n; i++) { a[i] = nextInt(); } return a; } } } /** Dec Char Dec Char Dec Char Dec Char --------- --------- --------- ---------- 0 NUL (null) 32 SPACE 64 @ 96 ` 1 SOH (start of heading) 33 ! 65 A 97 a 2 STX (start of text) 34 " 66 B 98 b 3 ETX (end of text) 35 # 67 C 99 c 4 EOT (end of transmission) 36 $ 68 D 100 d 5 ENQ (enquiry) 37 % 69 E 101 e 6 ACK (acknowledge) 38 & 70 F 102 f 7 BEL (bell) 39 ' 71 G 103 g 8 BS (backspace) 40 ( 72 H 104 h 9 TAB (horizontal tab) 41 ) 73 I 105 i 10 LF (NL line feed, new line) 42 * 74 J 106 j 11 VT (vertical tab) 43 + 75 K 107 k 12 FF (NP form feed, new page) 44 , 76 L 108 l 13 CR (carriage return) 45 - 77 M 109 m 14 SO (shift out) 46 . 78 N 110 n 15 SI (shift in) 47 / 79 O 111 o 16 DLE (data link escape) 48 0 80 P 112 p 17 DC1 (device control 1) 49 1 81 Q 113 q 18 DC2 (device control 2) 50 2 82 R 114 r 19 DC3 (device control 3) 51 3 83 S 115 s 20 DC4 (device control 4) 52 4 84 T 116 t 21 NAK (negative acknowledge) 53 5 85 U 117 u 22 SYN (synchronous idle) 54 6 86 V 118 v 23 ETB (end of trans. block) 55 7 87 W 119 w 24 CAN (cancel) 56 8 88 X 120 x 25 EM (end of medium) 57 9 89 Y 121 y 26 SUB (substitute) 58 : 90 Z 122 z 27 ESC (escape) 59 ; 91 [ 123 { 28 FS (file separator) 60 < 92 \ 124 | 29 GS (group separator) 61 = 93 ] 125 } 30 RS (record separator) 62 > 94 ^ 126 ~ 31 US (unit separator) 63 ? 95 _ 127 DEL */
java
13
B
B. Letter Atime limit per test1 secondmemory limit per test64 megabytesinputstdinoutputstdoutLittle Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.You are given three segments on the plane. They form the letter A if the following conditions hold: Two segments have common endpoint (lets call these segments first and second); while the third segment connects two points on the different segments. The angle between the first and the second segments is greater than 0 and do not exceed 90 degrees. The third segment divides each of the first two segments in proportion not less than 1 / 4 (i.e. the ratio of the length of the shortest part to the length of the longest part is not less than 1 / 4). InputThe first line contains one integer t (1 ≤ t ≤ 10000) — the number of test cases to solve. Each case consists of three lines. Each of these three lines contains four space-separated integers — coordinates of the endpoints of one of the segments. All coordinates do not exceed 108 by absolute value. All segments have positive length.OutputOutput one line for each test case. Print «YES» (without quotes), if the segments form the letter A and «NO» otherwise.ExamplesInputCopy34 4 6 04 1 5 24 0 4 40 0 0 60 6 2 -41 1 0 10 0 0 50 5 2 -11 2 0 1OutputCopyYESNOYES
[ "geometry", "implementation" ]
import java.io.IOException; import java.util.Scanner; public class LetterA { static class Point{ int x,y; Point(int x, int y){ this.x=x; this.y=y; } } static class Segment{ Point p1,p2; Segment(Point p1, Point p2){ this.p1=p1; this.p2=p2; } } static boolean acute(Point l, Point m, Point n){ long area=(long)(l.x-n.x)*(m.y-n.y)-(long)(l.y-n.y)*(m.x-n.x); long a=(long)(l.x-n.x)*(l.x-n.x)+(long) (l.y-n.y)*(l.y-n.y); long b=(long)(m.x-n.x)*(m.x-n.x)+(long) (m.y-n.y)*(m.y-n.y); long c=(long)(m.x-l.x)*(m.x-l.x)+(long) (m.y-l.y)*(m.y-l.y); return area!=0 && c<=a+b; } static boolean verticalSegment(Segment a, Segment b){ if(a.p1.x==b.p1.x && a.p1.y==b.p1.y){ return acute(a.p2,b.p2,a.p1); } if(a.p2.x==b.p2.x && a.p2.y==b.p2.y){ return acute(a.p1,b.p1,a.p2); } if(a.p1.x==b.p2.x && a.p1.y==b.p2.y){ return acute(a.p2,b.p1,a.p1); } if(a.p2.x==b.p1.x && a.p2.y==b.p1.y){ return acute(a.p1,b.p2,a.p2); } return false; } static boolean intersecting(Segment s,Point p){ if(p.x<Math.min(s.p1.x,s.p2.x) || p.x>Math.max(s.p1.x,s.p2.x) || p.y<Math.min(s.p1.y,s.p2.y)|| p.y>Math.max(s.p1.y,s.p2.y)) return false; int x=Math.abs(s.p1.x-s.p2.x); int y=Math.abs(s.p1.y-s.p2.y); int xm=Math.min(Math.abs(s.p1.x-p.x),Math.abs(s.p2.x-p.x)); int ym=Math.min(Math.abs(s.p1.y-p.y),Math.abs(s.p2.y-p.y)); return x<=5*xm && y<=5*ym && (long)(p.x-s.p2.x)*(s.p1.y-s.p2.y)==(long)(p.y-s.p2.y)*(s.p1.x-s.p2.x); } static boolean check(Segment a, Segment b, Segment c){ return verticalSegment(a,b)&& (intersecting(a,c.p1)&&intersecting(b,c.p2) || intersecting(b,c.p1)&&intersecting(a,c.p2)); } public static void main(String[] args) throws IOException { Scanner cin= new Scanner(System.in); int n= cin.nextInt(); Segment[][] segments= new Segment[n][3]; for(int i=0;i<n;i++) { for(int j=0; j<3;j++){ int x1 = cin.nextInt(); int y1 = cin.nextInt(); int x2 = cin.nextInt(); int y2 = cin.nextInt(); segments[i][j]= new Segment(new Point(x1,y1),new Point(x2,y2)); } System.out.println(check(segments[i][0],segments[i][1],segments[i][2]) ||check(segments[i][1],segments[i][2],segments[i][0]) ||check(segments[i][2],segments[i][0],segments[i][1])?"YES":"NO"); } } }
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.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.LinkedList; import java.util.List; import java.util.Map; import java.util.StringTokenizer; public class C1311E_1 { public static void main(String[] args) { var scanner = new BufferedScanner(); var writer = new PrintWriter(new BufferedOutputStream(System.out)); var t = scanner.nextInt(); for (int tc = 0; tc < t; tc++) { var n = scanner.nextInt(); var d = scanner.nextInt(); var ans = solve(n, d); if (ans == null) { writer.println("NO"); } else { writer.println("YES"); for (int i = 2; i <= n; i++) { writer.print(ans[i] + " "); } writer.println(); } } scanner.close(); writer.flush(); writer.close(); } private static int[] solve(int n, int d) { var maxD = (n - 1) * n / 2; if (d > maxD) { return null; } var parent = new int[n + 1]; var childCount = new int[n + 1]; var depth = new int[n + 1]; for (int i = 2; i <= n; i++) { parent[i] = i - 1; depth[i] = i - 1; childCount[i - 1] = 1; } var dToRemove = maxD - d; while (dToRemove > 0) { var leaf = 0; for (int i = 1; i <= n; i++) { if (childCount[i] == 0 && (leaf == 0 || depth[i] > depth[leaf])) { leaf = i; } } var newParent = 0; for (int i = 1; i <= n; i++) { int delta = depth[leaf] - 1 - depth[i]; if (childCount[i] < 2 && delta > 0 && delta <= dToRemove && (newParent == 0 || depth[i] < depth[newParent])) { newParent = i; } } if (newParent == 0) { return null; } var oldParent = parent[leaf]; childCount[oldParent]--; var newDepth = depth[newParent] + 1; dToRemove -= (depth[leaf] - newDepth); depth[leaf] = newDepth; parent[leaf] = newParent; childCount[newParent]++; } return parent; } private static void add(int node, Map<Integer, List<Integer>> nodes, int[] depth, int[] childCount) { var hash = hash(depth[node], childCount[node]); nodes.putIfAbsent(hash, new LinkedList<>()); nodes.get(hash).add(node); } private static void remove(Integer node, Map<Integer, List<Integer>> nodes, int[] depth, int[] childCount) { var hash = hash(depth[node], childCount[node]); nodes.get(hash).remove(node); } private static int hash(int depth, int childCount) { return depth * 3 + childCount; } 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
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.*; public class Solution { public static void main(String[] args) { Scanner in=new Scanner(System.in); int t=in.nextInt(); for(int c=0;c<t;c++) { int n=in.nextInt(); in.nextLine(); String str=in.nextLine(); int size=0; int result=0; boolean hasA=false; for(int i=0;i<n;i++) { if(str.charAt(i)=='A'&&!hasA) { hasA=true; } else if(str.charAt(i)=='A') { if(size>=result) result=size; size=0; } else if(hasA) size++; } if(size>result) result=size; System.out.println(result); } } }
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.util.*; public class Hello { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); while (T-- > 0) { long N = sc.nextLong(); int M = sc.nextInt(); int freq[] = new int[65]; long sum = 0; for (int index = 0; index < M; index++) { int val = sc.nextInt(); for (int ctr = 0; ctr < 64; ctr++) { if ((val & (1L << ctr)) != 0L) { freq[ctr]++; break; } } sum += val; } if (N > sum) { System.out.println("-1"); continue; } int count = 0; for (int ctr = 0; ctr < 64; ctr++) { if ((N & (1L << ctr)) == 0L) { freq[ctr + 1] += freq[ctr] / 2; continue; } for (int val = ctr; val < 64; val++) { if (freq[val] != 0) { freq[val]--; break; } freq[val]++; count++; } freq[ctr + 1] += freq[ctr] / 2; } System.out.println(count); } } }
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.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.lang.reflect.Array; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import org.w3c.dom.NamedNodeMap; import java.io.*; import java.math.*; import java.util.*; import java.util.Arrays; import java.util.Comparator; import java.util.*; public class ispcff { public static void main(String[] args) throws java.lang.Exception { ispcff.FastReader sc =new FastReader(); int n = sc.nextInt(); int m = sc.nextInt(); String arr[]=new String [n]; String arr1[]= new String [m]; for (int i=0;i<n;i++) { arr[i]= sc.next(); } for (int i =0;i<m;i++) { arr1[i]= sc.next(); } int r = sc.nextInt(); for (int e=0;e<r;e++) { int y=sc.nextInt(); int w = y%n; int ww = y%m; if(w==0) { System.out.print(arr[n-1]); } else { System.out.print(arr[w-1]); } if(ww==0) { System.out.print(arr1[m-1]); } else { System.out.print(arr1[ww-1]); } System.out.println(); } } 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 void reverse_sorted(int[] arr) { ArrayList<Integer> list = new ArrayList<>(); for(int i=0;i<arr.length;i++) { list.add(arr[i]); } Collections.sort(list , Collections.reverseOrder()); for(int i=0;i<arr.length;i++) { arr[i] = list.get(i); } } static int LowerBound(int a[], int x) { // x is the target value or key int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]>=x) r=m; else l=m; } return r; } static int UpperBound(ArrayList<Integer> list, int x) {// x is the key or target value int l=-1,r=list.size(); while(l+1<r) { int m=(l+r)>>>1; if(list.get(m)<=x) l=m; else r=m; } return l+1; } public static HashMap<String, Integer> sortByValue(HashMap<String, Integer> hm) { // Create a list from elements of HashMap List<Map.Entry<String, Integer> > list = new LinkedList<Map.Entry<String, Integer> >(hm.entrySet()); // Sort the list Collections.sort(list, new Comparator<Map.Entry<String, Integer> >() { public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); // put data from sorted list to hashmap HashMap<String, Integer> temp = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> aa : list) { temp.put(aa.getKey(), aa.getValue()); } return temp; } static class Queue_Pair implements Comparable<Queue_Pair> { int first , second; public Queue_Pair(int first, int second) { this.first=first; this.second=second; } public int compareTo(Queue_Pair o) { return Integer.compare(o.first, first); } } static void leftRotate(int arr[], int d, int n) { for (int i = 0; i < d; i++) leftRotatebyOne(arr, n); } static void leftRotatebyOne(int arr[], int n) { int i, temp; temp = arr[0]; for (i = 0; i < n - 1; i++) arr[i] = arr[i + 1]; arr[n-1] = temp; } static boolean isPalindrome(String str) { // Pointers pointing to the beginning // and the end of the string int i = 0, j = str.length() - 1; // While there are characters to compare while (i < j) { // If there is a mismatch if (str.charAt(i) != str.charAt(j)) return false; // Increment first pointer and // decrement the other i++; j--; } // Given string is a palindrome return true; } static boolean palindrome_array(char arr[], int n) { // Initialise flag to zero. int flag = 0; // Loop till array size n/2. for (int i = 0; i <= n / 2 && n != 0; i++) { // Check if first and last element are different // Then set flag to 1. if (arr[i] != arr[n - i - 1]) { flag = 1; break; } } // If flag is set then print Not Palindrome // else print Palindrome. if (flag == 1) return false; else return true; } static boolean allElementsEqual(long[] arr,int n) { int z=0; for(int i=0;i<n-1;i++) { if(arr[i]==arr[i+1]) { z++; } } if(z==n-1) { return true; } else { return false; } } static boolean allElementsDistinct(int[] arr,int n) { int z=0; for(int i=0;i<n-1;i++) { if(arr[i]!=arr[i+1]) { z++; } } if(z==n-1) { return true; } else { return false; } } public static void reverse(int[] array) { // Length of the array int n = array.length; // Swaping the first half elements with last half // elements for (int i = 0; i < n / 2; i++) { // Storing the first half elements temporarily int temp = array[i]; // Assigning the first half to the last half array[i] = array[n - i - 1]; // Assigning the last half to the first half array[n - i - 1] = temp; } } public static void reverse_Long(long[] array) { // Length of the array int n = array.length; // Swaping the first half elements with last half // elements for (int i = 0; i < n / 2; i++) { // Storing the first half elements temporarily long temp = array[i]; // Assigning the first half to the last half array[i] = array[n - i - 1]; // Assigning the last half to the first half array[n - i - 1] = temp; } } static boolean isSorted(int[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { return false; } } return true; } static boolean isReverseSorted(int[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] < a[i + 1]) { return false; } } return true; } static int[] rearrangeEvenAndOdd(int arr[], int n) { ArrayList<Integer> list = new ArrayList<>(); for(int i=0;i<n;i++) { if(arr[i]%2==0) { list.add(arr[i]); } } for(int i=0;i<n;i++) { if(arr[i]%2!=0) { list.add(arr[i]); } } int len = list.size(); int[] array = list.stream().mapToInt(i->i).toArray(); return array; } static long[] rearrangeEvenAndOddLong(long arr[], int n) { ArrayList<Long> list = new ArrayList<>(); for(int i=0;i<n;i++) { if(arr[i]%2==0) { list.add(arr[i]); } } for(int i=0;i<n;i++) { if(arr[i]%2!=0) { list.add(arr[i]); } } int len = list.size(); long[] array = list.stream().mapToLong(i->i).toArray(); return array; } static boolean isPrime(long 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 (long i = 3; i <= Math.sqrt(n); i += 2) { if (n % i == 0) return false; } return true; } static long getSum(long n) { long sum = 0; while (n != 0) { sum = sum + n % 10; n = n/10; } return sum; } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static long gcdLong(long a, long b) { if (b == 0) return a; return gcdLong(b, a % b); } static void swap(int i, int j) { int temp = i; i = j; j = temp; } static int countDigit(int n) { return (int)Math.floor(Math.log10(n) + 1); } //Arrays.sort(arr, Comparator.comparingDouble(o -> o[0])); // q.replace(i, i+1, "4"); // StringBuilder q = new StringBuilder(w); }
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.*; import java.io.*; public class practice { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(new BufferedWriter(new PrintWriter(System.out))); StringBuilder sb = new StringBuilder(); int t = Integer.parseInt(br.readLine()); while (t --> 0) { StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int d = Integer.parseInt(st.nextToken()); if (d <= n) sb.append("Yes"); else { int low = 0; int high = n; boolean flag = false; while (low <= high && !flag) { int mid1 = low + (high - low) / 3; int mid2 = high - (high - low) / 3; int temp1 = mid1 + (int) Math.ceil((double) d / (mid1 + 1)); int temp2 = mid2 + (int) Math.ceil((double) d / (mid2 + 1)); if (temp2 <= n || temp1 <= n) flag = true; else { low = mid1 + 1; high = mid2 - 1; } } sb.append(flag ? "Yes" : "No"); } sb.append("\n"); } pw.println(sb.toString().trim()); pw.close(); br.close(); } }
java
1311
A
A. Add Odd or Subtract Eventime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given two positive integers aa and bb.In one move, you can change aa in the following way: Choose any positive odd integer xx (x>0x>0) and replace aa with a+xa+x; choose any positive even integer yy (y>0y>0) and replace aa with a−ya−y. You can perform as many such operations as you want. You can choose the same numbers xx and yy in different moves.Your task is to find the minimum number of moves required to obtain bb from aa. It is guaranteed that you can always obtain bb from aa.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. Each test case is given as two space-separated integers aa and bb (1≤a,b≤1091≤a,b≤109).OutputFor each test case, print the answer — the minimum number of moves required to obtain bb from aa if you can perform any number of moves described in the problem statement. It is guaranteed that you can always obtain bb from aa.ExampleInputCopy5 2 3 10 10 2 4 7 4 9 3 OutputCopy1 0 2 2 1 NoteIn the first test case; you can just add 11.In the second test case, you don't need to do anything.In the third test case, you can add 11 two times.In the fourth test case, you can subtract 44 and add 11.In the fifth test case, you can just subtract 66.
[ "greedy", "implementation", "math" ]
import java.util.*; public class Oddeven { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); for(int i=0;i<n;i++) { int a = in.nextInt(); int b = in.nextInt(); if(a==b) System.out.println(0); else if (a-b>0&&(a-b)%2==0) System.out.println(1); else if(a-b<0&&(a-b)%2!=0) System.out.println(1); else System.out.println(2); } } }
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.io.*; import java.util.*; public class We { public static void main(String[] args) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader (new InputStreamReader (System.in)); int numberSets = Integer.parseInt(br.readLine()); for (int nos = 0; nos < numberSets; nos++) { int size = Integer.parseInt(br.readLine()); Set <Integer> set = new HashSet <> (); int [] data = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray(); for (int i = 0; i < data.length; i++) { set.add(data[i]); } System.out.println(set.size()); } } }
java
1325
A
A. EhAb AnD gCdtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a positive integer xx. Find any such 22 positive integers aa and bb such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x.As a reminder, GCD(a,b)GCD(a,b) is the greatest integer that divides both aa and bb. Similarly, LCM(a,b)LCM(a,b) is the smallest integer such that both aa and bb divide it.It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.InputThe first line contains a single integer tt (1≤t≤100)(1≤t≤100)  — the number of testcases.Each testcase consists of one line containing a single integer, xx (2≤x≤109)(2≤x≤109).OutputFor each testcase, output a pair of positive integers aa and bb (1≤a,b≤109)1≤a,b≤109) such that GCD(a,b)+LCM(a,b)=xGCD(a,b)+LCM(a,b)=x. It's guaranteed that the solution always exists. If there are several such pairs (a,b)(a,b), you can output any of them.ExampleInputCopy2 2 14 OutputCopy1 1 6 4 NoteIn the first testcase of the sample; GCD(1,1)+LCM(1,1)=1+1=2GCD(1,1)+LCM(1,1)=1+1=2.In the second testcase of the sample, GCD(6,4)+LCM(6,4)=2+12=14GCD(6,4)+LCM(6,4)=2+12=14.
[ "constructive algorithms", "greedy", "number theory" ]
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 b = scan.nextInt(); if(b%2==0) System.out.println(b/2 + " " + b/2); else System.out.println(1 + " " + (b-1)); } } }
java
1312
D
D. Count the Arraystime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputYour task is to calculate the number of arrays such that: each array contains nn elements; each element is an integer from 11 to mm; for each array, there is exactly one pair of equal elements; for each array aa, there exists an index ii such that the array is strictly ascending before the ii-th element and strictly descending after it (formally, it means that aj<aj+1aj<aj+1, if j<ij<i, and aj>aj+1aj>aj+1, if j≥ij≥i). InputThe first line contains two integers nn and mm (2≤n≤m≤2⋅1052≤n≤m≤2⋅105).OutputPrint one integer — the number of arrays that meet all of the aforementioned conditions, taken modulo 998244353998244353.ExamplesInputCopy3 4 OutputCopy6 InputCopy3 5 OutputCopy10 InputCopy42 1337 OutputCopy806066790 InputCopy100000 200000 OutputCopy707899035 NoteThe arrays in the first example are: [1,2,1][1,2,1]; [1,3,1][1,3,1]; [1,4,1][1,4,1]; [2,3,2][2,3,2]; [2,4,2][2,4,2]; [3,4,3][3,4,3].
[ "combinatorics", "math" ]
import java.awt.MultipleGradientPaint.ColorSpaceType; import java.io.*; import java.sql.PreparedStatement; import java.util.*; public class cp { static int mod=998244353;//(int)1e9+7; // static Reader sc=new Reader(); static FastReader sc=new FastReader(System.in); static int[] sp; static int size=(int)1e6; static int[] arInt; static long[] arLong; static long ans; public static void main(String[] args) throws IOException { // long tc=sc.nextLong(); // Scanner sc=new Scanner(System.in); int tc=1; // print_int(pre); // primeSet=new HashSet<>(); // primeCnt=new int[(int)1e9]; // sieveOfEratosthenes((int)1e9); factorial(mod); InverseofNumber(mod); InverseofFactorial(mod); while(tc-->0) { int n=sc.nextInt(); int m=sc.nextInt(); out.println((Binomial(m, n-1, mod)*(n-2)%mod)*(power(2L, (long)n-3)%mod)%mod); } // System.out.flush(); out.flush(); out.close(); System.gc(); } /* ...SOLUTION ENDS HERE...........SOLUTION ENDS HERE... */ static class Node{ int a; ArrayList<Pair> adj; public Node(int a) { this.a=a; this.adj=new ArrayList<>(); } } static void dijkstra(Node[] g,int dist[],int parent[],int src) { Arrays.fill(dist, int_max); Arrays.fill(parent, -1); boolean vis[]=new boolean[dist.length]; // vis[1]=true; PriorityQueue<Pair> q=new PriorityQueue<>(); q.add(new Pair(1, 0)); dist[1]=0; while(!q.isEmpty()) { Pair curr=q.poll(); vis[curr.x]=true; for(Pair edge:g[curr.x].adj) { if (vis[edge.x]) { continue; } if (dist[edge.x]>dist[curr.x]+edge.y) { dist[edge.x]=dist[curr.x]+edge.y; parent[edge.x]=curr.x; q.add(new Pair(edge.x, dist[edge.x])); } } } } static void mapping(int a[]) { Pair[] temp=new Pair[a.length]; for (int i = 0; i < temp.length; i++) { temp[i]=new Pair(a[i], i); } Arrays.sort(temp); int k=0; for (int i = 0; i < temp.length; i++) { a[temp[i].y]=k++; } } static boolean palin(String s) { for(int i=0;i<s.length()/2;i++) if(s.charAt(i)!=s.charAt(s.length()-i-1)) return false; return true; } static class temp implements Comparable<temp>{ int x; int y; int sec; public temp(int x,int y,int l) { // TODO Auto-generated constructor stub this.x=x; this.y=y; this.sec=l; } @Override public int compareTo(cp.temp o) { // TODO Auto-generated method stub return this.sec-o.sec; } } // static class Node{ // int x; // int y; // ArrayList<Integer> edges; // public Node(int x,int y) { // // TODO Auto-generated constructor stub // this.x=x; // this.y=y; // this.edges=new ArrayList<>(); // } // } static int lis(int arr[],int n) { int ans=0; int dp[]=new int[n+1]; Arrays.fill(dp, int_max); dp[0]=int_min; for(int i=0;i<n;i++) { int j=UpperBound(dp,arr[i]); if(dp[j-1]<=arr[i] && arr[i]<dp[j]) dp[j]=arr[i]; } for(int i=0;i<=n;i++) { if(dp[i]<int_max) ans=i; } return ans; } static long get(long n) { return n*(n+1)/2L; } static boolean go(ArrayList<Pair> caves,int k) { for(Pair each:caves) { if(k<=each.x) return false; k+=each.y; } return true; } static String revString(String s) { char arr[]=s.toCharArray(); int n=s.length(); for(int i=0;i<n/2;i++) { char temp=arr[i]; arr[i]=arr[n-i-1]; arr[n-i-1]=temp; } return String.valueOf(arr); } // Fuction return the number of set bits in n static int SetBits(int n) { int cnt=0; while(n>0) { if((n&1)==1) { cnt++; } n=n>>1; } return cnt; } 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 void arrInt(int n) throws IOException { arInt=new int[n]; for (int i = 0; i < arInt.length; i++) { arInt[i]=sc.nextInt(); } } static void arrLong(int n) throws IOException { arLong=new long[n]; for (int i = 0; i < arLong.length; i++) { arLong[i]=sc.nextLong(); } } static ArrayList<Integer> add(int id,int c) { ArrayList<Integer> newArr=new ArrayList<>(); for(int i=0;i<id;i++) newArr.add(arInt[i]); newArr.add(c); for(int i=id;i<arInt.length;i++) { newArr.add(arInt[i]); } return newArr; } // function to find first index >= y static int upper(ArrayList<Integer> arr, int n, int x) { int l = 0, h = n - 1; while (h-l>1) { int mid = (l + h) / 2; if (arr.get(mid) <= x) l=mid+1; else { h=mid; } } if(arr.get(l)>x) { return l; } if(arr.get(h)>x) return h; return -1; } static int upper(ArrayList<Long> arr, int n, long x) { int l = 0, h = n - 1; while (h-l>1) { int mid = (l + h) / 2; if (arr.get(mid) <= x) l=mid+1; else { h=mid; } } if(arr.get(l)>x) { return l; } if(arr.get(h)>x) return h; return -1; } static int lower(ArrayList<Integer> arr, int n, int x) { int l = 0, h = n - 1; while (h-l>1) { int mid = (l + h) / 2; if (arr.get(mid) < x) l=mid+1; else { h=mid; } } if(arr.get(l)>=x) { return l; } if(arr.get(h)>=x) return h; return -1; } static int N = (int)2e5+5; // Array to store inverse of 1 to N static long[] factorialNumInverse = new long[N + 1]; // Array to precompute inverse of 1! to N! static long[] naturalNumInverse = new long[N + 1]; // Array to store factorial of first N numbers static long[] fact = new long[N + 1]; // Function to precompute inverse of numbers public static void InverseofNumber(int p) { naturalNumInverse[0] = naturalNumInverse[1] = 1; for(int i = 2; i <= N; i++) naturalNumInverse[i] = naturalNumInverse[p % i] * (long)(p - p / i) % p; } // Function to precompute inverse of factorials public static void InverseofFactorial(int p) { factorialNumInverse[0] = factorialNumInverse[1] = 1; // Precompute inverse of natural numbers for(int i = 2; i <= N; i++) factorialNumInverse[i] = (naturalNumInverse[i] * factorialNumInverse[i - 1]) % p; } // Function to calculate factorial of 1 to N public static void factorial(int p) { fact[0] = 1; // Precompute factorials for(int i = 1; i <= N; i++) { fact[i] = (fact[i - 1] * (long)i) % p; } } // Function to return nCr % p in O(1) time public static long Binomial(int N, int R, int p) { // n C r = n!*inverse(r!)*inverse((n-r)!) long ans = ((fact[N] * factorialNumInverse[R]) % p * factorialNumInverse[N - R]) % p; return ans; } static String tr(String s) { int now = 0; while (now + 1 < s.length() && s.charAt(now)== '0') ++now; return s.substring(now); } static boolean isPrime(long n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static ArrayList<Integer> commDiv(int a, int b) { // find gcd of a, b int n = gcd(a, b); // Count divisors of n. ArrayList<Integer> Div=new ArrayList<>(); for (int i = 1; i <= Math.sqrt(n); i++) { // if 'i' is factor of n if (n % i == 0) { // check if divisors are equal if (n / i == i) Div.add(i); else { Div.add(i); Div.add(n/i); } } } return Div; } static HashSet<Integer> factors(int x) { HashSet<Integer> a=new HashSet<Integer>(); for(int i=2;i*i<=x;i++) { if(x%i==0) { a.add(i); a.add(x/i); } } return a; } static void primeFactors(int n,HashSet<Integer> factors) { // Print the number of 2s that divide n while (n%2==0) { factors.add(2); n /= 2; } // n must be odd at this point. So we can // skip one element (Note i = i +2) for (int i = 3; i <= Math.sqrt(n); i+= 2) { // While i divides n, print i and divide n while (n%i == 0) { factors.add(i); n /= i; } } // This condition is to handle the case when // n is a prime number greater than 2 if (n > 2) factors.add(n); } static class Tuple{ int a; int b; int c; public Tuple(int a,int b,int c) { this.a=a; this.b=b; this.c=c; } } //function to find prime factors of n static HashMap<Long,Long> findFactors(long n2) { HashMap<Long,Long> ans=new HashMap<>(); if(n2%2==0) { ans.put(2L, 0L); // cnt++; while((n2&1)==0) { n2=n2>>1; ans.put(2L, ans.get(2L)+1); // } } for(long i=3;i*i<=n2;i+=2) { if(n2%i==0) { ans.put((long)i, 0L); // cnt++; while(n2%i==0) { n2=n2/i; ans.put((long)i, ans.get((long)i)+1); } } } if(n2!=1) { ans.put(n2, ans.getOrDefault(n2, (long) 0)+1); } return ans; } //fenwick tree implementaion static class fwt { int n; long BITree[]; fwt(int n) { this.n=n; BITree=new long[n+1]; } fwt(int arr[], int n) { this.n=n; BITree=new long[n+1]; for(int i = 0; i < n; i++) updateBIT(n, i, arr[i]); } long getSum(int index) { long sum = 0; index = index + 1; while(index>0) { sum += BITree[index]; index -= index & (-index); } return sum; } void updateBIT(int n, int index,int val) { index = index + 1; while(index <= n) { BITree[index] += val; index += index & (-index); } } long sum(int l, int r) { return getSum(r) - getSum(l - 1); } void print() { for(int i=0;i<n;i++) out.print(getSum(i)+" "); out.println(); } } static class sparseTable{ int n; long[][]dp; int log2[]; int P; void buildTable(long[] arr) { n=arr.length; P=(int)Math.floor(Math.log(n)/Math.log(2)); log2=new int[n+1]; log2[0]=log2[1]=0; for(int i=2;i<=n;i++) { log2[i]=log2[i/2]+1; } dp=new long[P+1][n]; for(int i=0;i<n;i++) { dp[0][i]=arr[i]; } for(int p=1;p<=P;p++) { for(int i=0;i+(1<<p)<=n;i++) { long left=dp[p-1][i]; long right=dp[p-1][i+(1<<(p-1))]; dp[p][i]=Math.min(left, right); } } } long maxQuery(int l,int r) { int len=r-l+1; int p=(int)Math.floor(log2[len]); long left=dp[p][l]; long right=dp[p][r-(1<<p)+1]; return Math.min(left,right); } } //Function to find number of set bits static int setBitNumber(long n) { if (n == 0) return 0; int msb = 0; n = n / 2; while (n != 0) { n = n / 2; msb++; } return msb; } static int getFirstSetBitPos(long n) { return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1; } static ArrayList<Integer> primes; static HashSet<Integer> primeSet; static boolean prime[]; static int primeCnt[]; static void sieveOfEratosthenes(int n) { prime= new boolean[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; } } // Print all prime numbers for (int i = 2; i <= n; i++) { if (prime[i] == true) primeCnt[i]=primeCnt[i-1]+1; } } static long mod(long a, long b) { long c = a % b; return (c < 0) ? c + b : c; } static void swap(long arr[],int i,int j) { long temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } static boolean util(int a,int b,int c) { if(b>a)util(b, a, c); while(c>=a) { c-=a; if(c%b==0) return true; } return (c%b==0); } static void flag(boolean flag) { out.println(flag ? "YES" : "NO"); out.flush(); } static void print(int a[]) { int n=a.length; for(int i=0;i<n;i++) { out.print(a[i]+" "); } out.println(); out.flush(); } static void print(long a[]) { int n=a.length; for(int i=0;i<n;i++) { out.print(a[i]+" "); } out.println(); out.flush(); } static void print_int(ArrayList<Integer> al) { int si=al.size(); for(int i=0;i<si;i++) { out.print(al.get(i)+" "); } out.println(); out.flush(); } static void print_long(ArrayList<Long> al) { int si=al.size(); for(int i=0;i<si;i++) { out.print(al.get(i)+" "); } out.println(); out.flush(); } static void printYesNo(boolean condition) { if (condition) { out.println("YES"); } else { out.println("NO"); } } static int LowerBound(int a[], int x) { // x is the target value or key int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]>=x) r=m; else l=m; } return r; } static int 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 static 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; } static int upperIndex(long arr[], int n, long 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; } static int UpperBound(int a[], int x) {// x is the key or target value int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]<=x) l=m; else r=m; } return l+1; } static int UpperBound(long a[], long x) {// x is the key or target value int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]<=x) l=m; else r=m; } return l+1; } static class DisjointUnionSets { int[] rank, parent; int n; // Constructor public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; this.n = n; makeSet(); } // Creates n sets with single item in each void makeSet() { for (int i = 0; i < n; i++) parent[i] = i; } int find(int x) { if (parent[x] != x) { parent[x] = find(parent[x]); } return parent[x]; } // Unites the set that includes x and the set // that includes x void union(int x, int y) { int xRoot = find(x), yRoot = find(y); if (xRoot == yRoot) return; if (rank[xRoot] < rank[yRoot]) parent[xRoot] = yRoot; else if (rank[yRoot] < rank[xRoot]) parent[yRoot] = xRoot; else // if ranks are the same { parent[yRoot] = xRoot; rank[xRoot] = rank[xRoot] + 1; } // if(xRoot!=yRoot) // parent[y]=x; } int connectedComponents() { int cnt=0; for(int i=0;i<n;i++) { if(parent[i]==i) cnt++; } return cnt; } } // static class Graph // { // int v; // ArrayList<Integer> list[]; // Graph(int v) // { // this.v=v; // list=new ArrayList[v+1]; // for(int i=1;i<=v;i++) // list[i]=new ArrayList<Integer>(); // } // void addEdge(int a, int b) // { // this.list[a].add(b); // } // // // // } static class Pair implements Comparable<Pair> { int x; int y; Pair(int x,int y) { this.x=x; this.y=y; } @Override public int compareTo(Pair o) { // TODO Auto-generated method stub return this.y-o.y; } } static class PairL implements Comparable<PairL> { long x; long y; PairL(long x,long y) { this.x=x; this.y=y; } @Override public int compareTo(PairL o) { // TODO Auto-generated method stub return (this.y>o.y)?1:-1; } } static long sum_array(int a[]) { int n=a.length; long sum=0; for(int i=0;i<n;i++) sum+=a[i]; return sum; } static long sum_array(long a[]) { int n=a.length; long sum=0; for(int i=0;i<n;i++) sum+=a[i]; return sum; } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void sort(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void reverse_array(int a[]) { int n=a.length; int i,t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } static void reverse_array(long a[]) { int n=a.length; int i; long t; for (i = 0; i < n / 2; i++) { t = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = t; } } // static long modInverse(long a, long m) // { // long g = gcd(a, m); // // return power(a, m - 2, m); // // } static long power(long x, long y) { long res = 1; x = x % mod; if (x == 0) return 0; while (y > 0) { if ((y & 1) != 0) res = (res * x) % mod; y = y >> 1; // y = y/2 x = (x * x) % mod; } return res; } static int power(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; // y = y/2 x = (x * x) % mod; } return res; } static long gcd(long a, long b) { if (a == 0) return b; //cnt+=a/b; return gcd(b%a,a); } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b%a, a); } static class FastReader{ byte[] buf = new byte[2048]; int index, total; InputStream in; FastReader(InputStream is) { in = is; } int scan() throws IOException { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) { return -1; } } return buf[index++]; } String next() throws IOException { int c; for (c = scan(); c <= 32; c = scan()); StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) { sb.append((char) c); } return sb.toString(); } int nextInt() throws IOException { int c, val = 0; for (c = scan(); c <= 32; c = scan()); boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } long nextLong() throws IOException { int c; long val = 0; for (c = scan(); c <= 32; c = scan()); boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static PrintWriter out=new PrintWriter(System.out); static int int_max=Integer.MAX_VALUE; static int int_min=Integer.MIN_VALUE; static long long_max=Long.MAX_VALUE; static long long_min=Long.MIN_VALUE; }
java
1292
B
B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0 2 4 20 OutputCopy3InputCopy1 1 2 3 1 0 15 27 26 OutputCopy2InputCopy1 1 2 3 1 0 2 2 1 OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.
[ "brute force", "constructive algorithms", "geometry", "greedy", "implementation" ]
import java.io.*; import java.util.*; public class Solution { static class node{ long x, y; public node(long x, long y) { this.x = x; this.y = y; } } public static void main(String[] args){ new Thread(null, null, "Anshum Gupta", 99999999) { public void run() { try { solve(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static final long mxx = (long)(1e18+5); static final int mxN = (int)(1e6); static final int mxV = (int)(5e5+1), log = 18; static long mod = (long)(1e9+7); //998244353;//̇ static final int INF = (int)1e9; static boolean[][]vis; static ArrayList<ArrayList<Integer>> adj; static int n, m, k, q, x, y; static long x0, y0, xs, ys, t, bx, by, ax, ay; static ArrayDeque<node> reachable; static ArrayList<node> poss; static final long limit = (long)(1e16+5); static void computeReachableNodes() { reachable = new ArrayDeque<Solution.node>(); poss = new ArrayList<node>(); reachable.add(new node(x0, y0)); poss.add(reachable.getLast()); while(reachable.getLast().x <= limit && reachable.getLast().y <= limit) { reachable.add(new node(reachable.getLast().x * ax + bx, reachable.getLast().y * ay + by)); poss.add(reachable.getLast()); } } public static void solve() throws Exception { // solve the problem here s = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out), true); // out = new PrintWriter("output.txt"); int tc = 1;//s.nextInt(); while(tc-->0){ x0 = s.nextLong(); y0 = s.nextLong(); ax = s.nextLong(); ay = s.nextLong(); bx = s.nextLong(); by = s.nextLong(); xs = s.nextLong(); ys = s.nextLong(); t = s.nextLong(); computeReachableNodes(); assert(reachable.size() == poss.size()); long ans = 0; n = reachable.size(); for(int i=0; i<n; i++) { for(int j=i; j<n; j++) { long length = poss.get(j).x - poss.get(i).x + poss.get(j).y - poss.get(i).y; long leftDistance = Math.abs(xs - poss.get(i).x) + Math.abs(ys - poss.get(i).y); long rightDistance = Math.abs(xs - poss.get(j).x) + Math.abs(ys - poss.get(j).y); if(leftDistance + length <= t || rightDistance + length <= t) { ans = Math.max(ans, j - i + 1); } } } out.println(ans); } out.flush(); out.close(); } public static PrintWriter out; public static MyScanner s; static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public MyScanner(String fileName) { try { br = new BufferedReader(new FileReader(fileName)); } catch (FileNotFoundException e) { e.printStackTrace(); } } 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[] nextIntArray(int n){ int[]a = new int[n]; for(int i=0; i<n; i++) { a[i] = this.nextInt(); } return a; } long[] nextlongArray(int n) { long[]a = new long[n]; for(int i=0; i<n; i++) { a[i] = this.nextLong(); } return a; } Integer[] nextIntegerArray(int n){ Integer[]a = new Integer[n]; for(int i=0; i<n; i++) { a[i] = this.nextInt(); } return a; } Long[] nextLongArray(int n) { Long[]a = new Long[n]; for(int i=0; i<n; i++) { a[i] = this.nextLong(); } return a; } char[][] next2DCharArray(int n, int m){ char[][]arr = new char[n][m]; for(int i=0; i<n; i++) { arr[i] = this.next().toCharArray(); } return arr; } ArrayList<ArrayList<Integer>> readUndirectedUnweightedGraph(int n, int m) { ArrayList<ArrayList<Integer>>adj = new ArrayList<ArrayList<Integer>>(); for(int i=0; i<=n; i++)adj.add(new ArrayList<Integer>()); for(int i=0; i<m; i++) { int u = s.nextInt(); int v = s.nextInt(); adj.get(u).add(v); adj.get(v).add(u); } return adj; } ArrayList<ArrayList<Integer>> readDirectedUnweightedGraph(int n, int m) { ArrayList<ArrayList<Integer>>adj = new ArrayList<ArrayList<Integer>>(); for(int i=0; i<=n; i++)adj.add(new ArrayList<Integer>()); for(int i=0; i<m; i++) { int u = s.nextInt(); int v = s.nextInt(); adj.get(u).add(v); } return adj; } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
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.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; public class JavaApplication70 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ HashSet<Integer>copy=new HashSet<Integer>(); HashSet<Integer>copy1=new HashSet<Integer>(); int n=sc.nextInt(); for(int i=0;i<n/2;i++){ copy.add(sc.nextInt()); } for(int i=n/2;i<n;i++){ copy1.add(sc.nextInt()); } copy.addAll(copy1); System.out.println(copy.size()); } } }
java
1303
B
B. National Projecttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYour company was appointed to lay new asphalt on the highway of length nn. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are gg days when the weather is good and if you lay new asphalt these days it becomes high-quality pavement; after that, the weather during the next bb days is bad, and if you lay new asphalt these days it becomes low-quality pavement; again gg good days, bb bad days and so on.You can be sure that you start repairing at the start of a good season, in other words, days 1,2,…,g1,2,…,g are good.You don't really care about the quality of the highway, you just want to make sure that at least half of the highway will have high-quality pavement. For example, if the n=5n=5 then at least 33 units of the highway should have high quality; if n=4n=4 then at least 22 units should have high quality.What is the minimum number of days is needed to finish the repair of the whole highway?InputThe first line contains a single integer TT (1≤T≤1041≤T≤104) — the number of test cases.Next TT lines contain test cases — one per line. Each line contains three integers nn, gg and bb (1≤n,g,b≤1091≤n,g,b≤109) — the length of the highway and the number of good and bad days respectively.OutputPrint TT integers — one per test case. For each test case, print the minimum number of days required to repair the whole highway if at least half of it should have high quality.ExampleInputCopy3 5 1 1 8 10 10 1000000 1 1000000 OutputCopy5 8 499999500000 NoteIn the first test case; you can just lay new asphalt each day; since days 1,3,51,3,5 are good.In the second test case, you can also lay new asphalt each day, since days 11-88 are good.
[ "math" ]
import java.io.*; import java.util.*; public class days { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine()); for(int u = 0;u < T;u++){ StringTokenizer st = new StringTokenizer(br.readLine()); long N = Long.parseLong(st.nextToken()); long G = Long.parseLong(st.nextToken()); long B = Long.parseLong(st.nextToken()); long need = N - N/2; long turn = need/G; long all = G + B; long left = need%G; if(left == 0){ turn --; left = G; } if(turn * B >= N/2 ){ System.out.println(all*turn + left); }else{ System.out.println(N); } } } }
java
1305
D
D. Kuroni and the Celebrationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem; Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with nn vertices. The tree is rooted at vertex rr, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices uu and vv, and it'll return a vertex ww, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most ⌊n2⌋⌊n2⌋ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location?InteractionThe interaction starts with reading a single integer nn (2≤n≤10002≤n≤1000), the number of vertices of the tree.Then you will read n−1n−1 lines, the ii-th of them has two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n, xi≠yixi≠yi), denoting there is an edge connecting vertices xixi and yiyi. It is guaranteed that the edges will form a tree.Then you can make queries of type "? u v" (1≤u,v≤n1≤u,v≤n) to find the lowest common ancestor of vertex uu and vv.After the query, read the result ww as an integer.In case your query is invalid or you asked more than ⌊n2⌋⌊n2⌋ queries, the program will print −1−1 and will finish interaction. You will receive a Wrong answer verdict. Make sure to exit immediately to avoid getting other verdicts.When you find out the vertex rr, print "! rr" and quit after that. This query does not count towards the ⌊n2⌋⌊n2⌋ limit.Note that the tree is fixed beforehand and will not change during the queries, i.e. the interactor is not adaptive.After printing any query do not forget to print end of line and flush the output. Otherwise, you might get Idleness limit exceeded. To do this, use: fflush(stdout) or cout.flush() in C++; System.out.flush() in Java; flush(output) in Pascal; stdout.flush() in Python; see the documentation for other languages.HacksTo hack, use the following format:The first line should contain two integers nn and rr (2≤n≤10002≤n≤1000, 1≤r≤n1≤r≤n), denoting the number of vertices and the vertex with Kuroni's hotel.The ii-th of the next n−1n−1 lines should contain two integers xixi and yiyi (1≤xi,yi≤n1≤xi,yi≤n) — denoting there is an edge connecting vertex xixi and yiyi.The edges presented should form a tree.ExampleInputCopy6 1 4 4 2 5 3 6 3 2 3 3 4 4 OutputCopy ? 5 6 ? 3 1 ? 1 2 ! 4NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test:
[ "constructive algorithms", "dfs and similar", "interactive", "trees" ]
import java.util.*; import java.io.*; public class Main { static StringBuilder sb; static dsu dsu; static long fact[]; static int mod = (int) (1e9 + 7); static ArrayList<HashSet<Integer>> graph; static HashSet<Integer> leaves; static void solve() { int n = i(); graph = new ArrayList(); leaves = new HashSet(); for(int i =0;i<n;i++) graph.add(new HashSet()); for(int i =0;i<n-1;i++){ int u = i()-1; int v = i()-1; graph.get(u).add(v); graph.get(v).add(u); } for(int i = 0;i<n;i++){ int sz = graph.get(i).size(); if(sz==1) leaves.add(i); } while(leaves.size()>1){ int u = leaves.iterator().next(); leaves.remove(u); int v = leaves.iterator().next(); leaves.remove(v); int w = query(u,v); if(w==u||w==v){ System.out.println("! "+(w+1)); System.out.flush(); return; } delete(u,w,-1); delete(v,w,-1); if(graph.get(w).size()<=1){ leaves.add(w); } } int ans = leaves.iterator().next(); System.out.println("! "+(ans+1)); System.out.flush(); } static void delete(int u,int lca,int p){ leaves.remove(u); // for(int v : graph.get(u)){ if(v==p) continue; else if(v==lca) graph.get(lca).remove(u); else delete(v,lca,u); } } static int query(int u,int v){ u++; v++; System.out.println("? "+u+" "+v); System.out.flush(); int lca = i()-1; return lca; } 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
1290
A
A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains three space-separated integers nn, mm and kk (1≤m≤n≤35001≤m≤n≤3500, 0≤k≤n−10≤k≤n−1)  — the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4 6 4 2 2 9 2 3 8 5 4 4 1 2 13 60 4 4 1 3 1 2 2 1 2 2 0 1 2 OutputCopy8 4 1 1 NoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element. the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8]; the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8]; if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element); if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44.
[ "brute force", "data structures", "implementation" ]
//some updates in import stuff 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.*; /* Always check before submitting list -> int to long conversion needed -> while loop mein break case shi ho -> extra kuch output na ho rha free fund mein */ //update this bad boi too public class Main{ static int mod = (int) (Math.pow(10, 9)+7); static final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 }; static final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 }; static final int[] dx9 = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, dy9 = { -1, 0, 1, -1, 0, 1, -1, 0, 1 }; static final double eps = 1e-10; static Set<Integer> primeNumbers = new HashSet<>(); public static void main(String[] args) throws IOException{ MyScanner sc = new MyScanner(); //changes in this line of code out = new PrintWriter(new BufferedOutputStream(System.out)); // out = new PrintWriter(new BufferedWriter(new FileWriter("output.out"))); //Write Code Below int test = sc.nextInt(); while(test --> 0){ int n = sc.nextInt(); int m = sc.nextInt(); int k = sc.nextInt(); int[] arr = new int[n]; for(int i =0; i < n; i++){ arr[i] = sc.nextInt(); } ArrayList<Integer> possible = new ArrayList<>(); if(k >= m){ //simple check (do it for all ahead elements bois) k = m-1; } for(int i = 0; i <= k; i++){ //first let's make inner boundaries bois int y = m-k-1; //the lesser this is the better bois (inner circle take away) int left = i; int right = n - (k-i+1); // out.println(left + " " + right); //so we have now ranges babyyyyy!!!! //now make one more box int si = left + y; int ei = right; int min = Integer.MAX_VALUE; while(y-- >= 0){ min = min(min, max(arr[si], arr[ei])); si--; ei--; } possible.add(min); } // out.println(possible); int ans = 0; for(int i : possible){ ans = max(ans, i); } out.println(ans); } out.close(); } //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //Updation Required //Fenwick Tree (customisable) //Segment Tree (customisable) //-----CURRENTLY PRESENT-------// //Graph //DSU //powerMODe //power //Segment Tree (work on this one) //Prime Sieve //Count Divisors //Next Permutation //Get NCR //isVowel //Sort (int) //Sort (long) //Binomial Coefficient //Pair //Triplet //lcm (int & long) //gcd (int & long) //gcd (for binomial coefficient) //swap (int & char) //reverse //SOME LATEST UPDATIONS!!! //mod_mul //mod_div //Fast input and output //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //------------------------------------------------------------------- //finding combinations in O(1) (basically the most basic logic you can think of) //not that complicated as i though it of //GRAPH (basic structure) public static class Graph{ public int V; public ArrayList<ArrayList<Integer>> edges; //2 -> [0,1,2] (current) Graph(int V){ this.V = V; edges = new ArrayList<>(V+1); for(int i= 0; i <= V; i++){ edges.add(new ArrayList<>()); } } public void addEdge(int from , int to){ edges.get(from).add(to); } } //DSU (path and rank optimised) public static class DisjointUnionSets { int[] rank, parent; int n; public DisjointUnionSets(int n) { rank = new int[n]; parent = new int[n]; Arrays.fill(rank, 1); Arrays.fill(parent,-1); this.n = n; } public int find(int curr){ if(parent[curr] == -1) return curr; //path compression optimisation return parent[curr] = find(parent[curr]); } public void union(int a, int b){ int s1 = find(a); int s2 = find(b); if(s1 != s2){ if(rank[s1] < rank[s2]){ parent[s1] = s2; rank[s2] += rank[s1]; }else{ parent[s2] = s1; rank[s1] += rank[s2]; } } } } //with mod public static long powerMOD(long x, long y) { long res = 1L; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0){ x %= mod; res %= mod; res = (res * x)%mod; } // y must be even now y = y >> 1; // y = y/2 x%= mod; x = (x * x)%mod; // Change x to x^2 } return res%mod; } //without mod public static long power(long x, long y) { long res = 1L; while (y > 0) { // If y is odd, multiply x with result if ((y & 1) != 0){ res = (res * x); } // y must be even now y = y >> 1; // y = y/ x = (x * x); } return res; } public static class segmentTree{ public long[] arr; public long[] tree; public long[] lazy; segmentTree(long[] array){ int n = array.length; arr = new long[n]; for(int i= 0; i < n; i++) arr[i] = array[i]; tree = new long[4*n + 1]; lazy = new long[4*n + 1]; } public void build(int[]arr, int s, int e, int[] tree, int index){ if(s == e){ tree[index] = arr[s]; return; } //otherwise divide in two parts and fill both sides simply int mid = (s+e)/2; build(arr, s, mid, tree, 2*index); build(arr, mid+1, e, tree, 2*index+1); //who will build the current position dude tree[index] = Math.min(tree[2*index], tree[2*index+1]); } public int query(int sr, int er, int sc, int ec, int index, int[] tree){ if(lazy[index] != 0){ tree[index] += lazy[index]; if(sc != ec){ lazy[2*index+1] += lazy[index]; lazy[2*index] += lazy[index]; } lazy[index] = 0; } //no overlap if(sr > ec || sc > er) return Integer.MAX_VALUE; //found the index baby if(sr <= sc && ec <= er) return tree[index]; //finding the index on both sides hehehehhe int mid = (sc + ec)/2; int left = query(sr, er, sc, mid, 2*index, tree); int right = query(sr, er, mid+1, ec, 2*index + 1, tree); return Integer.min(left, right); } //now we will do point update implementation //it should be simple then we expected for sure public void update(int index, int indexr, int increment, int[] tree, int s, int e){ if(lazy[index] != 0){ tree[index] += lazy[index]; if(s != e){ lazy[2*index+1] = lazy[index]; lazy[2*index] = lazy[index]; } lazy[index] = 0; } //no overlap if(indexr < s || indexr > e) return; //found the required index if(s == e){ tree[index] += increment; return; } //search for the index on both sides int mid = (s+e)/2; update(2*index, indexr, increment, tree, s, mid); update(2*index+1, indexr, increment, tree, mid+1, e); //now update the current range simply tree[index] = Math.min(tree[2*index+1], tree[2*index]); } public void rangeUpdate(int[] tree , int index, int s, int e, int sr, int er, int increment){ //if not at all in the same range if(e < sr || er < s) return; //complete then also move forward if(s == e){ tree[index] += increment; return; } //otherwise move in both subparts int mid = (s+e)/2; rangeUpdate(tree, 2*index, s, mid, sr, er, increment); rangeUpdate(tree, 2*index + 1, mid+1, e, sr, er, increment); //update current range too na //i always forget this step for some reasons hehehe, idiot tree[index] = Math.min(tree[2*index], tree[2*index + 1]); } public void rangeUpdateLazy(int[] tree, int index, int s, int e, int sr, int er, int increment){ //update lazy values //resolve lazy value before going down if(lazy[index] != 0){ tree[index] += lazy[index]; if(s != e){ lazy[2*index+1] += lazy[index]; lazy[2*index] += lazy[index]; } lazy[index] = 0; } //no overlap case if(sr > e || s > er) return; //complete overlap if(sr <= s && er >= e){ tree[index] += increment; if(s != e){ lazy[2*index+1] += increment; lazy[2*index] += increment; } return; } //otherwise go on both left and right side and do your shit int mid = (s + e)/2; rangeUpdateLazy(tree, 2*index, s, mid, sr, er, increment); rangeUpdateLazy(tree, 2*index + 1, mid+1, e, sr, er, increment); tree[index] = Math.min(tree[2*index+1], tree[2*index]); return; } } //prime sieve public static void primeSieve(int n){ BitSet bitset = new BitSet(n+1); for(long i = 0; i < n ; i++){ if (i == 0 || i == 1) { bitset.set((int) i); continue; } if(bitset.get((int) i)) continue; primeNumbers.add((int)i); for(long j = i; j <= n ; j+= i) bitset.set((int)j); } } //number of divisors // public static int countDivisors(long number){ // if(number == 1) return 1; // List<Integer> primeFactors = new ArrayList<>(); // int index = 0; // long curr = primeNumbers.get(index); // while(curr * curr <= number){ // while(number % curr == 0){ // number = number/curr; // primeFactors.add((int) curr); // } // index++; // curr = primeNumbers.get(index); // } // if(number != 1) primeFactors.add((int) number); // int current = primeFactors.get(0); // int totalDivisors = 1; // int currentCount = 2; // for (int i = 1; i < primeFactors.size(); i++) { // if (primeFactors.get(i) == current) { // currentCount++; // } else { // totalDivisors *= currentCount; // currentCount = 2; // current = primeFactors.get(i); // } // } // totalDivisors *= currentCount; // return totalDivisors; // } //now adding next permutation function to java hehe public static boolean next_permutation(int[] p) { for (int a = p.length - 2; a >= 0; --a) if (p[a] < p[a + 1]) for (int b = p.length - 1;; --b) if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } return false; } //is vowel function public static boolean isVowel(char c) { return (c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U'); } //to sort the array with better method public 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); } //sort long public 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); } //for calculating binomialCoeff public static int binomialCoeff(int n, int k) { int C[] = new int[k + 1]; // nC0 is 1 C[0] = 1; for (int i = 1; i <= n; i++) { // Compute next row of pascal // triangle using the previous row for (int j = Math.min(i, k); j > 0; j--) C[j] = C[j] + C[j - 1]; } return C[k]; } //Pair with int int public static class Pair{ public int a; public int b; Pair(int a , int b){ this.a = a; this.b = b; } @Override public String toString(){ return a + " -> " + b; } } //Triplet with int int int public static class Triplet{ public int a; public int b; public int c; Triplet(int a , int b, int c){ this.a = a; this.b = b; this.c = c; } @Override public String toString(){ return a + " -> " + b; } } //Shortcut function public static long lcm(long a , long b){ return a * (b/gcd(a,b)); } //let's make one for calculating lcm basically public static int lcm(int a , int b){ return (a * b)/gcd(a,b); } //int version for gcd public static int gcd(int a, int b){ if(b == 0) return a; return gcd(b , a%b); } //long version for gcd public static long gcd(long a, long b){ if(b == 0) return a; return gcd(b , a%b); } //for ncr calculator(ignore this code) public static long __gcd(long n1, long n2) { long gcd = 1; for (int i = 1; i <= n1 && i <= n2; ++i) { // Checks if i is factor of both integers if (n1 % i == 0 && n2 % i == 0) { gcd = i; } } return gcd; } //swapping two elements in an array public static void swap(int[] arr, int left , int right){ int temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } //for char array public static void swap(char[] arr, int left , int right){ char temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; } //reversing an array public static void reverse(int[] arr){ int left = 0; int right = arr.length-1; while(left <= right){ swap(arr, left,right); left++; right--; } } public static long expo(long a, long b, long mod) { long res = 1; while (b > 0) { if ((b & 1) == 1L) res = (res * a) % mod; //think about this one for a second a = (a * a) % mod; b = b >> 1; } return res; } //SOME EXTRA DOPE FUNCTIONS public static long mminvprime(long a, long b) { return expo(a, b - 2, b); } public static long mod_add(long a, long b, long m) { a = a % m; b = b % m; return (((a + b) % m) + m) % m; } public static long mod_sub(long a, long b, long m) { a = a % m; b = b % m; return (((a - b) % m) + m) % m; } public static long mod_mul(long a, long b, long m) { a = a % m; b = b % m; return (((a * b) % m) + m) % m; } public static long mod_div(long a, long b, long m) { a = a % m; b = b % m; return (mod_mul(a, mminvprime(b, m), m) + m) % m; } //O(n) every single time remember that public static long nCr(long N, long K , long mod){ long upper = 1L; long lower = 1L; long lowerr = 1L; for(long i = 1; i <= N; i++){ upper = mod_mul(upper, i, mod); } for(long i = 1; i <= K; i++){ lower = mod_mul(lower, i, mod); } for(long i = 1; i <= (N - K); i++){ lowerr = mod_mul(lowerr, i, mod); } // out.println(upper + " " + lower + " " + lowerr); long answer = mod_mul(lower, lowerr, mod); answer = mod_div(upper, answer, mod); return answer; } // ll *fact = new ll[2 * n + 1]; // ll *ifact = new ll[2 * n + 1]; // fact[0] = 1; // ifact[0] = 1; // for (ll i = 1; i <= 2 * n; i++) // { // fact[i] = mod_mul(fact[i - 1], i, MOD1); // ifact[i] = mminvprime(fact[i], MOD1); // } //ifact is basically inverse factorial in here!!!!!(imp) public static long combination(long n, long r, long m, long[] fact, long[] ifact) { long val1 = fact[(int)n]; long val2 = ifact[(int)(n - r)]; long val3 = ifact[(int)r]; return (((val1 * val2) % m) * val3) % m; } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } // public MyScanner() throws FileNotFoundException { // br = new BufferedReader(new FileReader("input.in")); // } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //-------------------------------------------------------- }
java
1295
B
B. Infinite Prefixestime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given string ss of length nn consisting of 0-s and 1-s. You build an infinite string tt as a concatenation of an infinite number of strings ss, or t=ssss…t=ssss… For example, if s=s= 10010, then t=t= 100101001010010...Calculate the number of prefixes of tt with balance equal to xx. The balance of some string qq is equal to cnt0,q−cnt1,qcnt0,q−cnt1,q, where cnt0,qcnt0,q is the number of occurrences of 0 in qq, and cnt1,qcnt1,q is the number of occurrences of 1 in qq. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".InputThe first line contains the single integer TT (1≤T≤1001≤T≤100) — the number of test cases.Next 2T2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers nn and xx (1≤n≤1051≤n≤105, −109≤x≤109−109≤x≤109) — the length of string ss and the desired balance, respectively.The second line contains the binary string ss (|s|=n|s|=n, si∈{0,1}si∈{0,1}).It's guaranteed that the total sum of nn doesn't exceed 105105.OutputPrint TT integers — one per test case. For each test case print the number of prefixes or −1−1 if there is an infinite number of such prefixes.ExampleInputCopy4 6 10 010010 5 3 10101 1 0 0 2 0 01 OutputCopy3 0 1 -1 NoteIn the first test case; there are 3 good prefixes of tt: with length 2828, 3030 and 3232.
[ "math", "strings" ]
import java.io.*; import java.math.*; import java.util.*; // @author : Dinosparton public class test { static class Pair{ long x; long y; Pair(long x,long y){ this.x = x; this.y = y; } } static class Compare { void compare(Pair arr[], int n) { // Comparator to sort the pair according to second element Arrays.sort(arr, new Comparator<Pair>() { @Override public int compare(Pair p1, Pair p2) { if(p1.x!=p2.x) { return (int)(p1.x - p2.x); } else { return (int)(p1.y - p2.y); } } }); // for (int i = 0; i < n; i++) { // System.out.print(arr[i].x + " " + arr[i].y + " "); // } // System.out.println(); } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String args[]) throws Exception { Scanner sc = new Scanner(); StringBuilder res = new StringBuilder(); int tc = sc.nextInt(); while(tc-->0) { int n = sc.nextInt(); long x = sc.nextLong(); String s = sc.next(); int cnt = 0; for(int i=0;i<n;i++) { if(s.charAt(i)=='0') { cnt++; } else { cnt--; } } int ans = 0; int bal = 0; for(int i=0;i<n;i++) { if(cnt == 0) { if(bal == x) { ans = -1; break; } } else if(Math.abs(x - bal)%Math.abs(cnt) == 0 && (x-bal)/cnt>=0) { ans++; } if(s.charAt(i)=='0') { bal++; } else { bal--; } } res.append(ans+"\n"); } System.out.println(res); } }
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" ]
//package Educational_Codeforces_Round_83; import java.util.Scanner; public class Main//C_Adding_Powers { public static void main(String[] args) { Scanner input=new Scanner(System.in); int T=input.nextInt(); for(int t=1;t<=T;t++) { int n=input.nextInt(); int k=input.nextInt(); long[] a=new long[35]; for(int i=1;i<=n;i++) a[i]=input.nextLong(); long[] pos=new long[105]; boolean flag=true; for(long e:a) { int cnt=0; while(e!=0) { pos[cnt]+=e%k; if(pos[cnt]>1) { flag=false; break; } e/=k; cnt++; } if(!flag) break; } if(flag==true) System.out.println("YES"); else System.out.println("NO"); } input.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.util.*; public class Lesson4YetAnotherMemeProblem { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int cases = scan.nextInt(); while (cases-- > 0) { long A = scan.nextLong(); long B = scan.nextLong(); long count = 0; for(int i=10;i<=(B+1);i*=10) { count++; } System.out.println(count * A); } } }
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.util.ArrayList; import java.util.HashSet; import java.util.Random; import java.util.Scanner; public class Main { private static final int TRY_MAX = 10; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = scanner.nextLong(); } shuffleArray(a); //сперва посчитаем для 2 и 3 HashSet<Long> checked = new HashSet<>(); long count2 = greedyCount(a, 2, n + 1); long count3 = greedyCount(a, 3, n + 1); int currentMin = (int) count2; if (count3 >= 0 && count3 < count2) { currentMin = (int) count3; } checked.add(2L); checked.add(3L); int currentTry = 0; final int maxTry = Math.min(TRY_MAX, n); while (currentMin != 0 && currentTry < maxTry) { for (int i = -1; i <= 1; i++) { ArrayList<Long> primes = factorization(a[currentTry] + i); for (long prime : primes) { if (checked.add(prime)) { long greedyCount = greedyCount(a, prime, currentMin); if (greedyCount >= 0 && greedyCount < currentMin) { currentMin = (int) greedyCount; if(currentMin==0){ System.out.println(0); return; } } } } } currentTry++; } System.out.println(currentMin); } public static ArrayList<Long> factorization(long x) { ArrayList<Long> primes = new ArrayList<>(); int limit = (int) Math.sqrt(x); for (int i = 2; i <= limit; i++) { if (x % i == 0) { primes.add((long) i); while (x % i == 0) { x /= i; limit = (int) Math.sqrt(x); } } } if (x > 1) primes.add(x); return primes; } public static long greedyCount(long[] a, long p, int stopValue) { int n = a.length; long result = 0; for (int i = 0; i < n; i++) { if (a[i] < p) result += (p - a[i]); else { long remainder = a[i] % p; result += Math.min(remainder, p - remainder); } if (stopValue <= result) return -1; } return result; } public static <T> void shuffleArray(T[] array) { Random random = new Random(); int n = array.length; for (int i = n - 1; i > 0; i--) { int j = random.nextInt(i + 1); T tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } public static void shuffleArray(long[] array) { Random random = new Random(); int n = array.length; for (int i = n - 1; i > 0; i--) { int j = random.nextInt(i + 1); long tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } }
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.util.*; import java.io.*; public class Y{ final static int M=(1<<20); static long[] t1=new long[M*2+5]; static long[] t2=new long[M*2+5]; static long[] ca=new long[M], cb=new long[M]; static long ans; static int n,m,p,x,i,j; static long y; public static void upd(int i){ t1[i]=t1[i<<1]+t1[i<<1|1]; t2[i]=Math.max(t2[i<<1],t1[i<<1]+t2[i<<1|1]); } public static void add(int i,int v){ for(t1[i+=M]+=v;(i>>=1)>0;upd(i)); } public static void main(String[] args) throws IOException{ Reader in = new Reader(); long Z= 1; Z<<=60; for(i=0;i<M;++i)ca[i]=cb[i]=Z;ans=-Z; n=in.nextInt();m=in.nextInt();p=in.nextInt(); mons[] a = new mons[p+1];a[0]=new mons(0, 0, 0); for(i=1;i<=n;++i){x=in.nextInt();y=in.nextLong();ca[x]=Math.min(ca[x],y);} for(i=1;i<=m;++i){x=in.nextInt();y=in.nextLong();cb[x]=Math.min(cb[x],y);} for(i=0;i<M;++i)t2[i+M]=-cb[i];for(i=M-1;i!=0;--i)upd(i); for(i=1;i<=p;++i){a[i]= new mons(in.nextInt(),in.nextInt(),in.nextInt());} Arrays.sort(a); for(i=0,j=1;i<M;++i){ for(;j<=p && a[j].x<i;++j)add(a[j].y,a[j].z); ans=Math.max(ans,t2[1]-ca[i]); } System.out.println(ans); in.close(); } static class Reader{ final private int S = (1<<16); private int bp,br; private byte[] buff; private DataInputStream din; public Reader(){ din = new DataInputStream(System.in); bp=br=0;buff= new byte[S]; } private void fill() throws IOException{ br = din.read(buff,bp=0,S); if(br==-1)buff[0]=-1; } private byte read() throws IOException{ if(bp==br)fill(); return buff[bp++]; } 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 void close() throws IOException { if(din==null)return; din.close(); } } } class mons implements Comparable<mons>{ int x,y,z; public mons(int x,int y, int z){ this.x=x;this.y=y;this.z=z; } @Override public int compareTo(mons o) { if(x>o.x){return 1;} if(x<o.x){return -1;} return 0; } }
java
1324
A
A. Yet Another Tetris Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given some Tetris field consisting of nn columns. The initial height of the ii-th column of the field is aiai blocks. On top of these columns you can place only figures of size 2×12×1 (i.e. the height of this figure is 22 blocks and the width of this figure is 11 block). Note that you cannot rotate these figures.Your task is to say if you can clear the whole field by placing such figures.More formally, the problem can be described like this:The following process occurs while at least one aiai is greater than 00: You place one figure 2×12×1 (choose some ii from 11 to nn and replace aiai with ai+2ai+2); then, while all aiai are greater than zero, replace each aiai with ai−1ai−1. And your task is to determine if it is possible to clear the whole field (i.e. finish the described process), choosing the places for new figures properly.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The next 2t2t lines describe test cases. The first line of the test case contains one integer nn (1≤n≤1001≤n≤100) — the number of columns in the Tetris field. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100), where aiai is the initial height of the ii-th column of the Tetris field.OutputFor each test case, print the answer — "YES" (without quotes) if you can clear the whole Tetris field and "NO" otherwise.ExampleInputCopy4 3 1 1 3 4 1 1 2 1 2 11 11 1 100 OutputCopyYES NO YES YES NoteThe first test case of the example field is shown below:Gray lines are bounds of the Tetris field. Note that the field has no upper bound.One of the correct answers is to first place the figure in the first column. Then after the second step of the process; the field becomes [2,0,2][2,0,2]. Then place the figure in the second column and after the second step of the process, the field becomes [0,0,0][0,0,0].And the second test case of the example field is shown below:It can be shown that you cannot do anything to end the process.In the third test case of the example, you first place the figure in the second column after the second step of the process, the field becomes [0,2][0,2]. Then place the figure in the first column and after the second step of the process, the field becomes [0,0][0,0].In the fourth test case of the example, place the figure in the first column, then the field becomes [102][102] after the first step of the process, and then the field becomes [0][0] after the second step of the process.
[ "implementation", "number theory" ]
import java.util.*; import java.io.*; public class yetAnotherTetrisProblem { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // try { // scanner = new Scanner(new FileInputStream("input.txt")); // } // catch (Exception e) { // System.out.println("Error"); // } int t = scanner.nextInt(); for (int x = 0; x < t; x++) { int n = scanner.nextInt(); int odds = 0; for (int i = 0; i < n; i++) { if (scanner.nextInt() % 2 != 1) { odds++; } } if (odds == n || odds == 0) { System.out.println("YES"); } else { System.out.println("NO"); } } } }
java
1307
C
C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1≤|s|≤1051≤|s|≤105) — the text that Bessie intercepted.OutputOutput a single integer  — the number of occurrences of the secret message.ExamplesInputCopyaaabb OutputCopy6 InputCopyusaco OutputCopy1 InputCopylol OutputCopy2 NoteIn the first example; these are all the hidden strings and their indice sets: a occurs at (1)(1), (2)(2), (3)(3) b occurs at (4)(4), (5)(5) ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5) aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3) bb occurs at (4,5)(4,5) aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4) aaa occurs at (1,2,3)(1,2,3) abb occurs at (3,4,5)(3,4,5) aaab occurs at (1,2,3,4)(1,2,3,4) aabb occurs at (2,3,4,5)(2,3,4,5) aaabb occurs at (1,2,3,4,5)(1,2,3,4,5) Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.
[ "brute force", "dp", "math", "strings" ]
import java.io.*; import java.math.*; import java.util.*; public class C_Cow_and_Message { public static void main(String[] args)throws Exception { new Solver().solve(); } } //* Success is not final, failure is not fatal: it is the courage to continue that counts. class Solver { void solve() throws Exception { String S = sc.next(); int n = S.length(); // System.out.println(n); long[][] dp = new long[n][26]; int[] last = new int[26]; long[] count = new long[26]; Arrays.fill(last, -1); long max = 0; for(int i =0;i<n;i++){ int c = S.charAt(i)-'a'; for(int j = 0;j<26;j++){ dp[i][j] = count[j]; if(last[c]!=-1){ dp[i][j] += dp[last[c]][j]; } max = Math.max(dp[i][j],max); } count[c]++; last[c] = i; // sc.printArray(last); // sc.printArray(count); } // for(int i =0;i<n;i++){ // for(int j = 0;j<26;j++){ // System.out.print(dp[i][j]+" "); // } // System.out.println(); // System.out.println(); // } // we just now need to print the max and the value of the // System.out.println(max); System.out.println(Math.max(sc.max(count),max)); sc.flush(); } final Helper sc; final int MAXN = 1000_006; final long MOD = (long) 1e9 + 7; Solver() { sc = new Helper(MOD, MAXN); sc.initIO(System.in, System.out); } } class Helper { final long MOD; final int MAXN; final Random rnd; public Helper(long mod, int maxn) { MOD = mod; MAXN = maxn; rnd = new Random(); } public static int[] sieve; public static ArrayList<Integer> primes; public void setSieve() { primes = new ArrayList<>(); sieve = new int[MAXN]; int i, j; for (i = 2; i*i < MAXN; ++i) if (sieve[i] == 0) { primes.add(i); for (j = i*i; j < MAXN; j += i) { sieve[j] = i; } } } public static long[] factorial; public void setFactorial() { factorial = new long[MAXN]; factorial[0] = 1; for (int i = 1; i < MAXN; ++i) factorial[i] = factorial[i - 1] * i % MOD; } public long getFactorial(int n) { if (factorial == null) setFactorial(); return factorial[n]; } public long ncr(int n, int r) { if (r > n) return 0; if (factorial == null) setFactorial(); long numerator = factorial[n]; long denominator = factorial[r] * factorial[n - r] % MOD; return numerator * pow(denominator, MOD - 2, MOD) % MOD; } public long[] getLongArray(int size) throws Exception { long[] ar = new long[size]; for (int i = 0; i < size; ++i) ar[i] = nextLong(); return ar; } public int[] getIntArray(int size) throws Exception { int[] ar = new int[size]; for (int i = 0; i < size; ++i) ar[i] = nextInt(); return ar; } public long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } public int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } public long max(long[] ar) { long ret = ar[0]; for (long itr : ar) ret = Math.max(ret, itr); return ret; } public int max(int[] ar) { int ret = ar[0]; for (int itr : ar) ret = Math.max(ret, itr); return ret; } public long min(long[] ar) { long ret = ar[0]; for (long itr : ar) ret = Math.min(ret, itr); return ret; } public int min(int[] ar) { int ret = ar[0]; for (int itr : ar) ret = Math.min(ret, itr); return ret; } public long sum(long[] ar) { long sum = 0; for (long itr : ar) sum += itr; return sum; } public long sum(int[] ar) { long sum = 0; for (int itr : ar) sum += itr; return sum; } public void shuffle(int[] ar) { int r; for (int i = 0; i < ar.length; ++i) { r = rnd.nextInt(ar.length); if (r != i) { ar[i] ^= ar[r]; ar[r] ^= ar[i]; ar[i] ^= ar[r]; } } } public void shuffle(long[] ar) { int r; for (int i = 0; i < ar.length; ++i) { r = rnd.nextInt(ar.length); if (r != i) { ar[i] ^= ar[r]; ar[r] ^= ar[i]; ar[i] ^= ar[r]; } } } public long pow(long base, long exp, long MOD) { base %= MOD; long ret = 1; while (exp > 0) { if ((exp & 1) == 1) ret = ret * base % MOD; base = base * base % MOD; exp >>= 1; } return ret; } static byte[] buf = new byte[1000_006]; static int index, total; static InputStream in; static BufferedWriter bw; public void initIO(InputStream is, OutputStream os) { try { in = is; bw = new BufferedWriter(new OutputStreamWriter(os)); } catch (Exception e) { } } public void initIO(String inputFile, String outputFile) { try { in = new FileInputStream(inputFile); bw = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(outputFile))); } catch (Exception e) { } } private int scan() throws Exception { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) return -1; } return buf[index++]; } public String nextLine() throws Exception { 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(); } public String next() throws Exception { 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(); } public int nextInt() throws Exception { 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; } public long nextLong() throws Exception { 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 void print(Object a) throws Exception { bw.write(a.toString()); } public void printsp(Object a) throws Exception { print(a); print(" "); } public void println() throws Exception { bw.write("\n"); } public void printArray(int[] arr) throws Exception{ for(int i = 0;i<arr.length;i++){ print(arr[i]+ " "); } println(); } public void println(Object a) throws Exception { print(a); println(); } public void flush() throws Exception { bw.flush(); } }
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.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int tc = 0; tc < t; ++tc) { String s = sc.next(); System.out.println(solve(s)); } sc.close(); } static int solve(String s) { int leftIndex = s.indexOf('1'); if (leftIndex == -1) { return 0; } return (int) s.substring(leftIndex, s.lastIndexOf('1') + 1).chars().filter(ch -> ch == '0').count(); } }
java
1303
C
C. Perfect Keyboardtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputPolycarp wants to assemble his own keyboard. Layouts with multiple rows are too complicated for him — his keyboard will consist of only one row; where all 2626 lowercase Latin letters will be arranged in some order.Polycarp uses the same password ss on all websites where he is registered (it is bad, but he doesn't care). He wants to assemble a keyboard that will allow to type this password very easily. He doesn't like to move his fingers while typing the password, so, for each pair of adjacent characters in ss, they should be adjacent on the keyboard. For example, if the password is abacaba, then the layout cabdefghi... is perfect, since characters a and c are adjacent on the keyboard, and a and b are adjacent on the keyboard. It is guaranteed that there are no two adjacent equal characters in ss, so, for example, the password cannot be password (two characters s are adjacent).Can you help Polycarp with choosing the perfect layout of the keyboard, if it is possible?InputThe first line contains one integer TT (1≤T≤10001≤T≤1000) — the number of test cases.Then TT lines follow, each containing one string ss (1≤|s|≤2001≤|s|≤200) representing the test case. ss consists of lowercase Latin letters only. There are no two adjacent equal characters in ss.OutputFor each test case, do the following: if it is impossible to assemble a perfect keyboard, print NO (in upper case, it matters in this problem); otherwise, print YES (in upper case), and then a string consisting of 2626 lowercase Latin letters — the perfect layout. Each Latin letter should appear in this string exactly once. If there are multiple answers, print any of them. ExampleInputCopy5 ababa codedoca abcda zxzytyz abcdefghijklmnopqrstuvwxyza OutputCopyYES bacdefghijklmnopqrstuvwxyz YES edocabfghijklmnpqrstuvwxyz NO YES xzytabcdefghijklmnopqrsuvw NO
[ "dfs and similar", "greedy", "implementation" ]
import java.util.HashSet; import java.util.Scanner; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Main { static final int ALPHABET_SIZE = 26; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for (int tc = 0; tc < T; ++tc) { String s = sc.next(); System.out.println(solve(s)); } sc.close(); } static String solve(String s) { @SuppressWarnings("unchecked") Set<Integer>[] adjSets = new Set[ALPHABET_SIZE]; for (int i = 0; i < adjSets.length; ++i) { adjSets[i] = new HashSet<>(); } for (int i = 0; i < s.length() - 1; ++i) { int index1 = s.charAt(i) - 'a'; int index2 = s.charAt(i + 1) - 'a'; adjSets[index1].add(index2); adjSets[index2].add(index1); } StringBuilder layout = new StringBuilder( IntStream.range(0, adjSets.length) .filter(i -> adjSets[i].isEmpty()) .mapToObj(i -> String.valueOf((char) (i + 'a'))) .collect(Collectors.joining())); boolean[] visited = new boolean[adjSets.length]; int[] begins = IntStream.range(0, adjSets.length).filter(i -> adjSets[i].size() == 1).toArray(); for (int begin : begins) { if (!visited[begin]) { visited[begin] = true; layout.append((char) (begin + 'a')); int current = begin; while (!adjSets[current].isEmpty()) { int next = adjSets[current].iterator().next(); adjSets[next].remove(current); current = next; if (visited[current]) { return "NO"; } visited[current] = true; layout.append((char) (current + 'a')); } } } return (layout.length() == ALPHABET_SIZE) ? String.format("YES\n%s", layout) : "NO"; } }
java
1299
B
B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4 1 0 4 1 3 4 0 3 OutputCopyYESInputCopy3 100 86 50 0 150 0 OutputCopynOInputCopy8 0 0 1 0 2 1 3 3 4 6 3 6 2 5 1 3 OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements.
[ "geometry" ]
import java.util.*; import java.io.*; public class B618 { public static void main(String [] args) { MyScanner sc = new MyScanner(); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); int [][] points = new int [n+1][2]; for (int i = 1; i <= n; i++) { int a = sc.nextInt(); int b = sc.nextInt(); points[i][0] = a; points[i][1] = b; } if (n % 2 == 1) { out.println("NO"); } else { int mid_x = (points[n/2][0] + points[n][0]); int mid_y = (points[n/2][1] + points[n][1]); boolean good = true; for (int i = 1; i < n / 2; i++) { int x = (points[i][0] + points[i+n/2][0]); int y = (points[i][1] + points[i + n/2][1]); if (x == mid_x && y == mid_y) { continue; } else { good = false; break; } } if (good) out.println("YES"); else out.println("NO"); } 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
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; public class CF1212{ public static void main(String[] args) throws IOException{ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); reader.readLine(); String[] robotIncScore = reader.readLine().split(" "); String[] bionicSolverScore = reader.readLine().split(" "); System.out.println(getMaxScoreAllowed(robotIncScore, bionicSolverScore)); } public static int getMaxScoreAllowed(String[] robotIncScore, String[] bionicSolverScore){ int totalQuestionsSolvesByRobotInc = 0; int totalQuestionsSolvesByBionicSolver = 0; for(int i=0; i<robotIncScore.length; i++){ int robotIncCurrentScore = Integer.parseInt(robotIncScore[i]); int bionicSolverCurrentScore = Integer.parseInt(bionicSolverScore[i]); if(robotIncCurrentScore == 1 && bionicSolverCurrentScore == 0){ totalQuestionsSolvesByRobotInc++; }else if(robotIncCurrentScore == 0 && bionicSolverCurrentScore == 1){ totalQuestionsSolvesByBionicSolver++; } } if( totalQuestionsSolvesByRobotInc == 0 || (totalQuestionsSolvesByBionicSolver == totalQuestionsSolvesByRobotInc && totalQuestionsSolvesByRobotInc == robotIncScore.length) ){ return -1; } if(totalQuestionsSolvesByBionicSolver == totalQuestionsSolvesByRobotInc){ return 2; }else if(totalQuestionsSolvesByRobotInc > totalQuestionsSolvesByBionicSolver){ return 1; } totalQuestionsSolvesByBionicSolver++; return totalQuestionsSolvesByBionicSolver/totalQuestionsSolvesByRobotInc + ((totalQuestionsSolvesByBionicSolver%totalQuestionsSolvesByRobotInc==0)?0:1); } }
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.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.StringTokenizer; public class ConneR_ARCMarklandN { 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 s = Integer.parseInt(st.nextToken()); var k = Integer.parseInt(st.nextToken()); var hashSet = new HashSet<Integer>(); st = new StringTokenizer(r.readLine()); for (int j = 0; j < k; j++) { hashSet.add(Integer.parseInt(st.nextToken())); } var minRight = -1; for (int j = s; j <= n; j++) { if (hashSet.add(j)) { minRight = j-s; break; } } var minLeft = -1; for (int j = s; j >0; j--) { if (hashSet.add(j)) { minLeft = s-j; break; } } if (minRight==-1) { System.out.println(minLeft); } else if(minLeft==-1) { System.out.println(minRight); } else { System.out.println(Math.min(minRight,minLeft)); } } } }
java
1320
C
C. World of Darkraft: Battle for Azathothtime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputRoma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind.Roma has a choice to buy exactly one of nn different weapons and exactly one of mm different armor sets. Weapon ii has attack modifier aiai and is worth caicai coins, and armor set jj has defense modifier bjbj and is worth cbjcbj coins.After choosing his equipment Roma can proceed to defeat some monsters. There are pp monsters he can try to defeat. Monster kk has defense xkxk, attack ykyk and possesses zkzk coins. Roma can defeat a monster if his weapon's attack modifier is larger than the monster's defense, and his armor set's defense modifier is larger than the monster's attack. That is, a monster kk can be defeated with a weapon ii and an armor set jj if ai>xkai>xk and bj>ykbj>yk. After defeating the monster, Roma takes all the coins from them. During the grind, Roma can defeat as many monsters as he likes. Monsters do not respawn, thus each monster can be defeated at most one.Thanks to Roma's excessive donations, we can assume that he has an infinite amount of in-game currency and can afford any of the weapons and armor sets. Still, he wants to maximize the profit of the grind. The profit is defined as the total coins obtained from all defeated monsters minus the cost of his equipment. Note that Roma must purchase a weapon and an armor set even if he can not cover their cost with obtained coins.Help Roma find the maximum profit of the grind.InputThe first line contains three integers nn, mm, and pp (1≤n,m,p≤2⋅1051≤n,m,p≤2⋅105) — the number of available weapons, armor sets and monsters respectively.The following nn lines describe available weapons. The ii-th of these lines contains two integers aiai and caicai (1≤ai≤1061≤ai≤106, 1≤cai≤1091≤cai≤109) — the attack modifier and the cost of the weapon ii.The following mm lines describe available armor sets. The jj-th of these lines contains two integers bjbj and cbjcbj (1≤bj≤1061≤bj≤106, 1≤cbj≤1091≤cbj≤109) — the defense modifier and the cost of the armor set jj.The following pp lines describe monsters. The kk-th of these lines contains three integers xk,yk,zkxk,yk,zk (1≤xk,yk≤1061≤xk,yk≤106, 1≤zk≤1031≤zk≤103) — defense, attack and the number of coins of the monster kk.OutputPrint a single integer — the maximum profit of the grind.ExampleInputCopy2 3 3 2 3 4 7 2 4 3 2 5 11 1 2 4 2 1 6 3 4 6 OutputCopy1
[ "brute force", "data structures", "sortings" ]
import java.io.*; import java.util.*; public class Main{ static public class SegmentTree { // 1-based DS, OOP int N; //the number of elements in the array as a power of 2 (i.e. after padding) long[] array, sTree, lazy; SegmentTree(long[] in) { array = in; N = in.length - 1; sTree = new long[N<<1]; //no. of nodes = 2*N - 1, we add one to cross out index zero lazy = new long[N<<1]; build(1,1,N); } void build(int node, int b, int e) // O(n) { if(b == e) sTree[node] = array[b]; else { int mid = b + e >> 1; build(node<<1,b,mid); build(node<<1|1,mid+1,e); sTree[node] = Math.max(sTree[node<<1],sTree[node<<1|1]); } } void update_range(int i, int j, int val) // O(log n) { update_range(1,1,N,i,j,val); } void update_range(int node, int b, int e, int i, int j, int val) { if(i > e || j < b) return; if(b >= i && e <= j) { sTree[node] += val; lazy[node] += val; } else { int mid = b + e >> 1; propagate(node, b, mid, e); update_range(node<<1,b,mid,i,j,val); update_range(node<<1|1,mid+1,e,i,j,val); sTree[node] = Math.max(sTree[node<<1],sTree[node<<1|1]); } } void propagate(int node, int b, int mid, int e) { lazy[node<<1] += lazy[node]; lazy[node<<1|1] += lazy[node]; sTree[node<<1] += lazy[node]; sTree[node<<1|1] += lazy[node]; lazy[node] = 0; } long query(int i, int j) { return query(1,1,N,i,j); } long query(int node, int b, int e, int i, int j) // O(log n) { if(i>e || j <b) return -inf; if(b>= i && e <= j) return sTree[node]; int mid = b + e >> 1; propagate(node, b, mid, e); long q1 = query(node<<1,b,mid,i,j); long q2 = query(node<<1|1,mid+1,e,i,j); return Math.max(q1, q2); } } static long inf=(long)3e9; public static void main(String[] args) throws IOException { MScanner sc=new MScanner(System.in); PrintWriter pw=new PrintWriter(System.out); int n=sc.nextInt(),m=sc.nextInt(),p=sc.nextInt(); int[][]weapons=new int[n][2],armors=new int[m][2],monsters=new int[p][3]; for(int i=0;i<n;i++) { weapons[i]=sc.takearr(2); } for(int i=0;i<m;i++) { armors[i]=sc.takearr(2); } for(int i=0;i<p;i++) { monsters[i]=sc.takearr(3); } Arrays.sort(weapons,(x,y) -> x[0]-y[0]); Arrays.sort(armors,(x,y) -> x[0]-y[0]); Arrays.sort(monsters,(x,y) -> x[0]-y[0]); int N = 1; while(N < m) N <<= 1; //padding long[]armorCosts=new long[N+1]; for(int i=1;i<=m;i++) { armorCosts[i]=-armors[i-1][1]; } SegmentTree st=new SegmentTree(armorCosts); int lastMonster=0; long ans=-inf; for(int i=0;i<n;i++) { while(lastMonster<p && monsters[lastMonster][0]<weapons[i][0]) { int firstArmor=-1; int lo=0,hi=m-1; while(lo<=hi) { int mid=(lo+hi)>>1; if(armors[mid][0]>monsters[lastMonster][1]) { firstArmor=mid; hi=mid-1; } else { lo=mid+1; } } lastMonster++; if(firstArmor==-1)continue; st.update_range(firstArmor+1, m, monsters[lastMonster-1][2]); } ans=Math.max(ans, st.query(1, m)-weapons[i][1]); } 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
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.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; import java.util.TreeSet; public class Main { static ArrayList<Integer> adj[]; static PrintWriter out = new PrintWriter(System.out); public static int mod = 1000000007; static int notmemo[][][]; static int k; static long a[]; static int b[]; static int m; static char c[]; static int trace[]; static int h; static int x; static int ans1; static int ans2; static char t[]; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int t1=sc.nextInt(); label:while(t1-->0) { c=sc.next().toCharArray(); t=sc.next().toCharArray(); notmemo=new int[c.length+1][t.length+1][t.length+1]; for (int i = 0; i < notmemo.length; i++) { for (int j = 0; j < notmemo[i].length; j++) { Arrays.fill(notmemo[i][j],-1); } } for (int i = 0; i <=t.length; i++) { if(dp(0,0,i)==i){ System.out.println("YES"); continue label; } } System.out.println("NO"); } } public static int dp(int i, int j, int idx) { if(i==c.length) { if(idx==t.length) return 0; return (int) -1e9; } if(notmemo[i][j][idx]!=-1) { return notmemo[i][j][idx]; } int take=(int) -1e9; int take1=(int) -1e9; if(j<t.length&&c[i]==t[j]) { take=1+dp(i+1,j+1,idx); } if(idx<t.length&&c[i]==t[idx]) { take1=dp(i+1,j,idx+1); } int leave=dp(i+1,j,idx); return notmemo[i][j][idx]=Math.max(take1, Math.max(leave,take)); } static class book implements Comparable<book> { int idx; long score; public book(int i, long s) { idx = i; score = s; } public int compareTo(book o) { return (int) (o.score - score); } } static class library implements Comparable<library> { int numofbooks; int signup; int shiprate; int idx; public library(int a, int b, int c, int idx) { numofbooks = a; signup = b; shiprate = c; this.idx = idx; } @Override public int compareTo(library o) { if(signup==o.signup) { return o.numofbooks-numofbooks; } return signup - o.signup; } } static boolean isPal(String s) { int j = s.length() - 1; c = s.toCharArray(); Arrays.sort(c); for (int i = 0; i < c.length; i++) { } return true; } static String s; static boolean isOn(int S, int j) { return (S & 1 << j) != 0; } static int y, d; static void extendedEuclid(int a, int b) { if (b == 0) { x = 1; y = 0; d = a; return; } extendedEuclid(b, a % b); int x1 = y; int y1 = x - a / b * y; x = x1; y = y1; } static boolean f = true; static class SegmentTree { // 1-based DS, OOP int N; // the number of elements in the array as a power of 2 (i.e. after padding) int[] array, sTree, lazy; SegmentTree(int[] in) { array = in; N = in.length - 1; sTree = new int[N << 1]; // no. of nodes = 2*N - 1, we add one to cross out index zero lazy = new int[N << 1]; build(1, 1, N); } void build(int node, int b, int e) // O(n) { if (b == e) sTree[node] = array[b]; else { int mid = b + e >> 1; build(node << 1, b, mid); build(node << 1 | 1, mid + 1, e); sTree[node] = sTree[node << 1] + sTree[node << 1 | 1]; } } void update_point(int index, int val) // O(log n) { index += N - 1; sTree[index] += val; while (index > 1) { index >>= 1; sTree[index] = Math.max(sTree[index << 1], sTree[index << 1 | 1]); } } void update_range(int i, int j, int val) // O(log n) { update_range(1, 1, N, i, j, val); } void update_range(int node, int b, int e, int i, int j, int val) { if (i > e || j < b) return; if (b >= i && e <= j) { sTree[node] += (e - b + 1) * val; lazy[node] += val; } else { int mid = b + e >> 1; propagate(node, b, mid, e); update_range(node << 1, b, mid, i, j, val); update_range(node << 1 | 1, mid + 1, e, i, j, val); sTree[node] = sTree[node << 1] + sTree[node << 1 | 1]; } } void propagate(int node, int b, int mid, int e) { lazy[node << 1] += lazy[node]; lazy[node << 1 | 1] += lazy[node]; sTree[node << 1] += (mid - b + 1) * lazy[node]; sTree[node << 1 | 1] += (e - mid) * lazy[node]; lazy[node] = 0; } int query(int i, int j) { return query(1, 1, N, i, j); } int query(int node, int b, int e, int i, int j) // O(log n) { if (i > e || j < b) return 0; if (b >= i && e <= j) return sTree[node]; int mid = b + e >> 1; // propagate(node, b, mid, e); int q1 = query(node << 1, b, mid, i, j); int q2 = query(node << 1 | 1, mid + 1, e, i, j); return Math.max(q1, q2); } } static int memo[][]; static long nCr1(int n, int k) { if (n < k) return 0; if (k == 0 || k == n) return 1; if (comb[n][k] != -1) return comb[n][k]; if (n - k < k) return comb[n][k] = nCr1(n, n - k); return comb[n][k] = ((nCr1(n - 1, k - 1) % mod) + (nCr1(n - 1, k) % mod)) % mod; } static class UnionFind { int[] p, rank, setSize; int numSets; int max[]; public UnionFind(int N) { max = new int[N]; p = new int[numSets = N]; rank = new int[N]; setSize = new int[N]; for (int i = 0; i < N; i++) { p[i] = i; setSize[i] = 1; max[i] = i; } } public int findSet(int i) { return p[i] == i ? i : (p[i] = findSet(p[i])); } public boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); } public void unionSet(int i, int j) { if (isSameSet(i, j)) return; numSets--; int x = findSet(i), y = findSet(j); if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; max[x] = Math.max(max[x], max[y]); } else { p[x] = y; setSize[y] += setSize[x]; if (rank[x] == rank[y]) rank[y]++; max[y] = Math.max(max[x], max[y]); } } private int getmax(int j) { return max[findSet(j)]; } public int numDisjointSets() { return numSets; } public int sizeOfSet(int i) { return setSize[findSet(i)]; } } /** * private static void trace(int i, int time) { if(i==n) return; * * * long ans=dp(i,time); * if(time+a[i].t<a[i].burn&&(ans==dp(i+1,time+a[i].t)+a[i].cost)) { * * trace(i+1, time+a[i].t); * * l1.add(a[i].idx); return; } trace(i+1,time); * * } **/ static class incpair implements Comparable<incpair> { int a; long b; int idx; incpair(int a, long dirg, int i) { this.a = a; b = dirg; idx = i; } public int compareTo(incpair e) { return (int) (b - e.b); } } static class decpair implements Comparable<decpair> { int a; long b; int idx; decpair(int a, long dirg, int i) { this.a = a; b = dirg; idx = i; } public int compareTo(decpair e) { return (int) (e.b - b); } } static long allpowers[]; static class Quad implements Comparable<Quad> { int u; int v; char state; int turns; public Quad(int i, int j, char c, int k) { u = i; v = j; state = c; turns = k; } public int compareTo(Quad e) { return (int) (turns - e.turns); } } static long dirg[][]; static Edge[] driver; static int n; static class Edge implements Comparable<Edge> { int node; long cost; Edge(int a, long dirg) { node = a; cost = dirg; } public int compareTo(Edge e) { return (int) (cost - e.cost); } } static long manhatandistance(long x, long x2, long y, long y2) { return Math.abs(x - x2) + Math.abs(y - y2); } static long fib[]; static long fib(int n) { if (n == 1 || n == 0) { return 1; } if (fib[n] != -1) { return fib[n]; } else return fib[n] = ((fib(n - 2) % mod + fib(n - 1) % mod) % mod); } static class Pair implements Comparable<Pair> { int a, b; Pair(int x, int y) { a = x; b = y; } @Override public int compareTo(Pair c) { return b-c.b; } } static long[][] comb; static class Triple implements Comparable<Triple> { int l; int r; long cost; int idx; public Triple(int a, int b, long l1, int l2) { l = a; r = b; cost = l1; idx = l2; } public int compareTo(Triple x) { if (l != x.l || idx == x.idx) return l - x.l; return -idx; } } static TreeSet<Long> primeFactors(long N) // O(sqrt(N) / ln sqrt(N)) { TreeSet<Long> factors = new TreeSet<Long>(); // take abs(N) in case of -ve integers int idx = 0, p = primes.get(idx); while (p * p <= N) { while (N % p == 0) { factors.add((long) p); N /= p; } if (primes.size() > idx + 1) p = primes.get(++idx); else break; } if (N != 1) // last prime factor may be > sqrt(N) factors.add(N); // for integers whose largest prime factor has a power of 1 return factors; } static boolean visited[]; /** * static int bfs(int s) { Queue<Integer> q = new LinkedList<Integer>(); * q.add(s); int count=0; int maxcost=0; int dist[]=new int[n]; dist[s]=0; * while(!q.isEmpty()) { * * int u = q.remove(); if(dist[u]==k) { break; } for(Pair v: adj[u]) { * maxcost=Math.max(maxcost, v.cost); * * * * if(!visited[v.v]) { * * visited[v.v]=true; q.add(v.v); dist[v.v]=dist[u]+1; maxcost=Math.max(maxcost, * v.cost); } } * * } return maxcost; } **/ public static boolean FindAllElements(int n, int k) { int sum = k; int[] A = new int[k]; Arrays.fill(A, 0, k, 1); for (int i = k - 1; i >= 0; --i) { while (sum + A[i] <= n) { sum += A[i]; A[i] *= 2; } } if (sum == n) { return true; } else return false; } static boolean vis2[][]; static boolean f2 = false; static long[][] matMul(long[][] a2, long[][] b, int p, int q, int r) // C(p x r) = A(p x q) x (q x r) -- O(p x q x // r) { long[][] C = new long[p][r]; for (int i = 0; i < p; ++i) { for (int j = 0; j < r; ++j) { for (int k = 0; k < q; ++k) { C[i][j] = (C[i][j] + (a2[i][k] % mod * b[k][j] % mod)) % mod; C[i][j] %= mod; } } } return C; } static ArrayList<Pair> a1[]; static int memo1[]; static boolean vis[]; static TreeSet<Integer> set = new TreeSet<Integer>(); static long modPow(long ways, long count, long mod) // O(log e) { ways %= mod; long res = 1; while (count > 0) { if ((count & 1) == 1) res = (res * ways) % mod; ways = (ways * ways) % mod; count >>= 1; } return res % mod; } static long gcd(long ans, long b) { if (b == 0) { return ans; } return gcd(b, ans % b); } static int[] isComposite; static int[] valid; static ArrayList<Integer> primes; static ArrayList<Integer> l; static void sieve(int N) // O(N log log N) { isComposite = new int[N + 1]; isComposite[0] = isComposite[1] = 1; // 0 indicates a prime number primes = new ArrayList<Integer>(); l = new ArrayList<>(); valid = new int[N + 1]; for (int i = 2; i <= N; ++i) // can loop till i*i <= N if primes array is not needed O(N log log sqrt(N)) if (isComposite[i] == 0) // can loop in 2 and odd integers for slightly better performance { primes.add(i); l.add(i); valid[i] = 1; for (int j = i * 2; j <= N; j += i) { // j = i * 2 will not affect performance too much, may alter in // modified sieve isComposite[j] = 1; } } for (int i = 0; i < primes.size(); i++) { for (int j : primes) { if (primes.get(i) * j > N) { break; } valid[primes.get(i) * j] = 1; } } } public static long[] schuffle(long[] sad) { for (int i = 0; i < sad.length; i++) { int x = (int) (Math.random() * sad.length); long temp = sad[x]; sad[x] = sad[i]; sad[i] = temp; } return sad; } static int V; static long INF = (long) 1E16; static class Edge2 { int node; long cost; long next; Edge2(int a, int c, Long long1) { node = a; cost = long1; next = c; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
java
1307
C
C. Cow and Messagetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputBessie the cow has just intercepted a text that Farmer John sent to Burger Queen! However; Bessie is sure that there is a secret message hidden inside.The text is a string ss of lowercase Latin letters. She considers a string tt as hidden in string ss if tt exists as a subsequence of ss whose indices form an arithmetic progression. For example, the string aab is hidden in string aaabb because it occurs at indices 11, 33, and 55, which form an arithmetic progression with a common difference of 22. Bessie thinks that any hidden string that occurs the most times is the secret message. Two occurrences of a subsequence of SS are distinct if the sets of indices are different. Help her find the number of occurrences of the secret message!For example, in the string aaabb, a is hidden 33 times, b is hidden 22 times, ab is hidden 66 times, aa is hidden 33 times, bb is hidden 11 time, aab is hidden 22 times, aaa is hidden 11 time, abb is hidden 11 time, aaab is hidden 11 time, aabb is hidden 11 time, and aaabb is hidden 11 time. The number of occurrences of the secret message is 66.InputThe first line contains a string ss of lowercase Latin letters (1≤|s|≤1051≤|s|≤105) — the text that Bessie intercepted.OutputOutput a single integer  — the number of occurrences of the secret message.ExamplesInputCopyaaabb OutputCopy6 InputCopyusaco OutputCopy1 InputCopylol OutputCopy2 NoteIn the first example; these are all the hidden strings and their indice sets: a occurs at (1)(1), (2)(2), (3)(3) b occurs at (4)(4), (5)(5) ab occurs at (1,4)(1,4), (1,5)(1,5), (2,4)(2,4), (2,5)(2,5), (3,4)(3,4), (3,5)(3,5) aa occurs at (1,2)(1,2), (1,3)(1,3), (2,3)(2,3) bb occurs at (4,5)(4,5) aab occurs at (1,3,5)(1,3,5), (2,3,4)(2,3,4) aaa occurs at (1,2,3)(1,2,3) abb occurs at (3,4,5)(3,4,5) aaab occurs at (1,2,3,4)(1,2,3,4) aabb occurs at (2,3,4,5)(2,3,4,5) aaabb occurs at (1,2,3,4,5)(1,2,3,4,5) Note that all the sets of indices are arithmetic progressions.In the second example, no hidden string occurs more than once.In the third example, the hidden string is the letter l.
[ "brute force", "dp", "math", "strings" ]
import java.util.*; import java.lang.*; import java.io.*; public class Solution { static long[] fac; static int m = (int)1e9+7; static int c = 1; // static long[] factorial; 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) { String s = Reader.next(); int n = s.length(); long ans = 0; for(int i = 0;i<26;i++){ for(int j = 0;j<26;j++){ long curr = 0; int jc = 0; for(int k = n-1;k>=0;k--){ if(s.charAt(k)-'a'==i){ curr += jc; } if(s.charAt(k)-'a'==j){ jc++; } } ans = Math.max(ans,curr); ans = Math.max(ans,jc); } } output.write(ans+"\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
1299
B
B. Aerodynamictime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGuy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon PP which is defined by coordinates of its vertices. Define P(x,y)P(x,y) as a polygon obtained by translating PP by vector (x,y)−→−−(x,y)→. The picture below depicts an example of the translation:Define TT as a set of points which is the union of all P(x,y)P(x,y) such that the origin (0,0)(0,0) lies in P(x,y)P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y)(x,y) lies in TT only if there are two points A,BA,B in PP such that AB−→−=(x,y)−→−−AB→=(x,y)→. One can prove TT is a polygon too. For example, if PP is a regular triangle then TT is a regular hexagon. At the picture below PP is drawn in black and some P(x,y)P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if PP and TT are similar. Your task is to check whether the polygons PP and TT are similar.InputThe first line of input will contain a single integer nn (3≤n≤1053≤n≤105) — the number of points.The ii-th of the next nn lines contains two integers xi,yixi,yi (|xi|,|yi|≤109|xi|,|yi|≤109), denoting the coordinates of the ii-th vertex.It is guaranteed that these points are listed in counterclockwise order and these points form a strictly convex polygon.OutputOutput "YES" in a separate line, if PP and TT are similar. Otherwise, output "NO" in a separate line. You can print each letter in any case (upper or lower).ExamplesInputCopy4 1 0 4 1 3 4 0 3 OutputCopyYESInputCopy3 100 86 50 0 150 0 OutputCopynOInputCopy8 0 0 1 0 2 1 3 3 4 6 3 6 2 5 1 3 OutputCopyYESNoteThe following image shows the first sample: both PP and TT are squares. The second sample was shown in the statements.
[ "geometry" ]
//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(); if (n % 2 != 0) { pw.println("NO"); return; } int[][] pair = new int[n][2]; for (int i = 0; i < n; i++) { for (int j = 0; j < 2; j++) { pair[i][j] = sc.nextInt(); } } boolean same = true; for (int i = 0, j = n / 2; i < n / 2; i++, j++) { if (pair[i + 1][0] - pair[i][0] != pair[j][0] - pair[(j + 1) % n][0]) { same=false;break; } if (pair[i + 1][1] - pair[i][1] != pair[j][1] - pair[(j + 1) % n][1]) { same=false;break; } } pw.println(same? "YES": "NO"); } } 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
1292
B
B. Aroma's Searchtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputTHE SxPLAY & KIVΛ - 漂流 KIVΛ & Nikki Simmons - PerspectivesWith a new body; our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.The space can be considered a 2D plane, with an infinite number of data nodes, indexed from 00, with their coordinates defined as follows: The coordinates of the 00-th node is (x0,y0)(x0,y0) For i>0i>0, the coordinates of ii-th node is (ax⋅xi−1+bx,ay⋅yi−1+by)(ax⋅xi−1+bx,ay⋅yi−1+by) Initially Aroma stands at the point (xs,ys)(xs,ys). She can stay in OS space for at most tt seconds, because after this time she has to warp back to the real world. She doesn't need to return to the entry point (xs,ys)(xs,ys) to warp home.While within the OS space, Aroma can do the following actions: From the point (x,y)(x,y), Aroma can move to one of the following points: (x−1,y)(x−1,y), (x+1,y)(x+1,y), (x,y−1)(x,y−1) or (x,y+1)(x,y+1). This action requires 11 second. If there is a data node at where Aroma is staying, she can collect it. We can assume this action costs 00 seconds. Of course, each data node can be collected at most once. Aroma wants to collect as many data as possible before warping back. Can you help her in calculating the maximum number of data nodes she could collect within tt seconds?InputThe first line contains integers x0x0, y0y0, axax, ayay, bxbx, byby (1≤x0,y0≤10161≤x0,y0≤1016, 2≤ax,ay≤1002≤ax,ay≤100, 0≤bx,by≤10160≤bx,by≤1016), which define the coordinates of the data nodes.The second line contains integers xsxs, ysys, tt (1≤xs,ys,t≤10161≤xs,ys,t≤1016) – the initial Aroma's coordinates and the amount of time available.OutputPrint a single integer — the maximum number of data nodes Aroma can collect within tt seconds.ExamplesInputCopy1 1 2 3 1 0 2 4 20 OutputCopy3InputCopy1 1 2 3 1 0 15 27 26 OutputCopy2InputCopy1 1 2 3 1 0 2 2 1 OutputCopy0NoteIn all three examples; the coordinates of the first 55 data nodes are (1,1)(1,1), (3,3)(3,3), (7,9)(7,9), (15,27)(15,27) and (31,81)(31,81) (remember that nodes are numbered from 00).In the first example, the optimal route to collect 33 nodes is as follows: Go to the coordinates (3,3)(3,3) and collect the 11-st node. This takes |3−2|+|3−4|=2|3−2|+|3−4|=2 seconds. Go to the coordinates (1,1)(1,1) and collect the 00-th node. This takes |1−3|+|1−3|=4|1−3|+|1−3|=4 seconds. Go to the coordinates (7,9)(7,9) and collect the 22-nd node. This takes |7−1|+|9−1|=14|7−1|+|9−1|=14 seconds. In the second example, the optimal route to collect 22 nodes is as follows: Collect the 33-rd node. This requires no seconds. Go to the coordinates (7,9)(7,9) and collect the 22-th node. This takes |15−7|+|27−9|=26|15−7|+|27−9|=26 seconds. In the third example, Aroma can't collect any nodes. She should have taken proper rest instead of rushing into the OS space like that.
[ "brute force", "constructive algorithms", "geometry", "greedy", "implementation" ]
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1292b { public static void main(String[] args) throws IOException { long x0 = rnl(), y0 = nl(), ax = nl(), ay = nl(), bx = nl(), by = nl(), xs = rnl(), ys = nl(), t = nl(); long data[][] = new long[64][2]; data[0][0] = x0; data[0][1] = y0; int ind = 0; while(data[ind][0] < LMAX / ax && data[ind][1] < LMAX / ay) { ++ind; data[ind][0] = data[ind - 1][0] * ax + bx; data[ind][1] = data[ind - 1][1] * ay + by; } int ans = 0; for(int i = 0; i < ind; ++i) { for(int j = i; j < ind; ++j) { long treq = dist(data[i][0], data[i][1], data[j][0], data[j][1]); long dist = min(dist(xs, ys, data[i][0], data[i][1]), dist(xs, ys, data[j][0], data[j][1])); treq += dist; if(t >= treq) { ans = max(ans, j - i + 1); } } } prln(ans); close(); } static long dist(long x0, long y0, long x1, long y1) { return abs(y1 - y0) + abs(x1 - x0); } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __rand = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e10 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return min(x[0], x[1]); if(x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if(x.length == 1) return x[0]; if(x.length == 2) return max(x[0], x[1]); if(x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for(int i = 1; i < x.length; ++i) if(x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int fli(double d) {return (int)d;} static int cei(double d) {return (int)ceil(d);} static long fll(double d) {return (long)d;} static long cel(double d) {return (long)ceil(d);} static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);} static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);} static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;} static long hash(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);} // array util static void reverse(int[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for(int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static int[] copy(int[] a) {int[] ans = new int[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static long[] copy(long[] a) {long[] ans = new long[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static char[] copy(char[] a) {char[] ans = new char[a.length]; for(int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static int[] sorted(int[] a) {int[] ans = copy(a); sort(ans); return ans;} static long[] sorted(long[] a) {long[] ans = copy(a); sort(ans); return ans;} static int[] rsorted(int[] a) {int[] ans = copy(a); rsort(ans); return ans;} static long[] rsorted(long[] a) {long[] ans = copy(a); rsort(ans); return ans;} // graph util static List<List<Integer>> graph(int n) {List<List<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;} static List<List<Integer>> graph(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connect(g, rni() - 1, ni() - 1); return g;} static List<List<Integer>> graph(int n, int m) throws IOException {return graph(graph(n), m);} static List<List<Integer>> dgraph(List<List<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connecto(g, rni() - 1, ni() - 1); return g;} static List<List<Integer>> dgraph(List<List<Integer>> g, int n, int m) throws IOException {return dgraph(graph(n), m);} static List<Set<Integer>> sgraph(int n) {List<Set<Integer>> g = new ArrayList<>(); for(int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;} static List<Set<Integer>> sgraph(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connect(g, rni() - 1, ni() - 1); return g;} static List<Set<Integer>> sgraph(int n, int m) throws IOException {return sgraph(sgraph(n), m);} static List<Set<Integer>> dsgraph(List<Set<Integer>> g, int m) throws IOException {for(int i = 0; i < m; ++i) connecto(g, rni() - 1, ni() - 1); return g;} static List<Set<Integer>> dsgraph(List<Set<Integer>> g, int n, int m) throws IOException {return dsgraph(sgraph(n), m);} static void connect(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);} static void connecto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);} static void dconnect(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);} static void dconnecto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);} // input static void r() throws IOException {input = new StringTokenizer(__in.readLine());} static int ri() throws IOException {return Integer.parseInt(__in.readLine());} static long rl() throws IOException {return Long.parseLong(__in.readLine());} static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;} static int[] riam1(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()) - 1; return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;} static char[] rcha() throws IOException {return __in.readLine().toCharArray();} static String rline() throws IOException {return __in.readLine();} static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());} static int ni() {return Integer.parseInt(input.nextToken());} static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());} static long nl() {return Long.parseLong(input.nextToken());} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {__out.println("yes");} static void pry() {__out.println("Yes");} static void prY() {__out.println("YES");} static void prno() {__out.println("no");} static void prn() {__out.println("No");} static void prN() {__out.println("NO");} static void pryesno(boolean b) {__out.println(b ? "yes" : "no");}; static void pryn(boolean b) {__out.println(b ? "Yes" : "No");} static void prYN(boolean b) {__out.println(b ? "YES" : "NO");} static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next()); else __out.println();} static void h() {__out.println("hlfd");} static void flush() {__out.flush();} static void close() {__out.close();} }
java
1325
D
D. Ehab the Xorcisttime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputGiven 2 integers uu and vv, find the shortest array such that bitwise-xor of its elements is uu, and the sum of its elements is vv.InputThe only line contains 2 integers uu and vv (0≤u,v≤1018)(0≤u,v≤1018).OutputIf there's no array that satisfies the condition, print "-1". Otherwise:The first line should contain one integer, nn, representing the length of the desired array. The next line should contain nn positive integers, the array itself. If there are multiple possible answers, print any.ExamplesInputCopy2 4 OutputCopy2 3 1InputCopy1 3 OutputCopy3 1 1 1InputCopy8 5 OutputCopy-1InputCopy0 0 OutputCopy0NoteIn the first sample; 3⊕1=23⊕1=2 and 3+1=43+1=4. There is no valid array of smaller length.Notice that in the fourth sample the array is empty.
[ "bitmasks", "constructive algorithms", "greedy", "number theory" ]
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.*; import java.io.*; public class Main { // Graph // prefix sums //inputs public static void main(String args[])throws Exception{ Input sc=new Input(); precalculates p=new precalculates(); StringBuilder sb=new StringBuilder(); long d[]=sc.readArrayLong(); long a=d[0],b=d[1]; long p1=0; long p2=0; if(a==b && a==0){ System.out.println(0); return; } long temp=a; while(temp!=0){ if(temp%2!=0) p1++; temp/=2; } temp=b; while(temp!=0){ if(temp%2!=0) p2++; temp/=2; } if((a+b)%2!=0 || a>b) { System.out.println(-1); return; } if(a==b) { System.out.println("1\n"+a); return; } long x=b-a; x/=2; if(((a+x)^x)==a) System.out.println("2\n"+(a+x)+" "+(x)); else System.out.println("3\n"+(a)+" "+(x)+" "+(x)); System.out.print(sb); } } class Input{ BufferedReader br; StringTokenizer st; Input(){ br=new BufferedReader(new InputStreamReader(System.in)); st=new StringTokenizer(""); } public int[] readArray() throws Exception{ st=new StringTokenizer(br.readLine()); int a[]=new int[st.countTokens()]; for(int i=0;i<a.length;i++){ a[i]=Integer.parseInt(st.nextToken()); } return a; } public long[] readArrayLong() throws Exception{ st=new StringTokenizer(br.readLine()); long a[]=new long[st.countTokens()]; for(int i=0;i<a.length;i++){ a[i]=Long.parseLong(st.nextToken()); } return a; } public int readInt() throws Exception{ st=new StringTokenizer(br.readLine()); return Integer.parseInt(st.nextToken()); } public long readLong() throws Exception{ st=new StringTokenizer(br.readLine()); return Long.parseLong(st.nextToken()); } public String readString() throws Exception{ return br.readLine(); } public int[][] read2dArray(int n,int m)throws Exception{ int a[][]=new int[n][m]; for(int i=0;i<n;i++){ st=new StringTokenizer(br.readLine()); for(int j=0;j<m;j++){ a[i][j]=Integer.parseInt(st.nextToken()); } } return a; } } class precalculates{ public long gcd(long p, long q) { if (q == 0) return p; else return gcd(q, p % q); } public int[] prefixSumOneDimentional(int a[]){ int n=a.length; int dp[]=new int[n]; for(int i=0;i<n;i++){ if(i==0) dp[i]=a[i]; else dp[i]=dp[i-1]+a[i]; } return dp; } public int[] postSumOneDimentional(int a[]) { int n = a.length; int dp[] = new int[n]; for (int i = n - 1; i >= 0; i--) { if (i == n - 1) dp[i] = a[i]; else dp[i] = dp[i + 1] + a[i]; } return dp; } public int[][] prefixSum2d(int a[][]){ int n=a.length;int m=a[0].length; int dp[][]=new int[n+1][m+1]; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ dp[i][j]=a[i-1][j-1]+dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1]; } } return dp; } public long pow(long a,long b){ long mod=998244353; long ans=1; if(b<=0) return 1; if(b%2==0){ ans=pow(a,b/2)%mod; return ((ans%mod)*(ans%mod))%mod; }else{ ans=pow(a,b-1)%mod; return ((a%mod)*(ans%mod))%mod; } } } class GraphInteger{ HashMap<Integer,vertex> vtces; class vertex{ HashMap<Integer,Integer> children; public vertex(){ children=new HashMap<>(); } } public GraphInteger(){ vtces=new HashMap<>(); } public void addVertex(int a){ vtces.put(a,new vertex()); } public void addEdge(int a,int b,int cost){ if(!vtces.containsKey(a)){ vtces.put(a,new vertex()); } if(!vtces.containsKey(b)){ vtces.put(b,new vertex()); } vtces.get(a).children.put(b,cost); // vtces.get(b).children.put(a,cost); } public boolean isCyclicDirected(){ boolean isdone[]=new boolean[vtces.size()+1]; boolean check[]=new boolean[vtces.size()+1]; for(int i=1;i<=vtces.size();i++) { if (!isdone[i] && isCyclicDirected(i,isdone, check)) { return true; } } return false; } private boolean isCyclicDirected(int i,boolean isdone[],boolean check[]){ if(check[i]) return true; if(isdone[i]) return false; check[i]=true; isdone[i]=true; Set<Integer> set=vtces.get(i).children.keySet(); for(Integer ii:set){ if(isCyclicDirected(ii,isdone,check)) return true; } check[i]=false; return false; } } class union_find { int n; int[] sz; int[] par; union_find(int nval) { n = nval; sz = new int[n + 1]; par = new int[n + 1]; for (int i = 0; i <= n; i++) { par[i] = i; sz[i] = 1; } } int root(int x) { if (par[x] == x) return x; return par[x] = root(par[x]); } boolean find(int a, int b) { return root(a) == root(b); } int union(int a, int b) { int ra = root(a); int rb = root(b); if (ra == rb) return 0; if(a==b) return 0; if (sz[a] > sz[b]) { int temp = ra; ra = rb; rb = temp; } par[ra] = rb; sz[rb] += sz[ra]; return 1; } } /* static int mod=998244353; private static int add(int x, int y) { x += y; return x % MOD; } private static int mul(int x, int y) { int res = (int) (((long) x * y) % MOD); return res; } private static int binpow(int x, int y) { int z = 1; while (y > 0) { if (y % 2 != 0) z = mul(z, x); x = mul(x, x); y >>= 1; } return z; } private static int inv(int x) { return binpow(x, MOD - 2); } private static int devide(int x, int y) { return mul(x, inv(y)); } private static int C(int n, int k, int[] fact) { return devide(fact[n], mul(fact[k], fact[n-k])); } */
java
1325
C
C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusive. All the written labels are distinct. The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3 1 2 1 3 OutputCopy0 1 InputCopy6 1 2 1 3 2 4 2 5 5 6 OutputCopy0 3 2 4 1NoteThe tree from the second sample:
[ "constructive algorithms", "dfs and similar", "greedy", "trees" ]
import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codeforces { static long MOD=1000000000+7; static long fact(long n) { long f=1; for(long j=1;j<=n;j++) f=(f*j)%MOD; return f; } static long power(long n) { long p=1; for(long j=1;j<=n-1;j++) p=(p*2)%MOD; return p; } public static void main(String[] args) throws java.lang.Exception { /* your code goes here */ BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); //int t = Integer.parseInt(buf.readLine().trim()); StringBuilder sb = new StringBuilder(); //for (int i = 0; i < t; i++) { String st1[]=(buf.readLine().trim()).split(" "); int n=Integer.parseInt(st1[0]); int nodes[][]=new int[n-1][2]; int cnt[]=new int[100000+1]; for(int j=0;j<n-1;j++) { String st2[]=(buf.readLine()).split(" "); int u=Integer.parseInt(st2[0]); int v=Integer.parseInt(st2[1]); nodes[j][0]=u; nodes[j][1]=v; cnt[u]++; cnt[v]++; } int flag=-1; for(int j=0;j<cnt.length;j++) { if(cnt[j]>=3) { flag=j; break; } } int res[]=new int[n-1]; if(flag!=-1) { int ct=3,p=0; for(int j=0;j<n-1;j++) { if(p<=2) { if (nodes[j][0] == flag || nodes[j][1] == flag) { res[j]=p; p++; } else { res[j]=ct; ct++; } } else { res[j]= ct; ct++; } } } else { int ct=0; for(int j=0;j<n-1;j++) res[j]=j; } for(int j=0;j<n-1;j++) sb.append(res[j]+"\n"); //} System.out.println(sb); } }
java
1324
E
E. Sleeping Scheduletime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputVova had a pretty weird sleeping schedule. There are hh hours in a day. Vova will sleep exactly nn times. The ii-th time he will sleep exactly after aiai hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 00). Each time Vova sleeps exactly one day (in other words, hh hours).Vova thinks that the ii-th sleeping time is good if he starts to sleep between hours ll and rr inclusive.Vova can control himself and before the ii-th time can choose between two options: go to sleep after aiai hours or after ai−1ai−1 hours.Your task is to say the maximum number of good sleeping times Vova can obtain if he acts optimally.InputThe first line of the input contains four integers n,h,ln,h,l and rr (1≤n≤2000,3≤h≤2000,0≤l≤r<h1≤n≤2000,3≤h≤2000,0≤l≤r<h) — the number of times Vova goes to sleep, the number of hours in a day and the segment of the good sleeping time.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai<h1≤ai<h), where aiai is the number of hours after which Vova goes to sleep the ii-th time.OutputPrint one integer — the maximum number of good sleeping times Vova can obtain if he acts optimally.ExampleInputCopy7 24 21 23 16 17 14 20 20 11 22 OutputCopy3 NoteThe maximum number of good times in the example is 33.The story starts from t=0t=0. Then Vova goes to sleep after a1−1a1−1 hours, now the time is 1515. This time is not good. Then Vova goes to sleep after a2−1a2−1 hours, now the time is 15+16=715+16=7. This time is also not good. Then Vova goes to sleep after a3a3 hours, now the time is 7+14=217+14=21. This time is good. Then Vova goes to sleep after a4−1a4−1 hours, now the time is 21+19=1621+19=16. This time is not good. Then Vova goes to sleep after a5a5 hours, now the time is 16+20=1216+20=12. This time is not good. Then Vova goes to sleep after a6a6 hours, now the time is 12+11=2312+11=23. This time is good. Then Vova goes to sleep after a7a7 hours, now the time is 23+22=2123+22=21. This time is also good.
[ "dp", "implementation" ]
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main { public static void main(String[] args) { new Main().solve(new InputReader(System.in), new PrintWriter(System.out)); } private void solve(InputReader in, PrintWriter pw) { int tt = 1; // int tt = in.nextInt(); while (tt-- > 0) { int n = in.nextInt(); int h = in.nextInt(); int l = in.nextInt(); int r = in.nextInt(); int[] a = in.nextArray(n); // f[i][j]代表已经睡了i次且恰好早睡j次时好睡眠的次数 int[][] f = new int[n + 1][n + 1]; // for (int i = 0; i <= n; i++) { // Arrays.fill(f[i], Integer.MIN_VALUE); // } // f[0][0] = 0; for (int i = 0, sum = 0; i < n; i++) { sum += a[i]; for (int j = 0; j <= i; j++) { f[i + 1][j] = max(f[i + 1][j], f[i][j] + check((sum - j) % h, l, r)); f[i + 1][j + 1] = max(f[i + 1][j + 1], f[i][j] + check((sum - (j + 1)) % h, l, r)); } } int maxv = 0; for (int i = 0; i <= n; i++) { maxv = max(maxv, f[n][i]); } pw.println(maxv); } pw.close(); } private int check(int x, int l, int r) { if (x >= l && x <= r) { return 1; } return 0; } private int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } private int lcm(int a, int b) { return a / gcd(a, b) * b; } } class InputReader { private final BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String nextLine() { String str; try { str = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } return str; } public boolean hasNext() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { String nextLine = null; try { nextLine = reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (nextLine == null) return false; tokenizer = new StringTokenizer(nextLine); } return true; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public int[] nextArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; ++i) { a[i] = nextInt(); } return a; } }
java
1301
B
B. Motarack's Birthdaytime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputDark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array aa of nn non-negative integers.Dark created that array 10001000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer kk (0≤k≤1090≤k≤109) and replaces all missing elements in the array aa with kk.Let mm be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai−ai+1||ai−ai+1| for all 1≤i≤n−11≤i≤n−1) in the array aa after Dark replaces all missing elements with kk.Dark should choose an integer kk so that mm is minimized. Can you help him?InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤1041≤t≤104)  — the number of test cases. The description of the test cases follows.The first line of each test case contains one integer nn (2≤n≤1052≤n≤105) — the size of the array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (−1≤ai≤109−1≤ai≤109). If ai=−1ai=−1, then the ii-th integer is missing. It is guaranteed that at least one integer is missing in every test case.It is guaranteed, that the sum of nn for all test cases does not exceed 4⋅1054⋅105.OutputPrint the answers for each test case in the following format:You should print two integers, the minimum possible value of mm and an integer kk (0≤k≤1090≤k≤109) that makes the maximum absolute difference between adjacent elements in the array aa equal to mm.Make sure that after replacing all the missing elements with kk, the maximum absolute difference between adjacent elements becomes mm.If there is more than one possible kk, you can print any of them.ExampleInputCopy7 5 -1 10 -1 12 -1 5 -1 40 35 -1 35 6 -1 -1 9 -1 3 -1 2 -1 -1 2 0 -1 4 1 -1 3 -1 7 1 -1 7 5 2 -1 5 OutputCopy1 11 5 35 3 6 0 42 0 0 1 2 3 4 NoteIn the first test case after replacing all missing elements with 1111 the array becomes [11,10,11,12,11][11,10,11,12,11]. The absolute difference between any adjacent elements is 11. It is impossible to choose a value of kk, such that the absolute difference between any adjacent element will be ≤0≤0. So, the answer is 11.In the third test case after replacing all missing elements with 66 the array becomes [6,6,9,6,3,6][6,6,9,6,3,6]. |a1−a2|=|6−6|=0|a1−a2|=|6−6|=0; |a2−a3|=|6−9|=3|a2−a3|=|6−9|=3; |a3−a4|=|9−6|=3|a3−a4|=|9−6|=3; |a4−a5|=|6−3|=3|a4−a5|=|6−3|=3; |a5−a6|=|3−6|=3|a5−a6|=|3−6|=3. So, the maximum difference between any adjacent elements is 33.
[ "binary search", "greedy", "ternary search" ]
import java.util.*; import java.io.*; public class A { static class Pair { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } } static long gcd(long n, long m) { if (m == 0) return n; else return gcd(m, n % m); } static long lcm(long n, long m) { return (n * m) / gcd(n, m); } static void dfs(ArrayList<ArrayList<Integer>> adj, int s, int[] vis, int[] cnt) { for (int i : adj.get(s)) { if (vis[i] == 1) { continue; } cnt[0]++; vis[i] = 1; dfs(adj, i, vis, cnt); } } public static long solve(long a, long b, long x, long y, long n) { if (a - n >= x) { return ((a - n) * b); } else { n -= a - x; a = x; if (b - n >= y) { return (a * (b - n)); } else { b = y; return (a * b); } } } static int high(int n) { int p = (int) (Math.log(n) / Math.log(2)); return (int) Math.pow(2, p); } static int bs(long[] pow, long target) { int low = 0; int idx = -1; int high = pow.length - 1; while (low <= high) { int mid = (low + high) / 2; if (pow[mid] <= target) { low = mid + 1; idx = mid; } else { high = mid - 1; } } return idx; } static boolean prime(int n) { int m = (int) Math.sqrt(n); for (int i = 2; i <= m; i++) if (n % i == 0) return false; return true; } static StringBuilder str = new StringBuilder(); public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for (int xx = 0; xx < t; xx++) { int n = sc.nextInt(); long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } long min = (int) 1e9; long max = 0; for (int i = 0; i < n; i++) { if (i > 0 && arr[i] == -1 && arr[i - 1] != -1) { min = Math.min(min, arr[i - 1]); max = Math.max(max, arr[i - 1]); } if (i < n - 1 && arr[i] == -1 && arr[i + 1] != -1) { max = Math.max(arr[i + 1], max); min = Math.min(arr[i + 1], min); } } long c = 2; long sum = max + min; if (c != 0) c = sum / c; else c = 0; if (arr[0] == -1) arr[0] = c; max = 0; for (int i = 1; i < n; i++) { if (arr[i] == -1) arr[i] = c; max = Math.max(max, Math.abs(arr[i] - arr[i - 1])); } str.append(max + " " + c + "\n"); } System.out.println(str); sc.close(); } }
java
1296
E1
E1. String Coloring (easy version)time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis is an easy version of the problem. The actual problems are different; but the easy version is almost a subtask of the hard version. Note that the constraints and the output format are different.You are given a string ss consisting of nn lowercase Latin letters.You have to color all its characters one of the two colors (each character to exactly one color, the same letters can be colored the same or different colors, i.e. you can choose exactly one color for each index in ss).After coloring, you can swap any two neighboring characters of the string that are colored different colors. You can perform such an operation arbitrary (possibly, zero) number of times.The goal is to make the string sorted, i.e. all characters should be in alphabetical order.Your task is to say if it is possible to color the given string so that after coloring it can become sorted by some sequence of swaps. Note that you have to restore only coloring, not the sequence of swaps.InputThe first line of the input contains one integer nn (1≤n≤2001≤n≤200) — the length of ss.The second line of the input contains the string ss consisting of exactly nn lowercase Latin letters.OutputIf it is impossible to color the given string so that after coloring it can become sorted by some sequence of swaps, print "NO" (without quotes) in the first line.Otherwise, print "YES" in the first line and any correct coloring in the second line (the coloring is the string consisting of nn characters, the ii-th character should be '0' if the ii-th character is colored the first color and '1' otherwise).ExamplesInputCopy9 abacbecfd OutputCopyYES 001010101 InputCopy8 aaabbcbb OutputCopyYES 01011011 InputCopy7 abcdedc OutputCopyNO InputCopy5 abcde OutputCopyYES 00000
[ "constructive algorithms", "dp", "graphs", "greedy", "sortings" ]
import java.util.*; import java.util.Map.Entry; import java.lang.*; import java.io.*; import java.math.BigInteger; public class CF { private static FS sc = new FS(); private static class FS { 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) {} return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } private static class extra { static int[] intArr(int size) { int[] a = new int[size]; for(int i = 0; i < size; i++) a[i] = sc.nextInt(); return a; } static long[] longArr(int size) { long[] a = new long[size]; for(int i = 0; i < size; i++) a[i] = sc.nextLong(); return a; } static long intSum(int[] a) { long sum = 0; for(int i = 0; i < a.length; i++) { sum += a[i]; } return sum; } static long longSum(long[] a) { long sum = 0; for(int i = 0; i < a.length; i++) { sum += a[i]; } return sum; } static LinkedList[] graphD(int vertices, int edges) { LinkedList<Integer>[] temp = new LinkedList[vertices+1]; for(int i = 0; i <= vertices; i++) temp[i] = new LinkedList<>(); for(int i = 0; i < edges; i++) { int x = sc.nextInt(); int y = sc.nextInt(); temp[x].add(y); } return temp; } static LinkedList[] graphUD(int vertices, int edges) { LinkedList<Integer>[] temp = new LinkedList[vertices+1]; for(int i = 0; i <= vertices; i++) temp[i] = new LinkedList<>(); for(int i = 0; i < edges; i++) { int x = sc.nextInt(); int y = sc.nextInt(); temp[x].add(y); temp[y].add(x); } return temp; } static void printG(LinkedList[] temp) { for(LinkedList<Integer> aa:temp) System.out.println(aa); } static long cal(long val, long pow) { if(pow == 0) return 1; long res = cal(val, pow/2); // long ret = (res*res)%mod; // if(pow%2 == 0) return ret; // return (val*ret)%mod; long ret = res*res; if(pow%2 == 0) return ret; return val*ret; } static long gcd(long a, long b) { return b == 0 ? a:gcd(b, a%b); } } static int mod = (int) 1e9 + 9; // static int mod = (int) 998244353; static int max = (int) 1e5+5, sq = 316; static LinkedList<Integer>[] temp; // static int[][] pre; static int ans; static class pair { int l, r, idx; pair(int x, int y, int z) { l = x; r = y; idx = z; } } public static void main(String[] args) { // int t = sc.nextInt(); int t = 1; StringBuilder ret = new StringBuilder(); while(t-- > 0) { int n = sc.nextInt(), flag = 0; String s = sc.next(); char cur = 'a', maxO = 'a'; String ans = ""; for(int i = 0; i < s.length(); i++) { char now = s.charAt(i); if(now >= cur) { ans += 0; cur = now; } else if(now >= maxO) { ans += 1; maxO = now; } else flag = 1; } ret.append(flag == 1 ? "NO\n":"YES\n"+ans + "\n"); } System.out.println(ret); } }
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.HashSet; import java.util.ArrayList; import java.util.Collections; import java.util.Arrays; import java.util.Scanner; public class A1307{ public static int[] sort(int[] arr,int low,int high){ int[] sortedArray; if (low==high) { sortedArray=new int[]{arr[low]}; return sortedArray; } int mid=(low+high)/2; int[] arr1=sort(arr,low,mid); int[] arr2=sort(arr,mid+1,high); sortedArray=merge(arr1,low,mid,arr2,mid+1,high); return sortedArray; } public static int[] merge(int[] arr1,int low1,int high1,int[] arr2,int low2,int high2){ int size1=high1-low1+1; int size2=high2-low2+1; int[] arr=new int[size1+size2]; int pointer=0; low1=0;low2=0; while (low1<size1 && low2<size2){ if (arr1[low1] <= arr2[low2]) { arr[pointer++]=arr1[low1++]; } else{ arr[pointer++]=arr2[low2++]; } } while(low1<size1) arr[pointer++]=arr1[low1++]; while(low2<size2) arr[pointer++]=arr2[low2++]; return arr; } 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 ans=0; for(int i=1;i<n;i++){ int dist=i; while(arr[i] > 0 && d >= dist){ d-=dist; ans++; arr[i]-=1; } } System.out.println(ans+arr[0]); } sc.close(); } }
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.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.*; public class cf1303e_2 { public static void main(String[] args) throws IOException { int tt = ri(); next: while (tt --> 0) { char[] s = rcha(), t = rcha(); int n = s.length, m = t.length, next[][] = new int[n + 1][26]; fill(next[n], n); for (int i = n - 1; i >= 0; --i) { for (int j = 0; j < 26; ++j) { next[i][j] = s[i] - 'a' == j ? i : next[i + 1][j]; } } for (int match = 0; match < m; ++match) { int dp[][] = new int[match + 1][m - match + 1]; for (int[] row : dp) { fill(row, n); } dp[0][0] = -1; for (int i = 0; i <= match; ++i) { for (int j = 0; j <= m - match; ++j) { if (dp[i][j] < n) { if (i < match) { dp[i + 1][j] = min(dp[i + 1][j], next[dp[i][j] + 1][t[i] - 'a']); } if (j < m - match) { dp[i][j + 1] = min(dp[i][j + 1], next[dp[i][j] + 1][t[match + j] - 'a']); } } } } if (dp[match][m - match] < n) { prY(); continue next; } } prN(); } close(); } static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out)); static StringTokenizer input; static Random __rand = new Random(); // references // IBIG = 1e9 + 7 // IMAX ~= 2e9 // LMAX ~= 9e18 // constants static final int IBIG = 1000000007; static final int IMAX = 2147483647; static final int IMIN = -2147483648; static final long LMAX = 9223372036854775807L; static final long LMIN = -9223372036854775808L; // math util static int minof(int a, int b, int c) {return min(a, min(b, c));} static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static long minof(long a, long b, long c) {return min(a, min(b, c));} static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;} static int maxof(int a, int b, int c) {return max(a, max(b, c));} static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static long maxof(long a, long b, long c) {return max(a, max(b, c));} static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;} static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;} static int fli(double d) {return (int) d;} static int cei(double d) {return (int) ceil(d);} static long fll(double d) {return (long) d;} static long cel(double d) {return (long) ceil(d);} static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);} static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);} static int lcm(int a, int b) {return a * b / gcf(a, b);} static long lcm(long a, long b) {return a * b / gcf(a, b);} static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;} static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);} // array util static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}} static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}} static void rsort(int[] a) {shuffle(a); sort(a);} static void rsort(long[] a) {shuffle(a); sort(a);} static void rsort(double[] a) {shuffle(a); sort(a);} static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;} // graph util static List<List<Integer>> g(int n) {List<List<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new ArrayList<>()); return g;} static List<Set<Integer>> sg(int n) {List<Set<Integer>> g = new ArrayList<>(); for (int i = 0; i < n; ++i) g.add(new HashSet<>()); return g;} static void c(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v); g.get(v).add(u);} static void cto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).add(v);} static void dc(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v); g.get(v).remove(u);} static void dcto(List<? extends Collection<Integer>> g, int u, int v) {g.get(u).remove(v);} // input static void r() throws IOException {input = new StringTokenizer(rline());} static int ri() throws IOException {return Integer.parseInt(rline());} static long rl() throws IOException {return Long.parseLong(rline());} static double rd() throws IOException {return Double.parseDouble(rline());} static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;} static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;} static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;} static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;} static char[] rcha() throws IOException {return rline().toCharArray();} static String rline() throws IOException {return __in.readLine();} static String n() {return input.nextToken();} static int rni() throws IOException {r(); return ni();} static int ni() {return Integer.parseInt(n());} static long rnl() throws IOException {r(); return nl();} static long nl() {return Long.parseLong(n());} static double rnd() throws IOException {r(); return nd();} static double nd() {return Double.parseDouble(n());} static List<List<Integer>> rg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;} static void rg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);} static List<List<Integer>> rdg(int n, int m) throws IOException {List<List<Integer>> g = g(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;} static void rdg(List<List<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);} static List<Set<Integer>> rsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1); return g;} static void rsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) c(g, rni() - 1, ni() - 1);} static List<Set<Integer>> rdsg(int n, int m) throws IOException {List<Set<Integer>> g = sg(n); for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1); return g;} static void rdsg(List<Set<Integer>> g, int m) throws IOException {for (int i = 0; i < m; ++i) cto(g, rni() - 1, ni() - 1);} // output static void pr(int i) {__out.print(i);} static void prln(int i) {__out.println(i);} static void pr(long l) {__out.print(l);} static void prln(long l) {__out.println(l);} static void pr(double d) {__out.print(d);} static void prln(double d) {__out.println(d);} static void pr(char c) {__out.print(c);} static void prln(char c) {__out.println(c);} static void pr(char[] s) {__out.print(new String(s));} static void prln(char[] s) {__out.println(new String(s));} static void pr(String s) {__out.print(s);} static void prln(String s) {__out.println(s);} static void pr(Object o) {__out.print(o);} static void prln(Object o) {__out.println(o);} static void prln() {__out.println();} static void pryes() {prln("yes");} static void pry() {prln("Yes");} static void prY() {prln("YES");} static void prno() {prln("no");} static void prn() {prln("No");} static void prN() {prln("NO");} static void pryesno(boolean b) {prln(b ? "yes" : "no");}; static void pryn(boolean b) {prln(b ? "Yes" : "No");} static void prYN(boolean b) {prln(b ? "YES" : "NO");} static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();} static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();} static void h() {prln("hlfd"); flush();} static void flush() {__out.flush();} static void close() {__out.close();}}
java
1322
C
C. Instant Noodlestime limit per test2 secondsmemory limit per test512 megabytesinputstandard inputoutputstandard outputWu got hungry after an intense training session; and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.You are given a bipartite graph with positive integers in all vertices of the right half. For a subset SS of vertices of the left half we define N(S)N(S) as the set of all vertices of the right half adjacent to at least one vertex in SS, and f(S)f(S) as the sum of all numbers in vertices of N(S)N(S). Find the greatest common divisor of f(S)f(S) for all possible non-empty subsets SS (assume that GCD of empty set is 00).Wu is too tired after his training to solve this problem. Help him!InputThe first line contains a single integer tt (1≤t≤5000001≤t≤500000) — the number of test cases in the given test set. Test case descriptions follow.The first line of each case description contains two integers nn and mm (1 ≤ n, m ≤ 5000001 ≤ n, m ≤ 500000) — the number of vertices in either half of the graph, and the number of edges respectively.The second line contains nn integers cici (1≤ci≤10121≤ci≤1012). The ii-th number describes the integer in the vertex ii of the right half of the graph.Each of the following mm lines contains a pair of integers uiui and vivi (1≤ui,vi≤n1≤ui,vi≤n), describing an edge between the vertex uiui of the left half and the vertex vivi of the right half. It is guaranteed that the graph does not contain multiple edges.Test case descriptions are separated with empty lines. The total value of nn across all test cases does not exceed 500000500000, and the total value of mm across all test cases does not exceed 500000500000 as well.OutputFor each test case print a single integer — the required greatest common divisor.ExampleInputCopy3 2 4 1 1 1 1 1 2 2 1 2 2 3 4 1 1 1 1 1 1 2 2 2 2 3 4 7 36 31 96 29 1 2 1 3 1 4 2 2 2 4 3 1 4 3 OutputCopy2 1 12 NoteThe greatest common divisor of a set of integers is the largest integer gg such that all elements of the set are divisible by gg.In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S)f(S) for any non-empty subset is 22, thus the greatest common divisor of these values if also equal to 22.In the second sample case the subset {1}{1} in the left half is connected to vertices {1,2}{1,2} of the right half, with the sum of numbers equal to 22, and the subset {1,2}{1,2} in the left half is connected to vertices {1,2,3}{1,2,3} of the right half, with the sum of numbers equal to 33. Thus, f({1})=2f({1})=2, f({1,2})=3f({1,2})=3, which means that the greatest common divisor of all values of f(S)f(S) is 11.
[ "graphs", "hashing", "math", "number theory" ]
import java.io.BufferedReader; import java.io.BufferedWriter; 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.List; import java.util.StringTokenizer; public class C1322C_1 { static long modulo1 = (long) 1e9; static long modulo2 = (long) 1e7; public static void main(String[] args) throws IOException { var scanner = new BufferedScanner(); var t = scanner.nextInt(); var writer = new BufferedWriter(new PrintWriter(System.out)); for (int i = 0; i < t; i++) { var n = scanner.nextInt(); var m = scanner.nextInt(); var c = new long[n + 1]; for (int j = 1; j <= n; j++) { c[j] = scanner.nextLong(); } var connectedToRight = new HashMap<Integer, List<Integer>>(); for (int j = 0; j < m; j++) { var u = scanner.nextInt(); var v = scanner.nextInt(); connectedToRight.compute(v, (k, l) -> { if (l == null) { l = new ArrayList<>(); } l.add(u); return l; }); } var hash1 = new long[n + 1]; var hash2 = new long[n + 1]; for (var entry : connectedToRight.entrySet()) { var right = entry.getKey(); var lefts = entry.getValue(); lefts.sort(Integer::compareTo); for (Integer left : lefts) { hash1[right] = hash(hash1[right], n + 1, left, modulo1); hash2[right] = hash(hash2[right], n + 1, left, modulo2); } } var rights = new ArrayList<>(connectedToRight.keySet()); rights.sort(Comparator.comparingLong(j -> hash1[(int) j]).thenComparingLong(j -> hash2[(int) j])); var j= -1; var h1 = -1L; var h2 = -1L; var ans = 0L; for (Integer right : rights) { if (hash1[right] == h1 && hash2[right] == h2) { c[j] += c[right]; } else { if (h1 >= 0) { ans = gcd(ans, c[j]); } j = right; h1 = hash1[right]; h2 = hash2[right]; } } if (h1 >= 0) { ans = gcd(ans, c[j]); } // System.out.println(ans); writer.write(String.valueOf(ans)); writer.newLine(); } writer.flush(); writer.close(); } private 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; } private static long hash(long acc, int r, int x, long modulo) { return (acc * r + x) % modulo; } 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; } } }
java
1290
B
B. Irreducible Anagramstime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputLet's call two strings ss and tt anagrams of each other if it is possible to rearrange symbols in the string ss to get a string, equal to tt.Let's consider two strings ss and tt which are anagrams of each other. We say that tt is a reducible anagram of ss if there exists an integer k≥2k≥2 and 2k2k non-empty strings s1,t1,s2,t2,…,sk,tks1,t1,s2,t2,…,sk,tk that satisfy the following conditions: If we write the strings s1,s2,…,sks1,s2,…,sk in order, the resulting string will be equal to ss; If we write the strings t1,t2,…,tkt1,t2,…,tk in order, the resulting string will be equal to tt; For all integers ii between 11 and kk inclusive, sisi and titi are anagrams of each other. If such strings don't exist, then tt is said to be an irreducible anagram of ss. Note that these notions are only defined when ss and tt are anagrams of each other.For example, consider the string s=s= "gamegame". Then the string t=t= "megamage" is a reducible anagram of ss, we may choose for example s1=s1= "game", s2=s2= "gam", s3=s3= "e" and t1=t1= "mega", t2=t2= "mag", t3=t3= "e": On the other hand, we can prove that t=t= "memegaga" is an irreducible anagram of ss.You will be given a string ss and qq queries, represented by two integers 1≤l≤r≤|s|1≤l≤r≤|s| (where |s||s| is equal to the length of the string ss). For each query, you should find if the substring of ss formed by characters from the ll-th to the rr-th has at least one irreducible anagram.InputThe first line contains a string ss, consisting of lowercase English characters (1≤|s|≤2⋅1051≤|s|≤2⋅105).The second line contains a single integer qq (1≤q≤1051≤q≤105)  — the number of queries.Each of the following qq lines contain two integers ll and rr (1≤l≤r≤|s|1≤l≤r≤|s|), representing a query for the substring of ss formed by characters from the ll-th to the rr-th.OutputFor each query, print a single line containing "Yes" (without quotes) if the corresponding substring has at least one irreducible anagram, and a single line containing "No" (without quotes) otherwise.ExamplesInputCopyaaaaa 3 1 1 2 4 5 5 OutputCopyYes No Yes InputCopyaabbbbbbc 6 1 2 2 4 2 2 1 9 5 7 3 5 OutputCopyNo Yes Yes Yes No No NoteIn the first sample; in the first and third queries; the substring is "a"; which has itself as an irreducible anagram since two or more non-empty strings cannot be put together to obtain "a". On the other hand; in the second query, the substring is "aaa", which has no irreducible anagrams: its only anagram is itself, and we may choose s1=s1= "a", s2=s2= "aa", t1=t1= "a", t2=t2= "aa" to show that it is a reducible anagram.In the second query of the second sample, the substring is "abb", which has, for example, "bba" as an irreducible anagram.
[ "binary search", "constructive algorithms", "data structures", "strings", "two pointers" ]
import java.io.*; import java.util.*; public class Anagrams { public static void main(String[] args) throws Exception { FastIO in = new FastIO(); String s = in.next(); int[][] prefix = new int[s.length()+1][26]; for (int i=0; i<s.length(); i++) { for (int j=0; j<26; j++) { prefix[i+1][j] = prefix[i][j]; } prefix[i+1][s.charAt(i)-'a']++; } int q = in.nextInt(); for (int i=0; i<q; i++) { int l = in.nextInt(); int r = in.nextInt(); if (r-l==0) in.pr.println("Yes"); else { int occ = 0; for (int j=0; j<26; j++) { if (prefix[r][j]-prefix[l-1][j]>0) occ++; } // in.pr.println(occ); if (occ>=3) in.pr.println("Yes"); else if (occ==2) { if (s.charAt(r-1)==s.charAt(l-1)) in.pr.println("No"); else in.pr.println("Yes"); } else in.pr.println("No"); } } in.pr.close(); } 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
1324
F
F. Maximum White Subtreetime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn vertices. A tree is a connected undirected graph with n−1n−1 edges. Each vertex vv of this tree has a color assigned to it (av=1av=1 if the vertex vv is white and 00 if the vertex vv is black).You have to solve the following problem for each vertex vv: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex vv? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cntwcntw white vertices and cntbcntb black vertices, you have to maximize cntw−cntbcntw−cntb.InputThe first line of the input contains one integer nn (2≤n≤2⋅1052≤n≤2⋅105) — the number of vertices in the tree.The second line of the input contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤10≤ai≤1), where aiai is the color of the ii-th vertex.Each of the next n−1n−1 lines describes an edge of the tree. Edge ii is denoted by two integers uiui and vivi, the labels of vertices it connects (1≤ui,vi≤n,ui≠vi(1≤ui,vi≤n,ui≠vi).It is guaranteed that the given edges form a tree.OutputPrint nn integers res1,res2,…,resnres1,res2,…,resn, where resiresi is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex ii.ExamplesInputCopy9 0 1 1 1 0 0 0 0 1 1 2 1 3 3 4 3 5 2 6 4 7 6 8 5 9 OutputCopy2 2 2 2 2 1 1 0 2 InputCopy4 0 0 1 0 1 2 1 3 1 4 OutputCopy0 -1 1 -1 NoteThe first example is shown below:The black vertices have bold borders.In the second example; the best subtree for vertices 2,32,3 and 44 are vertices 2,32,3 and 44 correspondingly. And the best subtree for the vertex 11 is the subtree consisting of vertices 11 and 33.
[ "dfs and similar", "dp", "graphs", "trees" ]
// package c1324; // // Codeforces Round #627 (Div. 3) 2020-03-12 05:05 // F. Maximum White Subtree // https://codeforces.com/contest/1324/problem/F // time limit per test 2 seconds; memory limit per test 256 megabytes // public class Pseudo for 'Source should satisfy regex [^{}]*public\s+(final)?\s*class\s+(\w+).*' // // You are given a tree consisting of n vertices. A tree is a connected undirected graph with n-1 // edges. Each vertex v of this tree has a color assigned to it (a_v = 1 if the vertex v is white // and 0 if the vertex v is black). // // You have to solve the following problem for each vertex v: what is the maximum difference between // the number of white and the number of black vertices you can obtain if you choose some subtree of // the given tree that the vertex v? The subtree of the tree is the connected subgraph of the given // tree. More formally, if you choose the subtree that contains cnt_w white vertices and cnt_b black // vertices, you have to maximize cnt_w - cnt_b. // // Input // // The first line of the input contains one integer n (2 <= n <= 2 * 10^5) -- the number of vertices // in the tree. // // The second line of the input contains n integers a_1, a_2, ..., a_n (0 <= a_i <= 1), where a_i is // the color of the i-th vertex. // // Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i // and v_i, the labels of vertices it connects (1 <= u_i, v_i <= n, u_i != v_i). // // It is guaranteed that the given edges form a tree. // // Output // // Print n integers res_1, res_2, ..., res_n, where res_i is the maximum possible difference between // the number of white and black vertices in some subtree that contains the vertex i. // // Example /* input: 9 0 1 1 1 0 0 0 0 1 1 2 1 3 3 4 3 5 2 6 4 7 6 8 5 9 output: 2 2 2 2 2 1 1 0 2 input: 4 0 0 1 0 1 2 1 3 1 4 output: 0 -1 1 -1 */ // Note // // The first example is shown below: // // https://espresso.codeforces.com/c9bf2c6663342bfd7b533a049ca2ba27b9f4b4df.png // // The black vertices have bold borders. // // In the second example, the best subtree for vertices 2, 3 and 4 are vertices 2, 3 and 4 // correspondingly. And the best subtree for the vertex 1 is the subtree consisting of vertices 1 // and 3. // import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Random; import java.util.StringTokenizer; public class C1324F { static final int MOD = 998244353; static final Random RAND = new Random(); static int[] solve(int[] a, int[][] edges) { int n = a.length; List<Integer>[] adjs = new ArrayList[n+1]; for (int i = 0; i < n+1; i++) { adjs[i] = new ArrayList<>(); } for (int[] edge : edges) { int u = edge[0]; int v = edge[1]; adjs[u].add(v); adjs[v].add(u); } int r = 1; int[] parent = new int[n+1]; Queue<Integer> q = new LinkedList<>(); q.add(r); while (!q.isEmpty()) { int v = q.poll(); for (int w : adjs[v]) { if (w == parent[v]) { continue; } parent[w] = v; q.add(w); } } if (test) System.out.format(" parent: %s\n", Arrays.toString(parent)); int[] subs = new int[n+1]; int[] degs = new int[n+1]; for (int i = 1; i <= n; i++) { degs[i] = adjs[i].size() - (i != 1 ? 1 : 0); if (degs[i] == 0) { q.add(i); } } while (!q.isEmpty()) { int v = q.poll(); // System.out.format(" v:%d\n", v); int sum = a[v-1] == 1 ? 1 : -1; for (int w : adjs[v]) { if (w == parent[v]) { continue; } // System.out.format(" w:%d\n", w); if (subs[w] > 0) { sum += subs[w]; } } subs[v] = sum; if (v != 1) { int p = parent[v]; degs[p]--; if (degs[p] == 0) { q.add(p); } } } if (test) System.out.format(" subs: %s\n", Arrays.toString(subs)); int[] arr = new int[n+1]; q.add(1); arr[1] = subs[1]; while (!q.isEmpty()) { int v = q.poll(); if (v == 1) { arr[1] = subs[1]; } else { int p = parent[v]; if (test) System.out.format(" v:%d p:%d subv:%2d arrp:%2d\n", v, p, subs[v], arr[p]); if (subs[v] >= 1) { // arr[p] included subs[v] arr[v] = Math.max(subs[v], arr[p]); } else { // arr[p] does not includedsubs[v] arr[v] = Math.max(subs[v], arr[p] + subs[v]); } } for (int w : adjs[v]) { if (w == parent[v]) { continue; } q.add(w); } } int[] ans = new int[n]; for (int i = 1; i <= n; i++) { ans[i-1] = arr[i]; } return ans; } static boolean test = false; static void doTest() { if (!test) { return; } long t0 = System.currentTimeMillis(); System.out.format("%d msec\n", System.currentTimeMillis() - t0); System.exit(0); } public static void main(String[] args) { doTest(); MyScanner in = new MyScanner(); int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } int[][] edges = new int[n-1][2]; for (int i = 0; i < n-1; i++) { edges[i][0] = in.nextInt(); edges[i][1] = in.nextInt(); } int[] ans = solve(a, edges); output(ans); } static void output(int[] a) { StringBuilder sb = new StringBuilder(); for (int v : a) { sb.append(v); sb.append(' '); if (sb.length() > 4000) { System.out.print(sb.toString()); sb.setLength(0); } } System.out.println(sb.toString()); } static void myAssert(boolean cond) { if (!cond) { throw new RuntimeException("Unexpected"); } } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { try { final String USERDIR = System.getProperty("user.dir"); String cname = MethodHandles.lookup().lookupClass().getCanonicalName().replace(".MyScanner", ""); cname = cname.lastIndexOf('.') > 0 ? cname.substring(cname.lastIndexOf('.') + 1) : cname; final File fin = new File(USERDIR + "/io/c" + cname.substring(1,5) + "/" + cname + ".in"); br = new BufferedReader(new InputStreamReader(fin.exists() ? new FileInputStream(fin) : System.in)); } catch (Exception e) { br = new BufferedReader(new InputStreamReader(System.in)); } } public String next() { try { while (st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
java
1286
B
B. Numbers on Treetime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputEvlampiy was gifted a rooted tree. The vertices of the tree are numbered from 11 to nn. Each of its vertices also has an integer aiai written on it. For each vertex ii, Evlampiy calculated cici — the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai. Illustration for the second example, the first integer is aiai and the integer in parentheses is ciciAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of cici, but he completely forgot which integers aiai were written on the vertices.Help him to restore initial integers!InputThe first line contains an integer nn (1≤n≤2000)(1≤n≤2000) — the number of vertices in the tree.The next nn lines contain descriptions of vertices: the ii-th line contains two integers pipi and cici (0≤pi≤n0≤pi≤n; 0≤ci≤n−10≤ci≤n−1), where pipi is the parent of vertex ii or 00 if vertex ii is root, and cici is the number of vertices jj in the subtree of vertex ii, such that aj<aiaj<ai.It is guaranteed that the values of pipi describe a rooted tree with nn vertices.OutputIf a solution exists, in the first line print "YES", and in the second line output nn integers aiai (1≤ai≤109)(1≤ai≤109). If there are several solutions, output any of them. One can prove that if there is a solution, then there is also a solution in which all aiai are between 11 and 109109.If there are no solutions, print "NO".ExamplesInputCopy3 2 0 0 2 2 0 OutputCopyYES 1 2 1 InputCopy5 0 1 1 3 2 1 3 0 2 0 OutputCopyYES 2 3 2 1 2
[ "constructive algorithms", "data structures", "dfs and similar", "graphs", "greedy", "trees" ]
//package com.company; import java.io.*; import java.math.*; import java.util.*; public class Main { public static class Task { int n; List<Integer>[] child; int[] bigger; int[] valueToVertex; int mx = 0; boolean find = true; int dfs(int u) { int valueStart = mx; for (int v: child[u]) { valueStart = Math.min(dfs(v), valueStart); } int processed = mx - valueStart; if (!find || bigger[u] > processed) { find = false; return -1; } for (int i = mx - 1; i >= valueStart + bigger[u]; i--) { valueToVertex[i + 1] = valueToVertex[i]; } mx++; valueToVertex[valueStart + bigger[u]] = u; return valueStart; } public void solve(Scanner sc, PrintWriter pw) throws IOException { n = sc.nextInt(); child = new List[n]; for (int i = 0; i < n; i++) { child[i] = new ArrayList<>(); } bigger = new int[n]; valueToVertex = new int[n + 1]; int r = -1; for (int i = 0; i < n; i++) { int p = sc.nextInt() - 1; bigger[i] = sc.nextInt(); if (p == -1) r = i; else child[p].add(i); } dfs(r); if (!find) { pw.println("NO"); return; } pw.println("YES"); int[] go = new int[n]; for (int i = 0; i < n; i++) { go[valueToVertex[i]] = i + 1; } for (int i = 0; i < n; i++) { pw.print(go[i] + " "); } 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("nondec.in")); PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out)); // PrintWriter pw = new PrintWriter(new FileOutputStream("nondec.out")); Runtime runtime = Runtime.getRuntime(); long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory(); TIME_START = System.currentTimeMillis(); Task t = new Task(); t.solve(sc, 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
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.*; public class max { public static void main(String[]args){ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0){ int n = sc.nextInt(); int []a = new int[n]; for(int i=0;i<n;i++) a[i] = sc.nextInt(); Arrays.sort(a); for(int i=n-1;i>=0;i--) System.out.print(a[i]+" "); System.out.println(); } } }
java
1316
A
A. Grade Allocationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputnn students are taking an exam. The highest possible score at this exam is mm. Let aiai be the score of the ii-th student. You have access to the school database which stores the results of all students.You can change each student's score as long as the following conditions are satisfied: All scores are integers 0≤ai≤m0≤ai≤m The average score of the class doesn't change. You are student 11 and you would like to maximize your own score.Find the highest possible score you can assign to yourself such that all conditions are satisfied.InputEach test contains multiple test cases. The first line contains the number of test cases tt (1≤t≤2001≤t≤200). The description of the test cases follows.The first line of each test case contains two integers nn and mm (1≤n≤1031≤n≤103, 1≤m≤1051≤m≤105)  — the number of students and the highest possible score respectively.The second line of each testcase contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤m0≤ai≤m)  — scores of the students.OutputFor each testcase, output one integer  — the highest possible score you can assign to yourself such that both conditions are satisfied._ExampleInputCopy2 4 10 1 2 3 4 4 5 1 2 3 4 OutputCopy10 5 NoteIn the first case; a=[1,2,3,4]a=[1,2,3,4], with average of 2.52.5. You can change array aa to [10,0,0,0][10,0,0,0]. Average remains 2.52.5, and all conditions are satisfied.In the second case, 0≤ai≤50≤ai≤5. You can change aa to [5,1,1,3][5,1,1,3]. You cannot increase a1a1 further as it will violate condition 0≤ai≤m0≤ai≤m.
[ "implementation" ]
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int test_case = in.nextInt(); int n,m; while(test_case!=0) { n= in.nextInt(); m = in.nextInt(); int[] num = new int[n]; int sum = 0; for (int i = 0; i <n; i++) { num[i] = in.nextInt(); sum += num[i]; } if(sum > m){ System.out.println(m); }else{ System.out.println(sum); } test_case--; } in.close(); } }
java
1292
A
A. NEKO's Maze Gametime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard output3R2 as DJ Mashiro - Happiness Breeze Ice - DJ Mashiro is dead or aliveNEKO#ΦωΦ has just got a new maze game on her PC!The game's main puzzle is a maze; in the forms of a 2×n2×n rectangle grid. NEKO's task is to lead a Nekomimi girl from cell (1,1)(1,1) to the gate at (2,n)(2,n) and escape the maze. The girl can only move between cells sharing a common side.However, at some moments during the game, some cells may change their state: either from normal ground to lava (which forbids movement into that cell), or vice versa (which makes that cell passable again). Initially all cells are of the ground type.After hours of streaming, NEKO finally figured out there are only qq such moments: the ii-th moment toggles the state of cell (ri,ci)(ri,ci) (either from ground to lava or vice versa).Knowing this, NEKO wonders, after each of the qq moments, whether it is still possible to move from cell (1,1)(1,1) to cell (2,n)(2,n) without going through any lava cells.Although NEKO is a great streamer and gamer, she still can't get through quizzes and problems requiring large amount of Brain Power. Can you help her?InputThe first line contains integers nn, qq (2≤n≤1052≤n≤105, 1≤q≤1051≤q≤105).The ii-th of qq following lines contains two integers riri, cici (1≤ri≤21≤ri≤2, 1≤ci≤n1≤ci≤n), denoting the coordinates of the cell to be flipped at the ii-th moment.It is guaranteed that cells (1,1)(1,1) and (2,n)(2,n) never appear in the query list.OutputFor each moment, if it is possible to travel from cell (1,1)(1,1) to cell (2,n)(2,n), print "Yes", otherwise print "No". There should be exactly qq answers, one after every update.You can print the words in any case (either lowercase, uppercase or mixed).ExampleInputCopy5 5 2 3 1 4 2 4 2 3 1 4 OutputCopyYes No No No Yes NoteWe'll crack down the example test here: After the first query; the girl still able to reach the goal. One of the shortest path ways should be: (1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5)(1,1)→(1,2)→(1,3)→(1,4)→(1,5)→(2,5). After the second query, it's impossible to move to the goal, since the farthest cell she could reach is (1,3)(1,3). After the fourth query, the (2,3)(2,3) is not blocked, but now all the 44-th column is blocked, so she still can't reach the goal. After the fifth query, the column barrier has been lifted, thus she can go to the final goal again.
[ "data structures", "dsu", "implementation" ]
import java.io.*; import java.util.*; public class A { 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[]) { if (System.getProperty("ONLINE_JUDGE") == null) { // Input is a file try { System.setIn(new FileInputStream("input.txt")); System.setOut(new PrintStream(new FileOutputStream("output.txt"))); } catch (Exception e) { System.err.println("Error"); } } else { // Input is System.in } FastReader sc = new FastReader(); // Scanner sc = new Scanner(System.in); //System.out.println(java.time.LocalTime.now()); StringBuilder sb = new StringBuilder(); // int t = sc.nextInt(); // while (t > 0) { int n = sc.nextInt(); int q = sc.nextInt(); String ans = "YES"; int count = 0; int[][] arr = new int[2][n]; for (int i = 0; i < q; i++) { int r = sc.nextInt() - 1; int c = sc.nextInt() - 1; if (arr[r][c] == 0) { if (r == 0) { if (check(arr, 1, c))count++; if (check(arr, 1, c - 1))count++; if (check(arr, 1, c + 1))count++; } else { if (check(arr, 0, c))count++; if (check(arr, 0, c - 1))count++; if (check(arr, 0, c + 1))count++; } arr[r][c] = 1; } else { if (r == 0) { if (check(arr, 1, c))count--; if (check(arr, 1, c - 1))count--; if (check(arr, 1, c + 1))count--; } else { if (check(arr, 0, c))count--; if (check(arr, 0, c - 1))count--; if (check(arr, 0, c + 1))count--; } arr[r][c] = 0; } if (count == 0)ans = "YES"; else ans = "NO"; sb.append(ans + "\n"); } // t--; // } System.out.println(sb); } public static boolean check(int[][] arr, int r, int c) { if (c < 0 || c >= arr[0].length)return false; if (arr[r][c] == 1)return true; return false; } //------------------------------------------------------------------------// class Pair implements Comparable<Pair> { int a; //first member of pair int b; //second member of pair public Pair(int a, int b) { this.a = a; this.b = b; } @Override public String toString() { return "(" + this.a + ", " + this.b + ")"; } @Override public int compareTo(Pair o) { return this.a - o.a; } } //----------------------------------------------------// public static void shuffleArray(int[] arr) { int n = arr.length; Random rnd = new Random(); for (int i = 0; i < n; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(n - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } //----------------------------------------------------// public static boolean isPowerOfTwo(long x) { return x != 0 && ((x & (x - 1)) == 0); } //----------------------------------------------------// public static long digSum(long a) { long sum = 0; while (a > 0) { sum += a % 10; a /= 10; } return sum; } //----------------------------------------------------// 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 += 6) { if (n % i == 0 || n % (i + 2) == 0)return false; } return true; } //----------------------------------------------------// public static int nextPrime(int n) { while (true) { n++; if (isPrime(n)) break; } return n; } //----------------------------------------------------// 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); } }
java
1316
C
C. Primitive Primestime limit per test1.5 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputIt is Professor R's last class of his teaching career. Every time Professor R taught a class; he gave a special problem for the students to solve. You being his favourite student, put your heart into solving it one last time.You are given two polynomials f(x)=a0+a1x+⋯+an−1xn−1f(x)=a0+a1x+⋯+an−1xn−1 and g(x)=b0+b1x+⋯+bm−1xm−1g(x)=b0+b1x+⋯+bm−1xm−1, with positive integral coefficients. It is guaranteed that the cumulative GCD of the coefficients is equal to 11 for both the given polynomials. In other words, gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1gcd(a0,a1,…,an−1)=gcd(b0,b1,…,bm−1)=1. Let h(x)=f(x)⋅g(x)h(x)=f(x)⋅g(x). Suppose that h(x)=c0+c1x+⋯+cn+m−2xn+m−2h(x)=c0+c1x+⋯+cn+m−2xn+m−2. You are also given a prime number pp. Professor R challenges you to find any tt such that ctct isn't divisible by pp. He guarantees you that under these conditions such tt always exists. If there are several such tt, output any of them.As the input is quite large, please use fast input reading methods.InputThe first line of the input contains three integers, nn, mm and pp (1≤n,m≤106,2≤p≤1091≤n,m≤106,2≤p≤109),  — nn and mm are the number of terms in f(x)f(x) and g(x)g(x) respectively (one more than the degrees of the respective polynomials) and pp is the given prime number.It is guaranteed that pp is prime.The second line contains nn integers a0,a1,…,an−1a0,a1,…,an−1 (1≤ai≤1091≤ai≤109) — aiai is the coefficient of xixi in f(x)f(x).The third line contains mm integers b0,b1,…,bm−1b0,b1,…,bm−1 (1≤bi≤1091≤bi≤109)  — bibi is the coefficient of xixi in g(x)g(x).OutputPrint a single integer tt (0≤t≤n+m−20≤t≤n+m−2)  — the appropriate power of xx in h(x)h(x) whose coefficient isn't divisible by the given prime pp. If there are multiple powers of xx that satisfy the condition, print any.ExamplesInputCopy3 2 2 1 1 2 2 1 OutputCopy1 InputCopy2 2 999999937 2 1 3 1 OutputCopy2NoteIn the first test case; f(x)f(x) is 2x2+x+12x2+x+1 and g(x)g(x) is x+2x+2, their product h(x)h(x) being 2x3+5x2+3x+22x3+5x2+3x+2, so the answer can be 1 or 2 as both 3 and 5 aren't divisible by 2.In the second test case, f(x)f(x) is x+2x+2 and g(x)g(x) is x+3x+3, their product h(x)h(x) being x2+5x+6x2+5x+6, so the answer can be any of the powers as no coefficient is divisible by the given prime.
[ "constructive algorithms", "math", "ternary search" ]
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { static int MOD = 1000000007; // After writing solution, quick scan for: // array out of bounds // special cases e.g. n=1? // npe, particularly in maps // // Big numbers arithmetic bugs: // int overflow // sorting, or taking max, after MOD void solve() throws IOException { int[] nmp = ril(3); int n = nmp[0]; int m = nmp[1]; int p = nmp[2]; int[] a = ril(n); int[] b = ril(m); // a[0]*b[0] // a[0]*b[1] + a[1]*b[0] // a[0]*b[2] + a[1]*b[1] + a[2]*b[0] // a[0]*b[3] + a[1]*b[2] + a[2]*b[1] + a[3]*b[0] // since gcd = 1 (namely, not p), then there is an element of both a and b that // are not divisible by p. interesting? // let the first not divisible by p in a be a[i]. // let the first not divisible by p in b be b[j]. int idxa = -1; for (int i = 0; i < n && idxa == -1; i++) if (a[i] % p != 0) idxa = i; int idxb = -1; for (int i = 0; i < m && idxb == -1; i++) if (b[i] % p != 0) idxb = i; pw.println(idxa + idxb); } // IMPORTANT // DID YOU CHECK THE COMMON MISTAKES ABOVE? // Template code below BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); public static void main(String[] args) throws IOException { Main m = new Main(); m.solve(); m.close(); } void close() throws IOException { pw.flush(); pw.close(); br.close(); } int ri() throws IOException { return Integer.parseInt(br.readLine().trim()); } long rl() throws IOException { return Long.parseLong(br.readLine().trim()); } int[] ril(int n) throws IOException { int[] nums = new int[n]; int c = 0; for (int i = 0; i < n; i++) { int sign = 1; c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } nums[i] = x * sign; } while (c != '\n' && c != -1) c = br.read(); return nums; } long[] rll(int n) throws IOException { long[] nums = new long[n]; int c = 0; for (int i = 0; i < n; i++) { int sign = 1; c = br.read(); long x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } nums[i] = x * sign; } while (c != '\n' && c != -1) c = br.read(); return nums; } int[] rkil() throws IOException { int sign = 1; int c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } return ril(x); } long[] rkll() throws IOException { int sign = 1; int c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } return rll(x); } char[] rs() throws IOException { return br.readLine().toCharArray(); } void sort(int[] A) { Random r = new Random(); for (int i = A.length-1; i > 0; i--) { int j = r.nextInt(i+1); int temp = A[i]; A[i] = A[j]; A[j] = temp; } Arrays.sort(A); } void printDouble(double d) { pw.printf("%.16f", d); } }
java
1304
B
B. Longest Palindrometime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputReturning back to problem solving; Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has nn distinct strings of equal length mm. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.InputThe first line contains two integers nn and mm (1≤n≤1001≤n≤100, 1≤m≤501≤m≤50) — the number of strings and the length of each string.Next nn lines contain a string of length mm each, consisting of lowercase Latin letters only. All strings are distinct.OutputIn the first line, print the length of the longest palindrome string you made.In the second line, print that palindrome. If there are multiple answers, print any one of them. If the palindrome is empty, print an empty line or don't print this line at all.ExamplesInputCopy3 3 tab one bat OutputCopy6 tabbat InputCopy4 2 oo ox xo xx OutputCopy6 oxxxxo InputCopy3 5 hello codef orces OutputCopy0 InputCopy9 4 abab baba abcd bcde cdef defg wxyz zyxw ijji OutputCopy20 ababwxyzijjizyxwbaba NoteIn the first example; "battab" is also a valid answer.In the second example; there can be 4 different valid answers including the sample output. We are not going to provide any hints for what the others are.In the third example; the empty string is the only valid palindrome string.
[ "brute force", "constructive algorithms", "greedy", "implementation", "strings" ]
import java.io.IOException; import java.util.*; import java.util.function.IntUnaryOperator; import java.util.function.UnaryOperator; import java.util.stream.Collectors; public class Main { public static Scanner in = new Scanner(System.in); Map<String,Integer>m=new HashMap<>(); public static boolean canConstruct(String target,String[]wordBank) { boolean []arr=new boolean[target.length()+1]; arr[0]=true; for(int i=0;i<arr.length;i++) { if(arr[i]) for(String word:wordBank) { int end=word.length()+i; if(end<=target.length()) if(target.substring(i,end).equals(word)) arr[i+word.length()]=true; if(arr[target.length()]) return true; } } return false; } public static int Max=0; public static int MaxRoot(int n,int m,int [][]arr) { if(n==arr.length||m==arr[0].length) return -1000000; if(n==arr.length-1&&m==arr[0].length-1) return arr[n][m]; return arr[n][m]+Math.max(MaxRoot(n+1,m,arr),MaxRoot(n,m+1,arr)); } public static String reverse(String s) { String rev=""; for(int i=s.length()-1;i>=0;i--) { rev+=s.charAt(i); } return rev; } public static void main(String[] args) { int n=in.nextInt(),m=in.nextInt(); in.nextLine(); String []str=new String[n]; String []rev=new String [n]; for(int i=0;i<n;i++){ str[i]=in.nextLine(); rev[i]=reverse(str[i]); } String ans=""; for(int i=0;i<n;i++) if(str[i].equals(rev[i])) {ans+=str[i];break;} for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { if(str[i].equals(rev[j])&&i!=j) {ans=str[i]+ans+rev[i];break;} } } System.out.println(ans.length()+"\n"+ans); } }
java
1312
B
B. Bogosorttime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array a1,a2,…,ana1,a2,…,an. Array is good if for each pair of indexes i<ji<j the condition j−aj≠i−aij−aj≠i−ai holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).For example, if a=[1,1,3,5]a=[1,1,3,5], then shuffled arrays [1,3,5,1][1,3,5,1], [3,5,1,1][3,5,1,1] and [5,3,1,1][5,3,1,1] are good, but shuffled arrays [3,1,5,1][3,1,5,1], [1,1,3,5][1,1,3,5] and [1,1,5,3][1,1,5,3] aren't.It's guaranteed that it's always possible to shuffle an array to meet this condition.InputThe first line contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.The first line of each test case contains one integer nn (1≤n≤1001≤n≤100) — the length of array aa.The second line of each test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1001≤ai≤100).OutputFor each test case print the shuffled version of the array aa which is good.ExampleInputCopy3 1 7 4 1 1 3 5 6 3 2 1 5 6 4 OutputCopy7 1 5 1 3 2 4 6 1 3 5
[ "constructive algorithms", "sortings" ]
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter out=new PrintWriter(System.out); Scanner sc=new Scanner(System.in); // String testcases[]=br.readLine().split(" "); // int t=Integer.parseInt(testcases[0]); int t=sc.nextInt(); for(int i=0;i<t;i++) { int n=sc.nextInt(); int a[]=new int[n]; for(int j=0;j<n;j++) a[j]=sc.nextInt(); sort(a); for(int j=n-1;j>=0;j--) System.out.print(a[j]+" "); System.out.println(); } } // static int gcd(int a, int b) { // return b==0?a:gcd(b, a%b); // } 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 boolean coprime(int a, int b) { // if(a==1||b==1) // return true; // if ( __gcd(a, b) == 1) // return true; // else // return false; // } // private static boolean checkSquare(long n) // { // if (Math.ceil((double)Math.sqrt(n)) == // Math.floor((double)Math.sqrt(n))) // return true; // else // return false; // } // private static long floorSqrt(long x) // { // if (x == 0 || x == 1) // return x; // long start = 1, end = x / 2, ans = 0; // while (start <= end) { // long mid = (start + end) / 2; // if (mid * mid == x) // return (int)mid; // if (mid * mid < x) { // start = mid + 1; // ans = mid; // } // else // end = mid - 1; // } // return (long)ans; // } }
java
1324
B
B. Yet Another Palindrome Problemtime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given an array aa consisting of nn integers.Your task is to determine if aa has some subsequence of length at least 33 that is a palindrome.Recall that an array bb is called a subsequence of the array aa if bb can be obtained by removing some (possibly, zero) elements from aa (not necessarily consecutive) without changing the order of remaining elements. For example, [2][2], [1,2,1,3][1,2,1,3] and [2,3][2,3] are subsequences of [1,2,1,3][1,2,1,3], but [1,1,2][1,1,2] and [4][4] are not.Also, recall that a palindrome is an array that reads the same backward as forward. In other words, the array aa of length nn is the palindrome if ai=an−i−1ai=an−i−1 for all ii from 11 to nn. For example, arrays [1234][1234], [1,2,1][1,2,1], [1,3,2,2,3,1][1,3,2,2,3,1] and [10,100,10][10,100,10] are palindromes, but arrays [1,2][1,2] and [1,2,3,1][1,2,3,1] are not.You have to answer tt independent test cases.InputThe first line of the input contains one integer tt (1≤t≤1001≤t≤100) — the number of test cases.Next 2t2t lines describe test cases. The first line of the test case contains one integer nn (3≤n≤50003≤n≤5000) — the length of aa. The second line of the test case contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤n1≤ai≤n), where aiai is the ii-th element of aa.It is guaranteed that the sum of nn over all test cases does not exceed 50005000 (∑n≤5000∑n≤5000).OutputFor each test case, print the answer — "YES" (without quotes) if aa has some subsequence of length at least 33 that is a palindrome and "NO" otherwise.ExampleInputCopy5 3 1 2 1 5 1 2 2 3 2 3 1 1 2 4 1 2 2 1 10 1 1 2 2 3 3 4 4 5 5 OutputCopyYES YES NO YES NO NoteIn the first test case of the example; the array aa has a subsequence [1,2,1][1,2,1] which is a palindrome.In the second test case of the example, the array aa has two subsequences of length 33 which are palindromes: [2,3,2][2,3,2] and [2,2,2][2,2,2].In the third test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.In the fourth test case of the example, the array aa has one subsequence of length 44 which is a palindrome: [1,2,2,1][1,2,2,1] (and has two subsequences of length 33 which are palindromes: both are [1,2,1][1,2,1]).In the fifth test case of the example, the array aa has no subsequences of length at least 33 which are palindromes.
[ "brute force", "strings" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.StringTokenizer; public class PalindromeProb { 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 list = new int[n]; st = new StringTokenizer(r.readLine()); for (int j = 0; j < n; j++) { list[j] = Integer.parseInt(st.nextToken()); } var hashMap = new HashMap<Integer, Integer>(); var check = false; for (int j = 0; j < list.length; j++) { var last = hashMap.get(list[j]); if (last != null) { if (j - last > 1) { System.out.println("YES"); check = true; break; } continue; } hashMap.put(list[j], j); } if (!check) { System.out.println("NO"); } } } }
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.io.*; public class D{ static FastScanner fs = null; public static void main(String[] args) { fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int t = 1; while(t-->0){ int n = fs.nextInt(); long a = fs.nextLong(); long b = fs.nextLong(); long k = fs.nextLong(); long hei[] = new long[n]; for(int i=0;i<n;i++){ hei[i] = fs.nextLong(); } long sum = a+b; for(int i=0;i<n;i++){ long d = hei[i]%sum; if(d==(long)0) d = sum; long z = d/a; if(d%a!=(long)0) z+=1; z-=(long)1; hei[i] = z; } int c = 0; long ans = 0; Arrays.sort(hei); for(int i=0;i<n;i++){ k-=hei[i]; c++; // out.println(i+" "+k+" "+c); if(k<0){ c-=1; break; } } ans = c; out.println(ans); } out.close(); } 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 class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
java
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 Task1288A { public static void main(String[] args) { Scanner in = new Scanner(System.in); int par = Integer.parseInt(in.nextLine()); int[][] value = new int[par][2]; for (int i = 0; i < par; i++) { value[i] = parser(in.nextLine()); } for (int i = 0; i < par; i++) { System.out.println(task(value[i])); } } public static int[] parser(String str) { String[] strArr = str.split(" "); int[] numArr = new int[strArr.length]; for (int i = 0; i < strArr.length; i++) { numArr[i] = Integer.parseInt(strArr[i]); } return numArr; } public static String task(int[] value) { if (value[0] >= value[1]) { return "YES"; } int i = value[0]; while (i != 0 && i + Math.ceil((double) value[1] / (i + 1)) > value[0]) { i /= 2; } if (i > 0) { return "YES"; } else { return "NO"; } } }
java
1290
A
A. Mind Controltime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou and your n−1n−1 friends have found an array of integers a1,a2,…,ana1,a2,…,an. You have decided to share it in the following way: All nn of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for himself. He then gets out of line, and the next person in line continues the process.You are standing in the mm-th position in the line. Before the process starts, you may choose up to kk different people in the line, and persuade them to always take either the first or the last element in the array on their turn (for each person his own choice, not necessarily equal for all people), no matter what the elements themselves are. Once the process starts, you cannot persuade any more people, and you cannot change the choices for the people you already persuaded.Suppose that you're doing your choices optimally. What is the greatest integer xx such that, no matter what are the choices of the friends you didn't choose to control, the element you will take from the array will be greater than or equal to xx?Please note that the friends you don't control may do their choice arbitrarily, and they will not necessarily take the biggest element available.InputThe input consists of multiple test cases. The first line contains a single integer tt (1≤t≤10001≤t≤1000)  — the number of test cases. The description of the test cases follows.The first line of each test case contains three space-separated integers nn, mm and kk (1≤m≤n≤35001≤m≤n≤3500, 0≤k≤n−10≤k≤n−1)  — the number of elements in the array, your position in line and the number of people whose choices you can fix.The second line of each test case contains nn positive integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109)  — elements of the array.It is guaranteed that the sum of nn over all test cases does not exceed 35003500.OutputFor each test case, print the largest integer xx such that you can guarantee to obtain at least xx.ExampleInputCopy4 6 4 2 2 9 2 3 8 5 4 4 1 2 13 60 4 4 1 3 1 2 2 1 2 2 0 1 2 OutputCopy8 4 1 1 NoteIn the first test case; an optimal strategy is to force the first person to take the last element and the second person to take the first element. the first person will take the last element (55) because he or she was forced by you to take the last element. After this turn the remaining array will be [2,9,2,3,8][2,9,2,3,8]; the second person will take the first element (22) because he or she was forced by you to take the first element. After this turn the remaining array will be [9,2,3,8][9,2,3,8]; if the third person will choose to take the first element (99), at your turn the remaining array will be [2,3,8][2,3,8] and you will take 88 (the last element); if the third person will choose to take the last element (88), at your turn the remaining array will be [9,2,3][9,2,3] and you will take 99 (the first element). Thus, this strategy guarantees to end up with at least 88. We can prove that there is no strategy that guarantees to end up with at least 99. Hence, the answer is 88.In the second test case, an optimal strategy is to force the first person to take the first element. Then, in the worst case, both the second and the third person will take the first element: you will end up with 44.
[ "brute force", "data structures", "implementation" ]
// have faith in yourself!!!!! /* Naive mistakes in java : --> Arrays.sort(primitive) is O(n^2) --> Never use '=' to compare to Integer data types, instead use 'equals()' --> -4 % 3 = -1, actually it should be 2, so add '+n' to modulo result */ import java.io.*; import java.util.*; public class CodeForces { public static void main(String[] args) throws IOException { openIO(); int testCase = 1; testCase = sc. nextInt(); for (int i = 1; i <= testCase; i++) solve(i); closeIO(); } /*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*/ public static void solve(int tCase) throws IOException { int n = sc.nextInt(); int m = sc.nextInt(); int k = Math.min(sc.nextInt(),m-1); int[] arr = new int[n+1]; for(int i=1;i<=n;i++)arr[i] = sc.nextInt(); int ans = 0; for(int x = 0;x<=k;x++){ int l = x+1; int r = n - (k - x); int curr = inf_int; for(int y = 0;y<=m - k - 1;y++){ int ll = l + y; int rr = r - (m-k-1-y); curr = Math.min(Math.max(arr[ll],arr[rr]),curr); } ans = Math.max(ans,curr); } out.println(ans); } /*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/ public static int mod = (int) 1e9 + 7; // public static int mod = 998244353; public static int inf_int = (int) 2e9; public static long inf_long = (long) 2e18; public static void _sort(int[] arr, boolean isAscending) { int n = arr.length; List<Integer> list = new ArrayList<>(); for (int ele : arr) list.add(ele); Collections.sort(list); if (!isAscending) Collections.reverse(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } public static void _sort(long[] arr, boolean isAscending) { int n = arr.length; List<Long> list = new ArrayList<>(); for (long ele : arr) list.add(ele); Collections.sort(list); if (!isAscending) Collections.reverse(list); for (int i = 0; i < n; i++) arr[i] = list.get(i); } // time : O(1), space : O(1) public static int _digitCount(long num,int base){ // this will give the # of digits needed for a number num in format : base return (int)(1 + Math.log(num)/Math.log(base)); } // time : O(n), space: O(n) public static long _fact(int n){ // simple factorial calculator long ans = 1; for(int i=2;i<=n;i++) ans = ans * i % mod; return ans; } // time for pre-computation of factorial and inverse-factorial table : O(nlog(mod)) public static long[] factorial , inverseFact; public static void _ncr_precompute(int n){ factorial = new long[n+1]; inverseFact = new long[n+1]; factorial[0] = inverseFact[0] = 1; for (int i = 1; i <=n; i++) { factorial[i] = (factorial[i - 1] * i) % mod; inverseFact[i] = _power(factorial[i], mod - 2); } } // time of factorial calculation after pre-computation is O(1) public static int _ncr(int n,int r){ if(r > n)return 0; return (int)(factorial[n] * inverseFact[r] % mod * inverseFact[n - r] % mod); } public static int _npr(int n,int r){ if(r > n)return 0; return (int)(factorial[n] * inverseFact[n - r] % mod); } // euclidean algorithm time O(max (loga ,logb)) public static long _gcd(long a, long b) { if (a == 0) return b; return _gcd(b % a, a); } // lcm(a,b) * gcd(a,b) = a * b public static long _lcm(long a, long b) { return (a / _gcd(a, b)) * b; } // binary exponentiation time O(logn) public static long _power(long x, long n) { long ans = 1; while (n > 0) { if ((n & 1) == 1) { ans *= x; ans %= mod; n--; } else { x *= x; x %= mod; n >>= 1; } } return ans; } //sieve or first divisor time : O(mx * log ( log (mx) ) ) public static int[] _seive(int mx){ int[] firstDivisor = new int[mx+1]; for(int i=0;i<=mx;i++)firstDivisor[i] = i; for(int i=2;i*i<=mx;i++) if(firstDivisor[i] == i) for(int j = i*i;j<=mx;j+=i) firstDivisor[j] = i; return firstDivisor; } // check if x is a prime # of not. time : O( n ^ 1/2 ) private static boolean _isPrime(long x){ for(long i=2;i*i<=x;i++) if(x%i==0)return false; return true; } static class Pair<K, V>{ K ff; V ss; public Pair(K ff, V ss) { this.ff = ff; this.ss = ss; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || this.getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; return ff.equals(pair.ff) && ss.equals(pair.ss); } @Override public int hashCode() { return Objects.hash(ff, ss); } } static FastestReader sc; static PrintWriter out; private static void openIO() throws IOException { sc = new FastestReader(); out = new PrintWriter(System.out); } /*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/ public static void closeIO() throws IOException { out.flush(); out.close(); sc.close(); } private static final class FastestReader { private static final int BUFFER_SIZE = 1 << 16; private final DataInputStream din; private final byte[] buffer; private int bufferPointer, bytesRead; public FastestReader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public FastestReader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() throws IOException { int b; //noinspection StatementWithEmptyBody while ((b = read()) != -1 && isSpaceChar(b)) { } return b; } public String next() throws IOException { int b = skip(); final StringBuilder sb = new StringBuilder(); while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = read(); } return sb.toString(); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } final 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(); } final 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(); } final 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 { din.close(); } } /*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*/ }
java
1315
C
C. Restoring Permutationtime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a sequence b1,b2,…,bnb1,b2,…,bn. Find the lexicographically minimal permutation a1,a2,…,a2na1,a2,…,a2n such that bi=min(a2i−1,a2i)bi=min(a2i−1,a2i), or determine that it is impossible.InputEach test contains one or more test cases. The first line contains the number of test cases tt (1≤t≤1001≤t≤100).The first line of each test case consists of one integer nn — the number of elements in the sequence bb (1≤n≤1001≤n≤100).The second line of each test case consists of nn different integers b1,…,bnb1,…,bn — elements of the sequence bb (1≤bi≤2n1≤bi≤2n).It is guaranteed that the sum of nn by all test cases doesn't exceed 100100.OutputFor each test case, if there is no appropriate permutation, print one number −1−1.Otherwise, print 2n2n integers a1,…,a2na1,…,a2n — required lexicographically minimal permutation of numbers from 11 to 2n2n.ExampleInputCopy5 1 1 2 4 1 3 4 1 3 4 2 3 4 5 5 1 5 7 2 8 OutputCopy1 2 -1 4 5 1 2 3 6 -1 1 3 5 6 7 9 2 4 8 10
[ "greedy" ]
/* Rating: 1367 Date: 24-11-2021 Time: 02-46-55 Author: Kartik Papney Linkedin: https://www.linkedin.com/in/kartik-papney-4951161a6/ Leetcode: https://leetcode.com/kartikpapney/ Codechef: https://www.codechef.com/users/kartikpapney */ import java.util.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class C_Restoring_Permutation { public static void s() { PriorityQueue<Integer> pq = new PriorityQueue<>(); int n = sc.nextInt(); int[] b = sc.readArray(n); boolean[] check = new boolean[2*n]; for(int val : b) { check[val-1] = true; } for(int i=0; i<check.length; i++) { if(!check[i]) pq.add(i+1); } HashMap<Integer, Integer> map = new HashMap<>(); for(int i=0; i<b.length; i++) { ArrayList<Integer> arr = new ArrayList<>(); while(!pq.isEmpty() && pq.peek() < b[i]) { arr.add(pq.poll()); } if(pq.isEmpty()) { p.writeln(-1); return; } else { map.put(b[i], pq.poll()); for(int val : arr) pq.add(val); } } for(int val : b) { p.writes(val + " " + map.get(val)); } p.writeln(); } public static void main(String[] args) { int t = 1; t = sc.nextInt(); while (t-- != 0) { s(); } p.print(); } static final Integer MOD = (int) 1e9 + 7; static final FastReader sc = new FastReader(); static final Print p = new Print(); static class Functions { 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 max(int[] a) { int max = Integer.MIN_VALUE; for (int val : a) max = Math.max(val, max); return max; } static int min(int[] a) { int min = Integer.MAX_VALUE; for (int val : a) min = Math.min(val, min); return min; } static long min(long[] a) { long min = Long.MAX_VALUE; for (long val : a) min = Math.min(val, min); return min; } static long max(long[] a) { long max = Long.MIN_VALUE; for (long val : a) max = Math.max(val, max); return max; } static long sum(long[] a) { long sum = 0; for (long val : a) sum += val; return sum; } static int sum(int[] a) { int sum = 0; for (int val : a) sum += val; return sum; } public static long mod_add(long a, long b) { return (a % MOD + b % MOD + MOD) % MOD; } public static long pow(long a, long b) { long res = 1; while (b > 0) { if ((b & 1) != 0) res = mod_mul(res, a); a = mod_mul(a, a); b >>= 1; } return res; } public static long mod_mul(long a, long b) { long res = 0; a %= MOD; while (b > 0) { if ((b & 1) > 0) { res = mod_add(res, a); } a = (2 * a) % MOD; b >>= 1; } return res; } public static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } public static long factorial(long n) { long res = 1; for (int i = 1; i <= n; i++) { res = (i % MOD * res % MOD) % MOD; } return res; } public static int count(int[] arr, int x) { int count = 0; for (int val : arr) if (val == x) count++; return count; } public static ArrayList<Integer> generatePrimes(int n) { boolean[] primes = new boolean[n]; for (int i = 2; i < primes.length; i++) primes[i] = true; for (int i = 2; i < primes.length; i++) { if (primes[i]) { for (int j = i * i; j < primes.length; j += i) { primes[j] = false; } } } ArrayList<Integer> arr = new ArrayList<>(); for (int i = 0; i < primes.length; i++) { if (primes[i]) arr.add(i); } return arr; } } static class Print { StringBuffer strb = new StringBuffer(); public void write(Object str) { strb.append(str); } public void writes(Object str) { char c = ' '; strb.append(str).append(c); } public void writeln(Object str) { char c = '\n'; strb.append(str).append(c); } public void writeln() { char c = '\n'; strb.append(c); } public void writes(int[] arr) { for (int val : arr) { write(val); write(' '); } } public void writes(long[] arr) { for (long val : arr) { write(val); write(' '); } } public void writeln(int[] arr) { for (int val : arr) { writeln(val); } } public void print() { System.out.print(strb); } public void println() { System.out.println(strb); } } 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[] 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; } double[] readArrayDouble(int n) { double[] a = new double[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } String nextLine() { String str = new String(); try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
java
1141
F2
F2. Same Sum Blocks (Hard)time limit per test3 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputThis problem is given in two editions; which differ exclusively in the constraints on the number nn.You are given an array of integers a[1],a[2],…,a[n].a[1],a[2],…,a[n]. A block is a sequence of contiguous (consecutive) elements a[l],a[l+1],…,a[r]a[l],a[l+1],…,a[r] (1≤l≤r≤n1≤l≤r≤n). Thus, a block is defined by a pair of indices (l,r)(l,r).Find a set of blocks (l1,r1),(l2,r2),…,(lk,rk)(l1,r1),(l2,r2),…,(lk,rk) such that: They do not intersect (i.e. they are disjoint). Formally, for each pair of blocks (li,ri)(li,ri) and (lj,rj(lj,rj) where i≠ji≠j either ri<ljri<lj or rj<lirj<li. For each block the sum of its elements is the same. Formally, a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]=a[l1]+a[l1+1]+⋯+a[r1]=a[l2]+a[l2+1]+⋯+a[r2]= ⋯=⋯= a[lk]+a[lk+1]+⋯+a[rk].a[lk]+a[lk+1]+⋯+a[rk]. The number of the blocks in the set is maximum. Formally, there does not exist a set of blocks (l′1,r′1),(l′2,r′2),…,(l′k′,r′k′)(l1′,r1′),(l2′,r2′),…,(lk′′,rk′′) satisfying the above two requirements with k′>kk′>k. The picture corresponds to the first example. Blue boxes illustrate blocks. Write a program to find such a set of blocks.InputThe first line contains integer nn (1≤n≤15001≤n≤1500) — the length of the given array. The second line contains the sequence of elements a[1],a[2],…,a[n]a[1],a[2],…,a[n] (−105≤ai≤105−105≤ai≤105).OutputIn the first line print the integer kk (1≤k≤n1≤k≤n). The following kk lines should contain blocks, one per line. In each line print a pair of indices li,rili,ri (1≤li≤ri≤n1≤li≤ri≤n) — the bounds of the ii-th block. You can print blocks in any order. If there are multiple answers, print any of them.ExamplesInputCopy7 4 1 2 2 1 5 3 OutputCopy3 7 7 2 3 4 5 InputCopy11 -5 -4 -3 -2 -1 0 1 2 3 4 5 OutputCopy2 3 4 1 1 InputCopy4 1 1 1 1 OutputCopy4 4 4 1 1 2 2 3 3
[ "data structures", "greedy" ]
import java.io.*; import java.util.ArrayDeque; import java.util.HashMap; import java.util.StringTokenizer; /** * * @author zhengnaishan * * @date 2023/2/9 9:15 */ public class CF1141 { public static void main(String[] args) { //前缀和最后出现的位置 HashMap<Long, ArrayDeque<int[]>> map = new HashMap<>(); Kattio io = new Kattio(); int n = io.nextInt(); int[] a = new int[n]; ArrayDeque<int[]> maxQueue = null; for (int i = 0; i < n; i++) { a[i] = io.nextInt(); long sum = 0; for (int j = i; j >= 0; j--) { sum += a[j]; ArrayDeque<int[]> queue = map.computeIfAbsent(sum, v -> new ArrayDeque<>()); if (queue.isEmpty() || queue.peek()[1] < j) { queue.push(new int[]{j, i}); if (maxQueue == null || queue.size() > maxQueue.size()) { maxQueue = queue; } } } } io.println(maxQueue.size()); for (int[] c : maxQueue) io.println(c[0] + 1 + " " + (c[1] + 1)); io.flush(); } public static class Kattio extends PrintWriter { private BufferedReader r; private StringTokenizer st; // 标准 IO public Kattio() { this(System.in, System.out); } public Kattio(InputStream i, OutputStream o) { super(o); r = new BufferedReader(new InputStreamReader(i)); } // 文件 IO public Kattio(String intput, String output) throws IOException { super(output); r = new BufferedReader(new FileReader(intput)); } // 在没有其他输入时返回 null public String next() { try { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(r.readLine()); return st.nextToken(); } catch (Exception e) { } return null; } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public long nextLong() { return Long.parseLong(next()); } } }
java
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" ]
//package Codeforce; import java.util.Scanner; public class TwoRegularPolygons { public static void main(String[] args) { Scanner input = new Scanner(System.in); int test = input.nextInt(); while (test-- > 0){ int n = input.nextInt(),m = input.nextInt(); System.out.println((n%m == 0)?"YES":"NO"); } } }
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.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.AbstractMap; import java.util.Arrays; import java.util.InputMismatchException; import java.util.Map; import java.util.TreeMap; /** * 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); DNewYearAndConference solver = new DNewYearAndConference(); solver.solve(1, in, out); out.close(); } } public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", Runtime.getRuntime().freeMemory() >> 1L); thread.start(); thread.join(); } static class DNewYearAndConference { int n; public DNewYearAndConference() { } public boolean valid(int[][] a, int[][] b) { int[][] events = new int[n<<1][2]; for(int i = 0, ind = 0; i<n; i++) { events[ind++] = new int[] {a[i][0], i+1}; events[ind++] = new int[] {a[i][1], -i-1}; } Arrays.sort(events, (o1, o2) -> { if(o1[0]==o2[0]) { return o2[1]-o1[1]; } return o1[0]-o2[0]; }); TreeMap<DNewYearAndConference.Segment, Integer> start = new TreeMap<>((o1, o2) -> { if(o1.l==o2.l) { return o1.r-o2.r; } return o1.l-o2.l; }), end = new TreeMap<>((o1, o2) -> { if(o1.r==o2.r) { return o1.l-o2.l; } return o1.r-o2.r; }); for(int[] event: events) { int ind = Math.abs(event[1])-1; DNewYearAndConference.Segment s = new DNewYearAndConference.Segment(b[ind]); if(event[1]<0) { int count = start.get(s); if(count>1) { start.put(s, count-1); end.put(s, count-1); }else { start.remove(s); end.remove(s); } }else { if(!start.isEmpty()&&(end.firstKey().r<s.l||start.lastKey().l>s.r)) { return false; } start.put(s, start.getOrDefault(s, 0)+1); end.put(s, end.getOrDefault(s, 0)+1); } } return true; } public void solve(int kase, InputReader in, Output pw) { n = in.nextInt(); int[][] a = new int[n][2], b = new int[n][2]; for(int i = 0; i<n; i++) { a[i] = new int[] {in.nextInt(), in.nextInt()}; b[i] = new int[] {in.nextInt(), in.nextInt()}; } if(valid(a, b)&&valid(b, a)) { pw.println("YES"); }else { pw.println("NO"); } } static class Segment { int l; int r; public Segment(int[] arr) { this.l = arr[0]; this.r = arr[1]; } public String toString() { return String.format("Segment{%d %d}", l, r); } } } static class Output implements Closeable, Flushable { public StringBuilder sb; public OutputStream os; public int BUFFER_SIZE; public boolean autoFlush; 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); autoFlush = false; LineSeparator = System.lineSeparator(); } public void println(String s) { sb.append(s); println(); if(autoFlush) { flush(); }else if(sb.length()>BUFFER_SIZE >> 1) { flushToBuffer(); } } 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 interface InputReader { int nextInt(); } 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++]; } } }
java
1325
C
C. Ehab and Path-etic MEXstime limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard outputYou are given a tree consisting of nn nodes. You want to write some labels on the tree's edges such that the following conditions hold: Every label is an integer between 00 and n−2n−2 inclusive. All the written labels are distinct. The largest value among MEX(u,v)MEX(u,v) over all pairs of nodes (u,v)(u,v) is as small as possible. Here, MEX(u,v)MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node uu to node vv.InputThe first line contains the integer nn (2≤n≤1052≤n≤105) — the number of nodes in the tree.Each of the next n−1n−1 lines contains two space-separated integers uu and vv (1≤u,v≤n1≤u,v≤n) that mean there's an edge between nodes uu and vv. It's guaranteed that the given graph is a tree.OutputOutput n−1n−1 integers. The ithith of them will be the number written on the ithith edge (in the input order).ExamplesInputCopy3 1 2 1 3 OutputCopy0 1 InputCopy6 1 2 1 3 2 4 2 5 5 6 OutputCopy0 3 2 4 1NoteThe tree from the second sample:
[ "constructive algorithms", "dfs and similar", "greedy", "trees" ]
import 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_Ehab_and_Path_etic_MEXs { 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 edge[][] = new int[n-1][2]; int degree[] = new int[n+1]; for(int i = 0; i < n-1; i++) { edge[i][0] = f.nextInt(); edge[i][1] = f.nextInt(); degree[edge[i][0]]++; degree[edge[i][1]]++; } int edgeNum[] = new int[n-1]; Arrays.fill(edgeNum, -1); int num = 0; for(int i = 0; i < edge.length; i++) { if(degree[edge[i][0]] == 1 || degree[edge[i][1]] == 1) { edgeNum[i] = num; num++; } } for(int i = 0; i < edge.length; i++) { if(edgeNum[i] == -1) { edgeNum[i] = num; num++; } } for(int i: edgeNum) { out.println(i); } } // 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
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.io.*; import java.util.*; public class M { public static void main(String[] args) { FastScanner x = new FastScanner(); Integer t = x.nextInt(); while (t-- > 0){ Long max = (long) Integer.MIN_VALUE; Long min = (long)Integer.MAX_VALUE; Long res = 0L; boolean boo = true; int co = 0; Integer n = x.nextInt(); Long[] arr = new Long[n]; Long sum = 0L; for (int i = 0; i < n; i++) { arr[i] = x.nextLong(); sum += arr[i]; if (sum < 1){ boo = false; } } sum = 0L; for (int i = n - 1; i >= 0 ; i--) { sum += arr[i]; if (sum < 1){ boo = false; } } if (boo){ System.out.println("YES"); }else{ System.out.println("NO"); } } }static Long getmax(Long[] arr){ Long max = (long) Integer.MIN_VALUE; for (int i = 0; i < arr.length; i++) { max = Math.max(max,arr[i]); }return max; } static String getter(String s, int ind,int len){ char a1 = s.charAt(ind); char a2 = s.charAt(len); StringBuilder res = new StringBuilder(); for (int i = 0; i < s.length(); i++) { if (i == ind){ res.append(a2); } else if (i == len) { res.append(a1); }else{ res.append(s.charAt(i)); } } return res.toString(); } static int shift(Integer[] arr,int l,int r,int k){ Integer[] sarr = new Integer[arr.length]; for (int i = 0; i < arr.length; i++) { sarr[i] = arr[i]; } for (int i = 0; i < k; i++) { for (int j = l - 1; j < r - 1; j++) { arr[j + 1] = arr[j]; } System.out.println(Arrays.toString(arr)); } return arr[arr.length - 1] - arr[0]; } static int lowerbound(Long[] arr,Long target){ if(arr == null || arr.length == 0){ return -1; } int l = 0; int r = arr.length - 1; while (l < r){ int mid = (l + r) / 2; if (arr[mid] < target){ l = mid + 1; }else{ r = mid; } } if (arr[l] >= target){ return l; } return -1; } static int upperbound(Long[] arr,Long target){ if (arr == null || arr.length == 0){ return -1; } int l = 0; int r = arr.length - 1; while (l < r){ int mid = (l + r) / 2; if (arr[mid] <= target){ l = mid + 1; }else { r = mid; } } return arr[l] > target ? l : -1; } public static void rec(int N,String cur) { if (cur.length() == N) { System.out.println(cur); return; } rec(N, cur + "0"); rec(N, cur + "1"); } public static int intfromstring(String s){ String[] nums = {"zero","one","two","three","four","five","six","seven","eight","nine","ten"}; for (int i = 0; i < nums.length; i++) { if (s.equals(nums[i])){ return i; } }return -1; } public static long NOK(long a,long b){ return lcm(a,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; } public static long sum(long a){ return a * (a - 1) / 2; } static boolean odd(int e){ return e % 2 == 1; }static boolean even(int e){ return e % 2 == 0; } 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; }static String arrtostring(long res[]){ return Arrays.toString(res).replace(",","").replace("[","").replace("]",""); } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextLine() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextLine()); } long nextLong() { return Long.parseLong(nextLine()); } double nextDouble() { return Double.parseDouble(nextLine()); } Integer[] readArray(int n) { Integer[] a=new Integer[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; } } }
java